Corejava 1
Corejava 1
Corejava 1
Ans:
Ans:
Skarifahmed@gmail.com
2
The JVM runtime executes .class or .jar files, emulating the JVM instruction
set by interpreting it, or using a just-in-time compiler (JIT) such as Sun's
HotSpot. JIT compiling, not interpreting, is used in most JVMs today to
achieve greater speed. Ahead-of-time compilers that enable the developer to
precompile class files into native code for a particular platform also exist.
Like most virtual machines, the Java Virtual Machine has a stack-based
architecture.
The JVM, which is the instance of the JRE (Java Runtime Environment), comes
into action when a Java program is executed. When execution is complete,
this instance is garbage-collected. JIT is the part of the JVM that is used to
speed up the execution time. JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the amount of time
needed for compilation.
Ans:
The Java Virtual Machine Specification, by Tim Lindholm and Frank Yellin,
outlines what determines a JVM . The specification defines three
components:
Firstly, the JVM must accept bytecode instructions. Bytecodes define the
instruction set that executes the user‘s application program . Each of
the JVM ‘s stack-based instructions consist of a one-byte *opcode
immediately followed by zero or more operands. The JVM ‘s instruction
set defines 200 standard opcodes, 25 quick variations of some opcodes (to
support dynamic binding), and three reserved opcodes. The opcodes dictate
to the JVM what action to perform .
Skarifahmed@gmail.com
3
Secondly, a binary form at known as the class file form at, must be used to
convey bytecodes and related class infrastructure in a platform –
independent manner. Static tools such as class file viewers can look at this
representation.
*Opcode
Ans:
ClassLoader:
A class loader is an object that is responsible for loading classes. The class
ClassLoader is an abstract class. Given the name of a class, a class loader
should attempt to locate or generate data that constitutes a definition for the
class. A typical strategy is to transform the name into a file name and then
read a "class file" of that name from a file system.
ByteCode Verfied
1.In the first phase,the verifier cheak for the stucture of the .class file.
2. the second level phase occurs when the bytecode is rub.The ByteCode
Skarifahmed@gmail.com
4
program.
security manager :
Interpreter
just-in-time compiler
Ans:
Abstraction
Encapsulation
Polymorphism
Skarifahmed@gmail.com
5
Inheritance
Realworld example:
1)Encapsulation
It is the mechanism that binds together code and data in manipulates, and
keeps both safe from outside interference and misuse. In short it isolates a
particular code and data from all other codes and data. In Java, the basis of
encapsulation is the class. A class defines the structure and behavior(data and
code) that will be shared by a set of objects.
Skarifahmed@gmail.com
6
2) Inheritance:
It is the process by which one object acquires the properties of another
object. This supports the hierarchical classification. Without the use of
hierarchies, each object would need to define all its characteristics explicitly.
Realworld example:
From the above, we can decide that “Student” or “Lecturer” belong to the
“Person” category. Thus “Person” will be the super (or parent) class for both
“Student” and “Lecturer.” Conversely, “Student” and “Lecturer” both get
inherited from “Person.”
3) Polymorphism:
Process of aquiring properies from one object to another with
changes.
poly=many , morphism=forms
Ans:
Skarifahmed@gmail.com
7
In the real world, you often have many objects of the same kind. For
example, your bicycle is just one of many bicycles in the world. Using
object-oriented terminology, we say that your bicycle object is an instance
of the class of objects known as bicycles.
Bicycles have some state (current gear, current cadence, two wheels) and
behavior (change gears, brake) in common.
Ans:
Real-world objects share two characteristics: They all have state and
behavior. Dogs have state (name, color, breed, hungry) and behavior
(barking, fetching, wagging tail). Bicycles also have state (current gear,
current pedal cadence, current speed) and behavior (changing gear, changing
pedal cadence, applying brakes). Identifying the state and behavior for real-
world objects is a great way to begin thinking in terms of object-oriented
programming.
Skarifahmed@gmail.com
8
Ans:
Object is obtained when it has a life, means it has occupied some memory.
Reference points to the Object.
When you pass an object variable into a method, you must keep in mind
that you’re passing the object reference, and not the actual object itself.
You must remember that you aren’t even passing the actual reference
variable, but rather a copy of the reference variable.
Both the caller and the called method will now have identical copies of the
reference, and thus both will refer to the same exact (not a copy)
Skarifahmed@gmail.com
9
Ans:
Variable and method together form a method.
Skarifahmed@gmail.com
10
} }
Keywords:
All the keywords are in lowercase, and incorrect usage results in compilation
errors. Example –abstract,Boolean etc.
Identifiers:
• Identifiers in Java are case sensitive, for example, price and Price are two
different identifiers.
In the above statement the literal is an integer value i.e 10. The
literal is 10 because; it directly represents the integer value.
In Java programming language there are some special type of literals that
represent numbers, characters, strings and boolean values.
Skarifahmed@gmail.com
11
Ans .
Because keywords are reserve identifier in java. Identifiers are the names of
variables, methods, classes, packages and interfaces.
Ans.
Primitive data types in Java can be divided into three main categories:
Integral types— represent signed integers (byte, short, int, long) and
unsigned character values (char)
Skarifahmed@gmail.com
12
Ans:
Ans:
Skarifahmed@gmail.com
13
Ans:
public,static,void,main.
public:-
static:-
void - The keyword void simply tells the compiler that main( ) does not
return a value.
main( ):- main is the method called when a Java application begins. Keep
in mind that Java is case-sensitive. Thus, Main is different from main. It is
important to understand that the Java compiler will compile classes that do
not contain a main( ) method. But the Java interpreter has no way to run
these classes. So, if you had typed Main instead of main, the compiler
would still compile your program. However, the Java interpreter would
report an error because it would be unable to find the main( ) method.
Skarifahmed@gmail.com
14
Ans:
We say that the subtraction operator (-) is "left associative", so the left
subtraction must be performed first. When we can't decide by operator
precedence alone in which order to calculate an expression, we must use
associativity.
Ans:
In order to understand the result returned by an operator, it is important to
understand the evaluation order of its operands. Java states that the
operands of operators are evaluated from left to right.Java guarantees that all
operands of an operator are fully evaluated before the operator is applied.
The only exceptions are the short-circuit conditional operators &&, ||,
and ?:.
Skarifahmed@gmail.com
15
(b=3) + b
3 + b b is assigned the value 3
3+3
6
The evaluation order also respects any parentheses, and the precedence and
associativity rules of operators.
Skarifahmed@gmail.com
16
Ans:
1>Narrowing Conversion
The value of broader data type can be converted to a value of a narrower data
type which can result in loss of information.
long a = 10;
System.out.println(a);
System.out.println(b);
Eg.
Skarifahmed@gmail.com
17
class A{
class B extends A{
A a=new B();
The value of narrower data type can be converted to a value of a brooder data
type without loss of information.
Skarifahmed@gmail.com
18
Eg.
class A{
class B extends A{
Ans :
Casting: casting is the process of converting one data type into another data
type or one reference type into another reference type.
Eg.
class Test {
Skarifahmed@gmail.com
19
UpCasting for reference type is, casting up the inheritance tree to a more
general type. It is done implicitly (i.e. typing in the cast is not required). Its
because the classes at lower level of hierarchy have all those features that are
present in the classes above them in the inheritance hierarchy. So they can be
up casted implicitly.
Eg.
class A{
class B extends A{
A a =new B();//upcasting
2>Down casting:
It is a process of converting broader data type to narrower data type with loss
of information.
Skarifahmed@gmail.com
20
long a = 10;
System.out.println(a);
System.out.println(b);
Down Casting for reference type is nothing but casting down the inheritance
tree to a more specific class i.e casting a superclass to subclass.
Eg.
class A{
class B extends A{
A a=new B();
B b =(B)a;//downcasting
Skarifahmed@gmail.com
21
Ans.
Numeric promotion :
• The two kinds of numeric promotion are unary numeric promotion and
binary numeric promotion.
Skarifahmed@gmail.com
22
Ans.
Logical AND (&), x & y true if both operands are true; otherwise, false.
Logical OR(|) x | y true if either or both operands are true; otherwise,f alse.
Skarifahmed@gmail.com
23
Ans:
Message passing:
When you pass an object variable into a method, you must keep in mind that
you’re passing the object reference, and not the actual object itself.
You must remember that you aren’t even passing the actual reference
variable, but rather a copy of the reference variable.
Both the caller and the called method will now have identical copies of the
reference, and thus both will refer to the same exact (not a copy) object on
the heap.
import java.awt.Dimension;
class ReferenceTest {
Skarifahmed@gmail.com
24
rt.modify(d);
dim.height = dim.height + 1;
dim = 11
class ReferenceTest {
int a = 1;
rt.modify(a);
Skarifahmed@gmail.com
25
number = number + 1;
After modify() a = 1
a did not change after it was passed to the method. Remember, it was only a
copy of a that was passed to the method. When a primitive variable is passed
to a method, it is pass by value, which means pass-by-copy-of-the-bits-in
the variable
Ans:
static - Static members belong to the class in which they are declared, and
are not part of any instance of the class.
When the class is loaded, static variables are initialized to their default values.
A static method in a class can directly access other static members in the
class. It cannot access instance (i.e., non-static) members of the class.
Skarifahmed@gmail.com
26
A final variable of a primitive data type cannot change its value once it has
been initialized.
class Native { /* * The static block ensures that the native method library * is
loaded before the native method is called. */ static {
System.loadLibrary(“ NativeMethodLib"); // (1) Load native library.
Skarifahmed@gmail.com
27
Ans:
Public:
public classes, methods, and fields can be accessed from everywhere. The
only constraint is that a file with Java source code can only contain one public
Skarifahmed@gmail.com
28
class whose name must also match with the filename. If it exists, this public
class represents the application or the applet, in which case the public
keyword is necessary to enable your Web browser or appletviewer to show the
applet. You use public classes, methods, or fields only if you explicitly want to
offer access to these entities and if this access cannot do any harm. An
example of a square determined by the position of its upper-left corner and its
size:
public class Square { // public class
public x, y, size; // public instance variables
}
Protected:
protected methods and fields can only be accessed within the same class to
which the methods and fields belong, within its subclasses, and within classes
of the same package, but not from anywhere else. You use the protected
access level when it is appropriate for a class's subclasses to have access to
the method or field, but not for unrelated classes.
If you do not set access to specific level, then such a class, method, or field
will be accessible from inside the same package to which the class, method, or
field belongs, but not from outside this package. This access-level is
convenient if you are creating packages. For example, a geometry package
that contains Square and Tiling classes, may be easier and cleaner to
implement if the coordinates of the upper-left corner of a Square are directly
available to the Tiling class but not outside the geometry package.
Private:
private methods and fields can only be accessed within the same class to
which the methods and fields belong. private methods and fields are not
visible within subclasses and are not inherited by subclasses. So, the private
access specifier is opposite to the public access specifier. It is mostly used for
encapsulation: data are hidden within the class and accessor methods are
provided. An example, in which the position of the upper-left corner of a
square can be set or obtained by accessor methods, but individual coordinates
are not accessible to the user.
public class Square { // public class
private double x, y // private (encapsulated) instance variables
Skarifahmed@gmail.com
29
Ans:
Array:
Example of Array-
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++)
ia[i] = i;
int sum = 0;
for (int i = 0; i < ia.length; i++)
sum += ia[i];
System.out.println(sum);
}
Skarifahmed@gmail.com
30
}
that produces the output:
5050
Anonymous Arrays:
No array name or array size is specified for the anonymous array i.e. both
combine the definition and initialization of array into one process.
class AnonArray {
min = dataSeq[index];
return min;
Minimum value: 2
Skarifahmed@gmail.com
31
When constructing multidimensional arrays with the new operator, the length
of the deeply nested arrays may be omitted. In this case,
these arrays are left unconstructed. For example an array of arrays to
represent a room on a floor in a hotel on a street in a city can have
the type HotelRoom[][][][]. From left to right, the square brackets represent
indices for street, hotel, floor, and room, respectively. This
4-dimensional array of arrays can be constructed piecemeal, starting with the
leftmost dimension and proceeding to the rightmost.
HotelRoom[][][][] rooms = new HotelRoom[10][5][][]; // Just streets and
hotels.
The above declaration constructs the array of arrays rooms partially with ten
streets, where each street has five hotels. Floors and rooms
can be added to a particular hotel on a particular street:
rooms[0][0] = new HotelRoom[3][]; // 3 floors in 1st. hotel on 1st. street.
rooms[0][0][0] = new HotelRoom[8]; // 8 rooms on 1st. floor in this hotel.
rooms[0][0][0][0] = new HotelRoom(); // Initialize 1st. room on this floor.
Ans:
Compile-time polymorphism :
Skarifahmed@gmail.com
32
For each method invocation, the compiler determines which method (from a
group of overloaded methods) will be executed, and this decision is made
when the program is compiled.
Run-time polymorphism:
class A
{
void method(int x)\\1
{
}
int method(String s)\\2
{
}
}
class B extends A{
void method(int a)\\3
{
}
public static void main(String a[]){
A a=new B();\\4
a.method(5);\\5
a.method(“name”);\\6
}
}
Explanation:
At compile time the methods marked 1 and will be checked whether method
overloading is occurring.
Skarifahmed@gmail.com
33
Ans:
Constructor
Parameterized Constructor
// .....
Skarifahmed@gmail.com
34
// Parameterized Constructor
{ this.noOfWatts = noOfWatts;
this.indicator = indicator;
this.location = location;
// ……
Ans:
Packages are containers for classes that are used to keep the class name
space compartmentalized.
For example, a package allows you to create a class named List, which you
can store in your own package without concern that it will collide with some
other class named List stored elsewhere. To create a package is quite easy:
simply include a package command as the first statement in a Java source
file.
Encapsulation
Skarifahmed@gmail.com
35
Ans:
A class may implement several A class may extend only one abstract
interfaces. class.
An interface cannot provide any code An abstract class can provide complete
at all, much less default code. code, default code.
Skarifahmed@gmail.com
36
// ... }
An Interface can only have public members whereas an abstract class can
contain private,public,default as well as protected members.
All variables in an Interface are by default - public static final while an
abstract class can have instance variables.
Abstract class definition begins with the keyword "abstract" keyword
followed by Class definition. An Interface definition begins with the
keyword "interface".
Ans:
The continue statement skips the current iteration of a for, while , or do-
while loop.
Skarifahmed@gmail.com
37
the continue statement transfers control when it is executed; that is, the
rest of the loop body is skipped and execution continues with the next
iteration of the inner loop
if (searchMe.charAt(i) != 'p')
continue;
numPs++;
For(int i=0;i<=10;i++)
if(i==6)break;
System.out.println(“Example of break”);
Ans:
The difference between a "do ...while" loop and a "while {} " loop is that the
while loop tests its condition before execution of the contents of the loop
begins; the "do " block tests its condition after it's been executed at least
Skarifahmed@gmail.com
38
once. If the test condition is false as the while block is entered the block of
code is never executed. Since the condition is tested at the bottom of a do-
while loop, its block of code is always executed at least once.
do
{
block of code
} while (condition is satisfied);
A semi-colon ( ; ) must be used at the end of the do ...while loop. This semi-
colon is needed because it instructs whether the while (condition) statement is
the beginning of a while loop or the end of a do ...while loop.
Ans:
Skarifahmed@gmail.com
39
Each thread has its own runtime stack (also called the call stack or the
invocation stack) that is used to handle execution of methods.
When the method finishes executing, its record is popped from the stack.
At any given time, the active methods on a runtime stack comprise what is
called the stack trace of a thread's execution.
Exception propagation:
Example:
Skarifahmed@gmail.com
40
All goes well until the return statement in the method computeAverage() is
executed. An error condition occurs in calculating the expression sum/number,
because integer division by 0 is an illegal operation. This error condition is
signalled by the JVM by throwing an ArithmeticException. This exception is
propagated by the JVMthrough the runtime stack . Execution of the
computeAverage() method is stopped at the point where the exception is
thrown. The execution of the return statement never gets completed. Since
this method does not have any code to deal with the exception, its execution
is likewise terminated abruptly and its activation record popped. We say that
the method completes abruptly. The exception is then offered to the method
whose activation is now on top of the stack (method printAverage()). This
method does not have any code to deal with the exception either, so its
execution completes abruptly. Lines (4) and (5) in the method rintAverage()
never get executed. The exception now propagates to the last active method
(method main()). This does not deal with the exception either. The main()
method also completes abruptly. Line (2) in the main() method never gets
executed. Since the exception is not caught by any of the active methods, it is
dealt with by the main thread's default exception handler. The default
exception handler usually prints the name of the exception, with an
explanatory message, followed by a printout of the stack trace at the time the
exception was thrown. An uncaught exception results in the death of the
thread in which the exception occurred.
Ans:
<statements>
<statements>
Skarifahmed@gmail.com
41
...
<statements>
<statements>
Exceptions thrown during execution of the try block can be caught and
handled in a catch block. A finally block is guaranteed to be executed,
regardless of the cause of exit from the try block, or whether any catch block
was executed.
try Block
The try block establishes a context that wants its termination to be handled.
Termination occurs as a result of encountering an exception ,or from
successful execution of the code in the try block.
For all exits from the try block, except those due to exceptions, the catch
blocks are skipped and control is transferred to the finally block, if one is
specified
For all exits from the try block resulting from exceptions, control is transferred
to the catch blocks—if any such blocks are specified—to find a matching catch
block .If no catch block matches the thrown exception, control is transferred
to the finally block, if one is specified
catch Block
Only an exit from a try block resulting from an exception can transfer control
to a catch block. A catch block can only catch the thrown exception if the
exception is assignable to the parameter in the catch block .The code of the
first such catch block is executed and all other catch blocks are ignored. On
exit from a catch block, normal execution continues unless there is any
pending exception that has been thrown and not handled. If this is the case,
Skarifahmed@gmail.com
42
the method is aborted and the exception is propagated up the runtime stack
as explained earlier. After a catch block has been executed, control is always
transferred to the finally block, if one is specified. This is always true as long
as there is a finally block, regardless of whether the catch block itself throws
an exception.
finally Block
A finally block encloses code that is always executed at some point after
the try block, whether an exception was thrown or not.
If there is a return statement in the try block, the finally block executes
right after the return statement!
Ans:
Checked exceptions: -
Except for RuntimeException, Error, and their subclasses, all exceptions are
called checked exceptions.
The compiler ensures that if a method can throw a checked exception, directly
or indirectly, then the method must explicitly deal with it. The method must
either catch the exception and take the appropriate action, or pass the
exception on to its caller
Example: IOException
Unchecked Exceptions:-
Skarifahmed@gmail.com
43
They are either irrecoverable and the program should not attempt to deal
with them.
Example:NullPointerException
Ans :
Exception and Error are the subclasses of the Throwable class. Exception class
is used for exceptional conditions that user program should catch. With
exception class we can subclass to create our own custom exception.
The subclasses of Error represent errors that are normally thrown by the class
loader, the virtual machine, or other support code. Application-specific code
should not normally throw any of these standard error classes. If a method
does throw an Error class or any of its subclasses, the method is not required
to declare that fact in its throws clause. Error defines exceptions that are not
expected to be caught by you program. Example is Stack Overflow.
Ans:
A program can explicitly throw an exception using the throw statement. The
general format of the throw statement is as follows:
Skarifahmed@gmail.com
44
package test;
super(msg);
if (second == 0) {
try {
System.out.println(divide(4, 0));
Skarifahmed@gmail.com
45
exc.printStackTrace();
The compiler enforces that the checked exceptions thrown by a method are
limited to those specified in its throws clause. Of course, the method can
throw exceptions that are subclasses of the checked exceptions in the throws
clause.
• use a try block and catch the exception in a handler and deal with it.
• use a try block and catch the exception in a handler, but throw another
exception that is either unchecked or declared in its throws clause
• explicitly allow propagation of the exception to its caller by declaring it in
the throws clause of its method prototype.
Example:-
Definition of printAverage()
throws Exception {
Skarifahmed@gmail.com
46
try {
} catch (Exception e) {
e.printStackTrace();
"main().");
} finally {
Skarifahmed@gmail.com
47
Ans:
Skarifahmed@gmail.com
48
Exceptions
A Java program should try to handle all of the standard exception classes,
since they represent routine abnormal conditions that should be anticipated
and caught to prevent program termination.
Runtime exceptions
ArithmeticException
ArrayIndexOutOfBoundsException
ArrayStoreException
ClassCastException
Skarifahmed@gmail.com
49
IllegalArgumentException
This exception is thrown to indicate that an illegal argument has been passed
to a method.
IllegalMonitorStateException
IllegalStateException
This exception is thrown to indicate that a method has been invoked when the
run-time environment is in an inappropriate state for the requested operation.
This exception is new in Java 1.1.
IllegalThreadStateException
IndexOutOfBoundsException
NegativeArraySizeException
NullPointerException
NumberFormatException
Skarifahmed@gmail.com
50
RuntimeException
SecurityException
StringIndexOutOfBoundsException
Other exceptions
The java.lang package defines the following standard exception classes that
are not runtime exceptions:
ClassNotFoundException
CloneNotSupportedException
This exception is thrown when the clone() method has been called for an
object that does not implement the Cloneable interface and thus cannot be
cloned.
Exception
Skarifahmed@gmail.com
51
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodException
Errors
The subclasses of Error represent errors that are normally thrown by the class
loader, the virtual machine, or other support code. Application-specific code
should not normally throw any of these standard error classes. If a method
does throw an Error class or any of its subclasses, the method is not required
to declare that fact in its throws clause.
Skarifahmed@gmail.com
52
A Java program should not try to handle the standard error classes. Most of
these error classes represent non-recoverable errors and as such, they cause
the Java runtime system to print an error message and terminate program
execution.
AbstractMethodError
ClassCircularityError
ClassFormatError
This error is thrown when an error is detected in the format of a file that
contains a class definition.
Error
ExceptionInInitializerError
IllegalAccessError
This error is thrown when a class attempts to access a field or call a method it
does not have access to. Usually this error is caught by the compiler; this
error can occur at run-time if the definition of a class changes after the class
that references it was last compiled.
Skarifahmed@gmail.com
53
IncompatibleClassChangeError
This error or one of its subclasses is thrown when a class refers to another
class in an incompatible way. This situation occurs when the current definition
of the referenced class is incompatible with the definition of the class that was
found when the referring class was compiled. For example, say class A refers
to a method in class B. Then, after class A is compiled, the method is removed
from class B. When class A is loaded, the run-time system discovers that the
method in class B no longer exists and throws an error.
InstantiationError
InternalError
This error is thrown to signal an internal error within the virtual machine.
LinkageError
NoClassDefFoundError
NoSuchFieldError
NoSuchMethodError
Skarifahmed@gmail.com
54
OutOfMemoryError
StackOverflowError
This error is thrown when a stack overflow error occurs within the virtual
machine.
ThreadDeath
This error is thrown by the stop() method of a Thread object to kill the thread.
Catching ThreadDeath objects is not recommended. If it is necessary to catch
a ThreadDeath object, it is important to re-throw the object so that it is
possible to cleanly stop the catching thread.
UnknownError
This error is thrown when an error of unknown origins is detected in the run-
time system.
UnsatisfiedLinkError
VerifyError
This error is thrown when the byte-code verifier detects that a class file,
though well-formed, contains some sort of internal inconsistency or security
problem.
VirtualMachineError
The appropriate subclass of this error is thrown to indicate that the Java
virtual machine has encountered an error.
Skarifahmed@gmail.com
55
Ans :
For example……..
class A {
System.out.println("staticMethod () in A");
class B extends A {
static int i=6; //3 static variable Hide the field definition of
static Variable in class A.
System.out.println("staticMethod () in B");
Skarifahmed@gmail.com
56
Since (staticMethod()) it's a class method, the compiler and JVM don't expect
to need an actual instance to invoke the method. The compiler will only look
at the declared type of the reference, and use that declared type to
determine, at compile time, which method to call. Since aObj is declared as
type A, the compiler looks at aObj.staticMethod() and decides it means
A.staticMethod. It doesn't matter that the instance reffered to by aObj is
actually a B - for static methods, the compiler only uses the declared type of
the reference.
Override a static method, what that means is that even if you write code that
looks like it's overriding a static method - it won't behave like an overridden
method.
Ans :
Skarifahmed@gmail.com
57
class A {
System.out.println("aDoIt");
System.out.println("aDoneIt");
class B extends A {
System.out.println("aDoIt");
System.out.println("aDoneIt");
System.out.println("aDoIt");
Skarifahmed@gmail.com
58
System.out.println("aDoneIt");
void instanceMethod() {
C c = new C();
c.instanceMethod();
The this reference to the current object is useful in situations where a local
variable hides, ors hadows, a field with the same name.
Skarifahmed@gmail.com
59
The this reference is available in non-static code and refers to the current
object. When an instance method is invoked, theth is reference denotes the
object on which the method is called.The field billType and static method
doneIt() from class A is accessed successfully by casting the this reference,
because it is the type of the reference that determines the field accessed.
From non-static code in a subclass, it is possible to directly access fields in a
class higher up the inheritance hierarchy, by casting the this reference.
Ans:
this Used to represent an instance of the class in which it appears. this can
be used to access class members and as a reference to the current instance.
The this keyword is also used to forward a call from one constructor in a class
to another constructor in the same class.
return this.aNumber;
Skarifahmed@gmail.com
60
class Cat {
public Cat() {
name = nameIn;
Skarifahmed@gmail.com
61
public Himalayan() {
name = nameIn;
return super.getName();
Skarifahmed@gmail.com
62
Ans :
class Cube {
int length;
int breadth;
int height;
Cube() {
this(10, 10);
Skarifahmed@gmail.com
63
Cube(int l, int b) {
this(l, b, 10);
length = l;
breadth = b;
height = h;
int weight;
SpecialCube() {
super();
weight = 10;
SpecialCube(int l, int b) {
this(l, b, 10);
Skarifahmed@gmail.com
64
super(l, b, h);
weight = 20;
Skarifahmed@gmail.com
65
Weight of SpecialCube1 is : 10
Weight of SpecialCube2 is : 20
The super() construct as with this() construct: if used, must occur as the first
statement in a constructor, and it can only be used in a constructor
declaration. This implies that this() and super() calls cannot both occur in the
same constructor. Just as the this() construct leads to chaining of constructors
in the same class, the super() construct leads to chaining of subclass
constructors to superclass constructors.
Ans:
Object pop();
boolean isEmpty();
boolean isFull();
Skarifahmed@gmail.com
66
tos = -1;
stackArray[++tos] = item;
stackArray[tos] = null;
tos--;
return objRef;
return stackArray[tos];
Skarifahmed@gmail.com
67
super(capacity);
} // (7)
}// (8)
// Reference declarations
Object objRef;
StackImpl stackRef;
SafeStackImpl safeStackRef;
IStack iStackRef;
ISafeStack iSafeStackRef;
Skarifahmed@gmail.com
68
iSafeStackArray =
Skarifahmed@gmail.com
69
// Parameter Conversion
System.out.println("First call:");
// SafeStackImpl[], ISafeStack[]);
System.out.println("Second call:");
// StackImpl[], SafeStackImpl[]);
System.out.println(objRefParam.getClass());
System.out.println(stackRefParam.getClass());
System.out.println(iStackRefParam.getClass());
System.out.println(stackArrayParam.getClass());
System.out.println(iStackArrayParam.getClass());
Skarifahmed@gmail.com
70
Rule1 If SourceType is a class type, then the reference value in srcRef may be
assigned to the destRef reference, provided
DestinationType is one of the following:
DestinationType is a superclass of the subclass SourceType.
DestinationType is an interface type that is implemented by the class
SourceType.
objRef = safeStackRef; // (1) Always possible
stackRef = safeStackRef; // (2) Subclass to superclass assignment
iStackRef = stackRef; // (3) StackImpl implements IStack
iSafeStackRef = safeStackRef; // (4) SafeStackImpl implements ISafeStack
Rule3 If SourceType is an array type, then the reference value in srcRef may
be assigned to the destRef reference, provided
DestinationType is one of the following:
DestinationType is Object.
DestinationType is an array type, where the element type of SourceType is
assignable to the element type of
DestinationType.
objRef = objArray; // (7) Always possible
objRef = stackArray; // (8) Always possible
objArray = stackArray; // (9) Always possible
objArray = iSafeStackArray;// (10) Always possible
objRef = intArray; // (11) Always possible
// objArray = intArray; // (12) Compile-time error
Skarifahmed@gmail.com
71
The rules for assignment are enforced at compile time, guaranteeing that no
type conversion error will occur during assignment at
runtime. Such conversions are type safe. The reason the rules can be
enforced at compile time is that they concern the type of the
reference (which is always known at compile time) rather than the actual type
of the object being referenced (which is known at runtime).
Ans:
Eg.-
String s = "Hello";
if (s instanceof java.lang.String) {
System.out.println("is a String");
Skarifahmed@gmail.com
72
Cast operator:-
The cast operator (type) is used to convert numeric values from one numeric
type to another or to change an object reference to a compatible type used to
enable conversions that would normally be disallowed by the compiler .
Eg.-
byte a = 1;
byte b = 2;
Ans:
Skarifahmed@gmail.com
73
Skarifahmed@gmail.com
74
An inner class is a non static nested class that is defined within the definition
of another class but outside any member definition. Inner classes should not
be marked static.
2. Local classes
3. Anonymous classes
Member classes :-A member class is a class that is defined inside the
definition of another class, (without the use of the static modifier as is the
case with a nested top-level class).
Example:
Skarifahmed@gmail.com
75
Local classes - Local classes are like local variables, specific to a block of code.
Their visibility is only within the block of their declaration. In order for the
class to be useful beyond the declaration block, it would need to implement
amore publicly available interface. Because local classes are not members, the
modifiers public, protected, private, and static are not usable.
Example:
Anonymous classes - Anonymous inner classes extend local inner classes one
level further. As anonymous classes have no name, you cannot provide a
constructor.
Example :
button.addActionListener(new ActionListener() {
// This is how you define an anonymous inner class
public void actionPerformed(ActionEvent e) {
Skarifahmed@gmail.com
76
b)Why the static inner classes are not considered as in the category of
inner classes? How can a interface be defined as a member of a class?
Ans:
Nested interfaces are considered implicitly static, the keyword static can,
therefore, be omitted. Since static member classes and interfaces are
members of an enclosing class or interface, they can have any member
accessibility.
Skarifahmed@gmail.com
77
Ans:
Ans:
Skarifahmed@gmail.com
78
Skarifahmed@gmail.com
79
Ans:
f) What about the association of the enclosing instance with the outer
instance for the following member classes.
Ans:
Skarifahmed@gmail.com
80
Inside the Inner1 class another non static member class Inner2 is
declared. These three classes contain a instance member name of
type String. How can the instance member of Outer1 be accessed
from Inner2?
Ans.
class Outer1
System.out.println(id);
Skarifahmed@gmail.com
81
class Inner1
System.out.println(id);
class Inner2 {
System.out.println(id);
Outer1.this.printId();
Inner1.this.printId();
printId();
Skarifahmed@gmail.com
82
b.printId();
c.printId();
d.printId();
bb.printId();
cc.printId();
System.out.println("------------");
ccc.printIndividualIds();
Skarifahmed@gmail.com
83
Output:
------------
Ans.
Skarifahmed@gmail.com
84
class LocalClassTest
foo.print();
};
class LocalClassTest
foo.print();
Skarifahmed@gmail.com
85
Skarifahmed@gmail.com