Chapter 1:
Language Fundamentals (Next: Chapter 2)
The Java programming language has includes five simple
arithmetic operators like are + (addition), - (subtraction), *
(multiplication), / (division), and % (modulo). The following table summarizes
them:1. Source file's elements (in order)
- Package declaration
- Import statements
- Class definitions
3. Sub-packages are really different packages, happen to live within an enclosing package. Classes in sub-packages cannot access classes in enclosing package with default access.
4. Comments can appear anywhere. Can't be nested. No matter what type of comments.
5. At most one public class definition per file. This class name should match the file name. If there are more than one public class definitions, compiler will accept the class with the file's name and give an error at the line where the other class is defined.
6. It's not required having a public class definition in a file. Strange, but true. J In this case, the file's name should be different from the names of classes and interfaces (not public obviously).
7. Even an empty file is a valid source file.
8. An identifier must begin with a letter, dollar sign ($) or underscore (_). Subsequent characters may be letters, $, _ or digits.
9. An identifier cannot have a name of a Java keyword. Embedded keywords are OK. true, false and null are literals (not keywords), but they can't be used as identifiers as well.
10. const and goto are reserved words, but not used.
11. Unicode characters can appear anywhere in the source code. The following code is valid.
ch\u0061r a = 'a';
char \u0062 = 'b';
char c = '\u0063';
12. Java has 8 primitive data types.
Data Type
|
Size (bits)
|
Initial Value
|
Min Value
|
Max Value
|
boolean
|
1
|
false
|
false
|
true
|
byte
|
8
|
0
|
-128 (-27)
|
127 (27 - 1)
|
short
|
16
|
0
|
-215
|
215 - 1
|
char
|
16
|
'\u0000'
|
'\u0000' (0)
|
'\uFFFF' (216 - 1)
|
int
|
32
|
0
|
-231
|
231 - 1
|
long
|
64
|
0L
|
-263
|
263 - 1
|
float
|
32
|
0.0F
|
1.4E-45
|
3.4028235E38
|
double
|
64
|
0.0
|
4.9E-324
|
1.7976931348623157E308
|
14. Object reference variables are initialized to null.
15. Octal literals begin with zero. Hex literals begin with 0X or 0x.
16. Char literals are single quoted characters or unicode values (begin with \u).
17. A number is by default an int literal, a decimal number is by default a double literal.
18. 1E-5d is a valid double literal, E2d is not (since it starts with a letter, compiler thinks that it's an identifier)
19. Two types of variables.
a. Member variables
- Accessible anywhere in the class.
- Automatically initialized before invoking any constructor.
- Static variables are initialized at class load time.
- Can have the same name as the class.
· Must be initialized explicitly. (Or,
compiler will catch it.) Object references can be initialized to null to make
the compiler happy. The following code won't compile. Specify else part or
initialize the local variable explicitly.
public String testMethod ( int a) {
String tmp;
if ( a > 0 ) tmp = "Positive";
return tmp;
}
· Can have the same name as a member variable, resolution is based on scope.
20. Arrays are Java objects. If you create an array of 5 Strings, there will be 6 objects created.
21. Arrays should be
public String testMethod ( int a) {
String tmp;
if ( a > 0 ) tmp = "Positive";
return tmp;
}
· Can have the same name as a member variable, resolution is based on scope.
20. Arrays are Java objects. If you create an array of 5 Strings, there will be 6 objects created.
21. Arrays should be
- Declared. (int[] a; String b[]; Object []c; Size should not be specified now)
- Allocated (constructed). ( a = new int[10]; c = new String[arraysize] )
- Initialized. for (int i = 0; i < a.length; a[i++] = 0)
int a[] = { 1, 2, 3 }; (or )
int a[] = new int[] { 1, 2, 3 }; But never specify the size with the new statement.
23. Java arrays are static arrays. Size has to be specified at compile time. Array.length returns array's size. (Use Vectors for dynamic purposes).
24. Array size is never specified with the reference variable, it is always maintained with the array object. It is maintained in array.length, which is a final instance variable.
25. Anonymous arrays can be created and used like this: new int[] {1,2,3} or new int[10]
26. Arrays with zero elements can be created. args array to the main method will be a zero element array if no command parameters are specified. In this case args.length is 0.
27. Comma after the last initializer in array declaration is ignored.
int[] i = new int[2] { 5, 10}; // Wrong
int i[5] = { 1, 2, 3, 4, 5}; // Wrong
int[] i[] = {{}, new int[] {} }; // Correct
int i[][] = { {1,2}, new int[2] }; // Correct
int i[] = { 1, 2, 3, 4, } ; // Correct
28. Array indexes start with 0. Index is an int data type.
29. Square brackets can come after datatype or before/after variable name. White spaces are fine. Compiler just ignores them.
30. Arrays declared even as member variables also need to be allocated memory explicitly.
static int a[];
static int b[] = {1,2,3};
public static void main(String s[]) {
System.out.println(a[0]); // Throws a null pointer exception
System.out.println(b[0]); // This code runs fine
System.out.println(a); // Prints 'null'
System.out.println(b); // Prints a string which is returned by toString
}
31. Once declared and allocated (even for local arrays inside methods), array elements are automatically initialized to the default values.
32. If only declared (not constructed), member array variables default to null, but local array variables will not default to null.
33. Java doesn't support multidimensional arrays formally, but it supports arrays of arrays. From the specification - "The number of bracket pairs indicates the depth of array nesting." So this can perform as a multidimensional array. (no limit to levels of array nesting)
34. In order to be run by JVM, a class should have a main method with the following signature.
public static void main(String args[])
static public void main(String[] s)
35. args array's name is not important. args[0] is the first argument. args.length gives no. of arguments.
36. main method can be overloaded.
37. main method can be final.
38. A class with a different main signature or w/o main method will compile. But throws a runtime error.
39. A class without a main method can be run by JVM, if its ancestor class has a main method. (main is just a method and is inherited)
40. Primitives are passed by value.
41. Objects (references) are passed by reference. The object reference itself is passed by value. So, it can't be changed. But, the object can be changed via the reference.
42. Garbage collection is a mechanism for reclaiming memory from objects that are no longer in use, and making the memory available for new objects.
43. An object being no longer in use means that it can't be referenced by any 'active' part of the program.
44. Garbage collection runs in a low priority thread. It may kick in when memory is too low. No guarantee.
45. It's not possible to force garbage collection. Invoking System.gc may start garbage collection process.
46. The automatic garbage collection scheme guarantees that a reference to an object is always valid while the object is in use, i.e. the object will not be deleted leaving the reference "dangling".
47. There are no guarantees that the objects no longer in use will be garbage collected and their finalizers executed at all. gc might not even be run if the program execution does not warrant it. Thus any memory allocated during program execution might remain allocated after program termination, unless reclaimed by the OS or by other means.
48. There are also no guarantees on the order in which the objects will be garbage collected or on the order in which the finalizers are called. Therefore, the program should not make any decisions based on these assumptions.
49. An object is only eligible for garbage collection, if the only references to the object are from other objects that are also eligible for garbage collection. That is, an object can become eligible for garbage collection even if there are references pointing to the object, as long as the objects with the references are also eligible for garbage collection.
50. Circular references do not prevent objects from being garbage collected.
51. We can set the reference variables to null, hinting the gc to garbage collect the objects referred by the variables. Even if we do that, the object may not be gc-ed if it's attached to a listener. (Typical in case of AWT components) Remember to remove the listener first.
52. All objects have a finalize method. It is inherited from the Object class.
53. finalize method is used to release system resources other than memory. (such as file handles and network connections) The order in which finalize methods are called may not reflect the order in which objects are created. Don't rely on it. This is the signature of the finalize method.
protected void finalize() throws Throwable { }
In the descendents this method can be protected or public. Descendents can restrict the exception list that can be thrown by this method.
54. finalize is called only once for an object. If any exception is thrown in finalize, the object is still eligible for garbage collection (at the discretion of gc)
55. gc keeps track of unreachable objects and garbage-collects them, but an unreachable object can become reachable again by letting know other objects of its existence from its finalize method (when called by gc). This 'resurrection' can be done only once, since finalize is called only one for an object.
56. finalize can be called explicitly, but it does not garbage collect the object.
57. finalize can be overloaded, but only the method with original finalize signature will be called by gc.
58. finalize is not implicitly chained. A finalize method in sub-class should call finalize in super class explicitly as its last action for proper functioning. But compiler doesn't enforce this check.
59. System.runFinalization can be used to run the finalizers (which have not been executed before) for the objects eligible for garbage collection.
Chapter 3
- Modifiers
1. Modifiers are Java keywords that provide information to compiler
about the nature of the code, data and classes.
2. Access modifiers - public, protected, private
·
Only applied to class level variables. Method variables
are visible only inside the method.
·
Can be applied to class itself (only to inner classes
declared at class level, no such thing as protected or private top level class)
·
Can be applied to methods and constructors.
·
If a class is accessible, it doesn't mean, the members
are also accessible. Members' accessibility determines what is accessible and
what is not. But if the class is not accessible, the members are not
accessible, even though they are declared public.
·
If no access modifier is specified, then the
accessibility is default package visibility. All classes in the same package
can access the feature. It's called as friendly access. But friendly is not a
Java keyword. Same directory is same package in Java's consideration.
·
'private' means only the class can access it, not even
sub-classes. So, it'll cause access denial to a sub-class's own
variable/method.
·
These modifiers dictate, which classes can
access the features. An instance of a class can access the
private features of another instance of the same class.
·
'protected' means all classes in the same package (like
default) and sub-classes in any package can access the features. But a subclass
in another package can access the protected members in the super-class via only
the references of subclass or its subclasses. A subclass in the same package
doesn't have this restriction. This ensures that classes from other packages
are accessing only the members that are part of their inheritance hierarchy.
·
Methods cannot be overridden to be more private. Only
the direction shown in following figure is permitted from parent classes to
sub-classes.
private à friendly
(default) à protected à public
Parent
classes
Sub-classes
3. final
·
final features cannot be changed.
·
The final modifier applies to
classes, methods, and variables.
·
final classes cannot be sub-classed.
·
You can declare a variable in any scope to be final.
·
You may, if necessary, defer initialization of a final local
variable. Simply declare the local variable and initialize it later (for final
instance variables. You must initialize them at the time of declaration or in
constructor).
·
final variables cannot be changed (result in a
compile-time error if you do so )
·
final methods cannot be overridden.
·
Method arguments marked final are read-only. Compiler
error, if trying to assign values to final arguments inside the method.
·
Member variables marked final are not initialized by
default. They have to be explicitly assigned a value at declaration or in an
initializer block. Static finals must be assigned to a value in a static
initializer block, instance finals must be assigned a value in an instance
initializer or in every constructor. Otherwise the compiler will complain.
·
A blank final is a final variable whose
declaration lacks an initializer.
·
Final variables that are not assigned a value at the
declaration and method arguments that are marked final are called blank final
variables. They can be assigned a value at most once.
·
Local variables can be declared final as well.
·
If a
final
variable holds a reference to an
object, then the state of the object may be changed by operations on the
object, but the variable will always refer to the same object.
·
This applies also to arrays, because arrays are
objects; if a
final
variable holds a reference to an array, then the components of the
array may be changed by operations on the array, but the variable will always
refer to the same array
·
A blank final instance variable must be
definitely assigned at the end of every constructor of the class in which
it is declared; otherwise a compile-time error occurs.
·
A class can be declared
final
if its definition
is complete and no subclasses are desired or required.
·
A compile-time error occurs if the name of a
final
class
appears in the extends
clause of another class
declaration; this implies that a final
class
cannot have any subclasses.
·
A compile-time error occurs if a class is declared both
final
and abstract
, because the implementation of such a class could never be
completed.
·
Because a
final
class never has
any subclasses, the methods of a final
class are never
overridden
4. abstract
·
Can be applied to classes and methods.
·
For deferring implementation to sub-classes.
·
Opposite of final, final can't be sub-classed, abstract
must be sub-classed.
·
A class should be declared abstract,
1. if it has any abstract methods.
2. if it doesn't provide implementation to any of the abstract methods
it inherited
3. if it doesn't provide implementation to any of the methods in an
interface that it says implementing.
·
Just terminate the abstract method signature with a
';', curly braces will give a compiler error.
·
A class can be abstract even if it doesn't have any
abstract methods.
5. static
·
Can be applied to nested classes, methods, variables,
free floating code-block (static initializer)
·
Static variables are initialized at class load time. A
class has only one copy of these variables.
·
Static methods can access only static variables. (They
have no this)
·
Access by class name is a recommended way to access
static methods/variables.
·
Static initializer code is run at class load time.
·
Static methods may not be overridden to be non-static.
·
Non-static methods may not be overridden to be static.
·
Abstract methods may not be static.
·
Local variables cannot be declared as static.
·
Actually, static methods are not participating in the
usual overriding mechanism of invoking the methods based on the class of the
object at runtime. Static method binding is done at compile time, so the method
to be invoked is determined by the type of reference variable rather than the
actual type of the object it holds at runtime.
Let's say a sub-class has a static method
which 'overrides' a static method in a parent class. If you have a
reference variable of parent class type and you assign a child class object to
that variable and invoke the static method, the method invoked will be the
parent class method, not the child class method. The following code
explains this.
public class StaticOverridingTest {
public static void main(String s[])
{
Child c = new Child();
c.doStuff(); // This will invoke Child.doStuff()
Parent p = new Parent();
p.doStuff(); // This will invoke Parent.doStuff()
p = c;
p.doStuff(); // This will invoke Parent.doStuff(), rather than
Child.doStuff()
}
}
class Parent {
static int x = 100;
public static void doStuff() {
System.out.println("In Parent..doStuff");
System.out.println(x);
}
}
class Child extends Parent {
static int x = 200;
public static void doStuff() {
System.out.println("In Child..doStuff");
System.out.println(x);
}
}
6. native
·
Can be applied to methods only. (static methods also)
·
Written in a non-Java language, compiled for a single
machine target type.
·
Java classes use lot of native methods for performance
and for accessing hardware Java is not aware of.
·
Native method signature should be terminated by a ';',
curly braces will provide a compiler error.
·
native doesn't affect access qualifiers. Native methods
can be private.
·
Can pass/return Java objects from native methods.
·
System.loadLibrary is
used in static initializer code to load native libraries. If the library is not
loaded when the static method is called, an UnsatisfiedLinkError is
thrown.
7. transient
·
Can be applied to class level variables only.(Local
variables cannot be declared transient)
·
Transient variables may not be final or static.(But
compiler allows the declaration, since it doesn't do any harm. Variables marked
transient are never serialized. Static variables are not serialized anyway.)
·
Not stored as part of object's persistent state, i.e.
not written out during serialization.
·
Can be used for security.
8. synchronized
·
Can be applied to methods or parts of methods only.
·
Used to control access to critical code in
multi-threaded programs.
9. volatile
·
Can be applied to variables only.
·
Can be applied to static variables.
·
Cannot be applied to final variables.
·
Declaring a variable volatile indicates that it might
be modified asynchronously, so that all threads will get the correct value of
the variable.
·
Used in multi-processor environments.
Modifier
|
Class
|
Inner classes (Except local and anonymous classes)
|
Variable
|
Method
|
Constructor
|
Free floating Code block
|
|
public
|
Y
|
Y
|
Y
|
Y
|
Y
|
N
|
|
protected
|
N
|
Y
|
Y
|
Y
|
Y
|
N
|
|
(friendly)
No access modifier
|
Y
|
Y (OK for all)
|
Y
|
Y
|
Y
|
N
|
|
private
|
N
|
Y
|
Y
|
Y
|
Y
|
N
|
|
final
|
Y
|
Y (Except anonymous classes)
|
Y
|
Y
|
N
|
N
|
|
abstract
|
Y
|
Y (Except anonymous classes)
|
N
|
Y
|
N
|
N
|
|
static
|
N
|
Y
|
Y
|
Y
|
N
|
Y (static initializer)
|
|
native
|
N
|
N
|
N
|
Y
|
N
|
N
|
|
transient
|
N
|
N
|
Y
|
N
|
N
|
N
|
|
synchronized
|
N
|
N
|
N
|
Y
|
N
|
Y (part of method, also need to specify an
object on which a lock should be obtained)
|
|
volatile
|
N
|
N
|
Y
|
N
|
N
|
N
|
|
|
|
|
|
|
|
|
|
Chapter 4 Converting
and Casting
Unary Numeric PromotionContexts:
·
Operand of the unary arithmetic operators + and -
·
Operand of the unary integer bit-wise complement
operator ~
·
During array creation, for example new int[x], where
the dimension expression x must evaluate to an int value.
·
Indexing array elements, for example table['a'], where
the index expression must evaluate to an int value.
·
Individual operands of the shift operators.
Binary numeric promotionContexts:
·
Operands of arithmetic operators *, / , %, + and -
·
Operands of relational operators <, <= , > and
>=
·
Numeric Operands of equality operators == and !=
·
Integer Operands of bit-wise operators &, ^ and |
Conversion of Primitives
1. 3 types of conversion - assignment conversion, method call
conversion and arithmetic promotion
2. boolean may not be converted to/from any non-boolean type.
3. Widening conversions accepted. Narrowing conversions rejected.
4. byte, short can't be converted to char and vice versa. ( but
can be cast )
5. Arithmetic promotion
5.1 Unary operators
·
if the operand is byte, short or char {
convert it to int;
}
else {
do nothing;
no conversion needed;
}
5.2 Binary operators
·
if one operand is double {
all double; convert the other
operand to double;
}
else if one operand is float {
all float; convert the other
operand to float;
}
else if one
operand is long {
all long; convert the other
operand to long;
}
else {
all int; convert all to int;
}
6. When assigning a literal value to a variable, the range of the
variable's data type is checked against the value of the literal and assignment
is allowed or compiler will produce an error.
char c = 3; // this will
compile, even though a numeric literal is by default an int since the range of
char will accept the value
int a = 3;
char d = a; // this won't
compile, since we're assigning an int to char
char e = -1; // this also won't
compile, since the value is not in the range of char
float f = 1.3; // this won't
compile, even though the value is within float range. Here range is not
important, but precision is. 1.3 is by default a double, so a specific cast or
f = 1.3f will work.
float f = 1/3; // this will
compile, since RHS evaluates to an int.
Float f = 1.0 / 3.0; // this
won't compile, since RHS evaluates to a double.
7. Also when assigning a final variable to a variable, even if the
final variable's data type is wider than the variable, if the value is within
the range of the variable an implicit conversion is done.
byte b;
final int a = 10;
b = a; // Legal, since value of
'a' is determinable and within range of b
final int x = a;
b = x; // Legal, since value of
'x' is determinable and within range of b
int
y;
final
int z = y;
b = z; // Illegal, since value
of 'z' is not determinable
8. Method call conversions always look for the exact data type or a
wider one in the method signatures. They will not do narrowing conversions to
resolve methods, instead we will get a compile error.
Here is the figure of allowable
primitive conversion.
byte à short à int à long à float à double
char
Casting of Primitives
9. Needed with narrowing conversions. Use with care - radical
information loss. Also can be used with widening conversions, to improve the
clarity of the code.
10. Can cast any non-boolean type to another non-boolean type.
11. Cannot cast a boolean or to a boolean type.
Conversion of Object references
12. Three types of reference variables to denote objects - class,
interface or array type.
13. Two kinds of objects can be created - class or array.
14. Two types of conversion - assignment and method call.
15. Permitted if the direction of the conversion is 'up' the inheritance
hierarchy. Means that types can be assigned/substituted to only super-types -
super-classes or interfaces. Not the other way around, explicit casting is
needed for that.
16. Interfaces can be used as types when declaring variables, so they
participate in the object reference conversion. But we cannot instantiate an
interface, since it is abstract and doesn't provide any implementation. These
variables can be used to hold objects of classes that implement the interface.
The reason for having interfaces as types may be, I think, several unrelated
classes may implement the same interface and if there's a need to deal with
them collectively one way of treating them may be an array of the interface
type that they implement.
17. Primitive arrays can be converted to only the arrays of the same
primitive type. They cannot be converted to another type of primitive array.
Only object reference arrays can be converted / cast.
18. Primitive arrays can be converted to an Object reference, but not to
an Object[] reference. This is because all arrays (primitive arrays and
Object[]) are extended from Object.
Casting of Object references
19. Allows super-types to be assigned to subtypes. Extensive checks done
both at compile and runtime. At compile time, class of the object may not be
known, so at runtime if checks fail, a ClassCastException is thrown.
20. Cast operator, instanceof operator and the == operator behave the
same way in allowing references to be the operands of them. You cannot cast or
apply instanceof or compare unrelated references, sibling references
or any incompatible references.
Compile-time Rules
·
When old and new types are classes, one class must be
the sub-class of the other.
·
When old and new types are arrays, both must contain
reference types and it must be legal to cast between those types (primitive
arrays cannot be cast, conversion possible only between same type of primitive
arrays).
·
We can always cast between an interface and a non-final
object.
Run-time rules
·
If new type is a class, the class of the expression
being converted must be new type or extend new type.
·
If new type is an interface, the class of the
expression being converted must implement the interface.
An Object reference can be converted to:
(java.lang.Object)
·
an Object reference
·
a Cloneable interface reference, with casting, with
runtime check
·
any class reference, with casting, with runtime check
· any array referenece, with casting, with runtime check
·
any interface reference, with casting, with runtime
check
A Class type reference can be converted to:
·
any super-class type reference, (including Object)
·
any sub-class type reference, with casting, with
runtime check
·
an interface reference, if the class implements that
interface
·
any interface reference, with casting, with runtime
check (except if the class is final and doesn't implement the interface)
An Interface reference can be converted to:
·
an Object reference
·
a super-interface reference
·
any interface/class reference with casting, with
runtime check (except if the class is final and doesn't implement the interface)
A Primitive Array reference can be converted to:
·
an Object reference
·
a Cloneable interface reference
·
a primitive array reference of the same type
An Object Array reference can be converted to:
·
an Object reference
·
a Cloneable interface reference
·
a super-class Array reference, including an Object
Array reference
·
any sub-class Array reference with casting, with
runtime check
Chapter 5 Flow
Control and Exceptions
Unreachable statements produce a compile-time error.
while (false) { x = 3; } // won't compile
for (;false;) { x =3; } // won't compile
if (false) {x = 3; } // will compile, to
provide the ability to conditionally compile the code.
·
Local variables already declared in an enclosing block,
therefore visible in a nested block cannot be re-declared inside the nested
block.
·
A local variable in a block may be re-declared in
another local block, if the blocks are disjoint.
·
Method parameters cannot be re-declared.
1. Loop constructs
·
3 constructs - for, while, do
·
All loops are controlled by a boolean expression.
·
In while and for, the test occurs at the top, so if the
test fails at the first time, body of the loop might not be executed at all.
·
In do, test occurs at the bottom, so the body is
executed at least once.
·
In for, we can declare multiple variables in the first
part of the loop separated by commas, also we can have multiple statements in
the third part separated by commas.
·
In the first section of for statement, we can have a
list of declaration statements or a list of expression statements, but
not both. We cannot mix them.
·
All expressions in the third section of for statement
will always execute, even if the first expression makes the loop condition
false. There is no short -circuit here.
2. Selection Statements
·
if takes a boolean arguments. Parenthesis required.
else part is optional. else if structure provides multiple selective branching.
·
switch takes an argument of byte, short, char or
int.(assignment compatible to int)
·
case value should be a constant expression that can be
evaluated at compile time.
·
Compiler checks each case value against the range of
the switch expression's data type. The
following code won't compile.
byte b;
switch (b) {
case 200: // 200 not in range
of byte
default:
}
·
We need to place a break statement in each case block
to prevent the execution to fall through other case blocks. But this is not a
part of switch statement and not enforced by the compiler.
·
We can have multiple case statements execute the same
code. Just list them one by one.
·
default case can be placed anywhere. It'll be executed only
if none of the case values match.
·
switch can be nested. Nested case labels are
independent, don't clash with outer case labels.
·
Empty switch construct is a valid construct. But any
statement within the switch block should come under a case label or the default
case label.
3. Branching statements
·
break statement can be used with any kind of loop or a
switch statement or just a labeled block.
·
continue statement can be used with only a loop (any
kind of loop).
·
Loops can have labels. We can use break and continue
statements to branch out of multiple levels of nested loops using labels.
·
Names of the labels follow the same rules as the name
of the variables.(Identifiers)
·
Labels can have the same name, as long as they don't
enclose one another.
·
There is no restriction against using the same
identifier as a label and as the name of a package, class, interface, method,
field, parameter, or local variable.
4. Exception Handling
·
An exception is an event that occurs during
the execution of a program that disrupts the normal flow of instructions.
·
There are 3 main advantages for exceptions:
1. Separates error handling code from "regular" code
2. Propagating errors up the call stack (without tedious programming)
3. Grouping error types and error differentiation
·
An exception causes a jump to the end of try block. If
the exception occurred in a method called from a try block, the called method
is abandoned.
·
If there's a catch block for the occurred exception or
a parent class of the exception, the exception is now considered handled.
· At least one 'catch' block or one 'finally' block must accompany a
'try' statement. If all 3 blocks are present, the order is
important. (try/catch/finally)
·
finally and catch can come only with
try, they cannot appear on their own.
·
Regardless of whether or not an exception occurred or
whether or not it was handled, if there is a finally block, it'll be executed
always. (Even if there is a return statement in try block).
·
System.exit() and error conditions are the only
exceptions where finally block is not executed.
·
If there was no exception or the exception was handled,
execution continues at the statement after the try/catch/finally blocks.
·
If the exception is not handled, the process repeats
looking for next enclosing try block up the call hierarchy. If this search
reaches the top level of the hierarchy (the point at which the thread was
created), then the thread is killed and message stack trace is dumped to
System.err.
·
Use throw new xxxException() to throw an exception. If
the thrown object is null, a NullPointerException will be thrown at the
handler.
·
If an exception handler re-throws an exception (throw
in a catch block), same rules apply. Either you need to have a try/catch within
the catch or specify the entire method as throwing the exception that's being
re-thrown in the catch block. Catch blocks at the same level will not handle
the exceptions thrown in a catch block - it needs its own handlers.
·
The method fillInStackTrace() in Throwable class throws
a Throwable object. It will be useful when re-throwing an exception or error.
·
The Java language requires that methods either catch
or specify all checked exceptions that can be thrown within the scope
of that method.
·
All objects of type java.lang.Exception are checked
exceptions. (Except the classes under java.lang.RuntimeException) If any method
that contains lines of code that might throw checked exceptions, compiler
checks whether you've handled the exceptions or you've declared the methods as
throwing the exceptions. Hence the name checked exceptions.
·
If there's no code in try block that may throw
exceptions specified in the catch blocks, compiler will produce an error. (This
is not the case for super-class Exception)
·
Java.lang.RuntimeException and java.lang.Error need not be handled or declared.
·
An overriding method may not throw a checked exception
unless the overridden method also throws that exception or a super-class of
that exception. In other words, an overriding method may not throw checked
exceptions that are not thrown by the overridden method. If we allow the
overriding methods in sub-classes to throw more general exceptions than the
overridden method in the parent class, then the compiler has no way of checking
the exceptions the sub-class might throw. (If we declared a parent class
variable and at runtime it refers to sub-class object) This violates the concept
of checked exceptions and the sub-classes would be able to by-pass the enforced
checks done by the compiler for checked exceptions. This should not be allowed.
Here is the exception hierarchy.
Object
|
|
Throwable
| |
| |
|
|
|
|
|
Error
|
|
Exception-->ClassNotFoundException, ClassNotSupportedException,
IllegalAccessException, InstantiationException, IterruptedException,
NoSuchMethodException, RuntimeException, AWTException, IOException
RuntimeException-->EmptyStackException, NoSuchElementException,
ArithmeticException, ArrayStoreException, ClassCastException, IllegalArgumentException,
IllegalMonitorStateException,
IndexOutOfBoundsException,
NegativeArraySizeException, NullPointerException, SecurityException.
IllegalArgumentException-->IllegalThreadStateException,
NumberFormatException
IndexOutOfBoundsException-->ArrayIndexOutOfBoundsException,
StringIndexOutOfBoundsException
IOException-->EOFException, FileNotFoundException, InterruptedIOException,
UTFDataFormatException, MalformedURLException, ProtocolException,
SockException, UnknownHostException, UnknownServiceException.
Chapter 7 Threads
·
Java is fundamentally multi-threaded.
·
Every thread corresponds to an instance of
java.lang.Thread class or a sub-class.
·
A thread becomes eligible to run, when its
start() method is called. Thread scheduler co-ordinates between the threads and
allows them to run.
·
When a thread begins execution, the scheduler calls its
run method.
Signature of run method - public void
run ()
·
When a thread returns from its run method (or stop
method is called - deprecated in 1.2), its dead. It cannot be restarted, but
its methods can be called. (it's just an object no more in a running state)
·
If start is called again on a dead thread, IllegalThreadStateException
is thrown.
·
When a thread is in running state, it may move out of
that state for various reasons. When it becomes eligible for execution again,
thread scheduler allows it to run.
·
There are two ways to implement threads.
1. Extend Thread class
·
Create a new class, extending the Thread class.
·
Provide a public void run method, otherwise empty run
in Thread class will be executed.
·
Create an instance of the new class.
·
Call start method on the instance (don't call run - it
will be executed on the same thread)
2. Implement Runnable interface
·
Create a new class implementing the Runnable interface.
·
Provide a public void run method.
·
Create an instance of this class.
·
Create a Thread, passing the instance as a target - new
Thread(object)
·
Target should implement Runnable, Thread class
implements it, so it can be a target itself.
·
Call the start method on the Thread.
·
JVM creates one user thread for running a program. This
thread is called main thread. The main method of the class is called from the
main thread. It dies when the main method ends. If other user threads have been
spawned from the main thread, program keeps running even if main thread dies.
Basically a program runs until all the user threads (non-daemon threads) are
dead.
·
A thread can be designated as a daemon thread by
calling setDaemon(boolean) method. This method should be called before
the thread is started, otherwise IllegalThreadStateException will be thrown.
·
A thread spawned by a daemon thread is a daemon thread.
·
Threads have priorities. Thread class have constants
MAX_PRIORITY (10), MIN_PRIORITY (1), NORM_PRIORITY (5)
·
A newly created thread gets its priority from the
creating thread. Normally it'll be NORM_PRIORITY.
·
getPriority and setPriority
are the methods to deal with priority of threads.
·
Java leaves the implementation of thread scheduling to
JVM developers. Two types of scheduling can be done.
1.
Pre-emptive Scheduling.
Ways for a
thread to leave running state -
·
It can cease to be ready to execute ( by calling a
blocking i/o method)
·
It can get pre-empted by a high-priority thread, which
becomes ready to execute.
·
It can explicitly call a thread-scheduling method such
as wait or suspend.
·
Solaris JVM's are pre-emptive.
·
Windows JVM's were pre-emptive until Java 1.0.2
2.
Time-sliced or Round Robin Scheduling
·
A thread is only allowed to execute for a certain
amount of time. After that, it has to contend for the CPU (virtual CPU, JVM)
time with other threads.
·
This prevents a high-priority thread mono-policing the
CPU.
·
The drawback with this scheduling is - it creates a
non-deterministic system - at any point in time, you cannot tell which thread
is running and how long it may continue to run.
·
Macintosh JVM's
·
Windows JVM's after Java 1.0.2
·
Different states of a thread:
1.
Yielding
·
Yield is a static method. Operates on current thread.
·
Moves the thread from running to ready state.
·
If there are no threads in ready state, the yielded
thread may continue execution, otherwise it may have to compete with the other
threads to run.
·
Run the threads that are doing time-consuming
operations with a low priority and call yield periodically from those threads
to avoid those threads locking up the CPU.
2.
Sleeping
·
Sleep is also a static method.
·
Sleeps for a certain amount of time. (passing time
without doing anything and w/o using CPU)
·
Two overloaded versions - one with milliseconds, one
with milliseconds and nanoseconds.
·
Throws an InterruptedException. (must be caught)
·
After the time expires, the sleeping thread goes to
ready state. It may not execute immediately after the time expires. If there
are other threads in ready state, it may have to compete with those threads to
run. The correct statement is the sleeping thread would execute some time
after the specified time period has elapsed.
·
If interrupt method is invoked on a sleeping thread,
the thread moves to ready state. The next time it begins running, it executes
the InterruptedException handler.
3.
Suspending
·
Suspend and resume
are instance methods and are deprecated in 1.2
·
A thread that receives a suspend call, goes to
suspended state and stays there until it receives a resume call on it.
·
A thread can suspend it itself, or another thread can
suspend it.
·
But, a thread can be resumed only by another thread.
·
Calling resume on a thread that is not suspended has no
effect.
·
Compiler won't warn you if suspend and resume are
successive statements, although the thread may not be able to be restarted.
4.
Blocking
·
Methods that are performing I/O have to wait for some
occurrence in the outside world to happen before they can proceed. This
behavior is blocking.
·
If a method needs to wait an indeterminable amount of
time until some I/O takes place, then the thread should graciously step out of
the CPU. All Java I/O methods behave this way.
·
A thread can also become blocked, if it failed to
acquire the lock of a monitor.
5.
Waiting
·
wait, notify and notifyAll
methods are not called on Thread, they're called on Object. Because the
object is the one which controls the threads in this case. It asks the threads
to wait and then notifies when its state changes. It's called a monitor.
·
Wait puts an executing thread into waiting state.(to
the monitor's waiting pool)
·
Notify moves one thread in the monitor's waiting pool
to ready state. We cannot control which thread is being notified. notifyAll is
recommended.
·
NotifyAll moves all threads in the monitor's waiting
pool to ready.
·
These methods can only be called from synchronized
code, or an IllegalMonitorStateException will be thrown. In other words,
only the threads that obtained the object's lock can call these methods.
Chapter 8
Locks, Monitors and Synchronization
·
Every object has a lock (for every synchronized code
block). At any moment, this lock is controlled by at most one thread.
·
A thread that wants to execute an object's synchronized
code must acquire the lock of the object. If it cannot acquire the lock, the
thread goes into blocked state and comes to ready only when the object's lock
is available.
·
When a thread, which owns a lock, finishes executing
the synchronized code, it gives up the lock.
·
Monitor (a.k.a Semaphore) is an object that can
block and revive threads, an object that controls client threads. Asks the
client threads to wait and notifies them when the time is right to continue,
based on its state. In strict Java terminology, any object that has some
synchronized code is a monitor.
·
2 ways to synchronize:
1.
Synchronize the entire method
·
Declare the method to be synchronized - very common
practice.
·
Thread should obtain the object's lock.
2.
Synchronize part of the method
·
Have to pass an arbitrary object which lock is to be
obtained to execute the synchronized code block (part of a method).
·
We can specify "this" in place object, to
obtain very brief locking - not very common.
·
wait - points to remember
§
calling thread gives up CPU
§
calling thread gives up the lock
§
calling thread goes to monitor's waiting pool
§
wait also has a version with timeout in milliseconds.
Use this if you're not sure when the current thread will get notified, this
avoids the thread being stuck in wait state forever.
·
notify - points to remember
§
one thread gets moved out of monitor's waiting pool to
ready state
§
notifyAll moves all the threads to ready state
§
Thread gets to execute must re-acquire the lock
of the monitor before it can proceed.
·
Note the differences between blocked and waiting.
Blocked
|
Waiting
|
Thread is waiting to get a lock on the
monitor.
(or waiting for a blocking i/o method)
|
Thread has been asked to wait. (by
means of wait method)
|
Caused by the thread tried to execute
some synchronized code. (or a blocking i/o method)
|
The thread already acquired the lock
and executed some synchronized code before coming across a wait call.
|
Can move to ready only when the lock
is available. ( or the i/o operation is complete)
|
Can move to ready only when it gets
notified (by means of notify or notifyAll)
|
·
Points for complex models:
1.
Always check monitor's state in a while loop, rather
than in an if statement.
2.
Always call notifyAll, instead of notify.
·
Class locks control the
static methods.
·
wait and sleep must
be enclosed in a try/catch for InterruptedException.
·
A single thread can obtain multiple locks on multiple
objects (or on the same object)
·
A thread owning the lock of an object can call other
synchronous methods on the same object. (this is another lock) Other threads can't
do that. They should wait to get the lock.
·
Non-synchronous methods can be called at any time by
any thread.
·
Synchronous methods are re-entrant. So they can
be called recursively.
·
Synchronized methods can be overrided to be
non-synchronous. Synchronized behavior affects only the original class.
·
Locks on inner/outer objects are independent. Getting a lock on outer object doesn't mean getting the lock on an
inner object as well, that lock should be obtained separately.
·
wait and notify should be called from synchronized
code. This ensures that while calling these methods the thread always has the
lock on the object. If you have wait/notify in non-synchronized code compiler
won't catch this. At runtime, if the thread doesn't have the lock while calling
these methods, an IllegalMonitorStateException is thrown.
·
Deadlocks can occur easily. e.g, Thread A locked Object
A and waiting to get a lock on Object B, but Thread B locked Object B and
waiting to get a lock on Object A. They'll be in this state forever.
·
It's the programmer's responsibility to avoid the
deadlock. Always get the locks in the same order.
·
While 'suspended', the thread keeps the locks it
obtained - so suspend is deprecated in 1.2
·
Use of stop is also deprecated; instead use a
flag in run method. Compiler won't warn you, if you have statements after a
call to stop, even though they are not reachable.
Chapter 3
- Modifiers
1. Modifiers are Java keywords that provide information to compiler
about the nature of the code, data and classes.
2. Access modifiers - public, protected, private
·
Only applied to class level variables. Method variables
are visible only inside the method.
·
Can be applied to class itself (only to inner classes
declared at class level, no such thing as protected or private top level class)
·
Can be applied to methods and constructors.
·
If a class is accessible, it doesn't mean, the members
are also accessible. Members' accessibility determines what is accessible and
what is not. But if the class is not accessible, the members are not
accessible, even though they are declared public.
·
If no access modifier is specified, then the
accessibility is default package visibility. All classes in the same package
can access the feature. It's called as friendly access. But friendly is not a
Java keyword. Same directory is same package in Java's consideration.
·
'private' means only the class can access it, not even
sub-classes. So, it'll cause access denial to a sub-class's own
variable/method.
·
These modifiers dictate, which classes can
access the features. An instance of a class can access the
private features of another instance of the same class.
·
'protected' means all classes in the same package (like
default) and sub-classes in any package can access the features. But a subclass
in another package can access the protected members in the super-class via only
the references of subclass or its subclasses. A subclass in the same package
doesn't have this restriction. This ensures that classes from other packages
are accessing only the members that are part of their inheritance hierarchy.
·
Methods cannot be overridden to be more private. Only
the direction shown in following figure is permitted from parent classes to
sub-classes.
private à friendly
(default) à protected à public
Parent
classes
Sub-classes
3. final
·
final features cannot be changed.
·
The final modifier applies to
classes, methods, and variables.
·
final classes cannot be sub-classed.
·
You can declare a variable in any scope to be final.
·
You may, if necessary, defer initialization of a final local
variable. Simply declare the local variable and initialize it later (for final
instance variables. You must initialize them at the time of declaration or in
constructor).
·
final variables cannot be changed (result in a
compile-time error if you do so )
·
final methods cannot be overridden.
·
Method arguments marked final are read-only. Compiler
error, if trying to assign values to final arguments inside the method.
·
Member variables marked final are not initialized by
default. They have to be explicitly assigned a value at declaration or in an
initializer block. Static finals must be assigned to a value in a static
initializer block, instance finals must be assigned a value in an instance
initializer or in every constructor. Otherwise the compiler will complain.
·
A blank final is a final variable whose
declaration lacks an initializer.
·
Final variables that are not assigned a value at the
declaration and method arguments that are marked final are called blank final
variables. They can be assigned a value at most once.
·
Local variables can be declared final as well.
·
If a
final
variable holds a reference to an
object, then the state of the object may be changed by operations on the
object, but the variable will always refer to the same object.
·
This applies also to arrays, because arrays are
objects; if a
final
variable holds a reference to an array, then the components of the
array may be changed by operations on the array, but the variable will always
refer to the same array
·
A blank final instance variable must be
definitely assigned at the end of every constructor of the class in which
it is declared; otherwise a compile-time error occurs.
·
A class can be declared
final
if its definition
is complete and no subclasses are desired or required.
·
A compile-time error occurs if the name of a
final
class
appears in the extends
clause of another class
declaration; this implies that a final
class
cannot have any subclasses.
·
A compile-time error occurs if a class is declared both
final
and abstract
, because the implementation of such a class could never be
completed.
·
Because a
final
class never has
any subclasses, the methods of a final
class are never
overridden
4. abstract
·
Can be applied to classes and methods.
·
For deferring implementation to sub-classes.
·
Opposite of final, final can't be sub-classed, abstract
must be sub-classed.
·
A class should be declared abstract,
1. if it has any abstract methods.
2. if it doesn't provide implementation to any of the abstract methods
it inherited
3. if it doesn't provide implementation to any of the methods in an
interface that it says implementing.
·
Just terminate the abstract method signature with a
';', curly braces will give a compiler error.
·
A class can be abstract even if it doesn't have any
abstract methods.
5. static
·
Can be applied to nested classes, methods, variables,
free floating code-block (static initializer)
·
Static variables are initialized at class load time. A
class has only one copy of these variables.
·
Static methods can access only static variables. (They
have no this)
·
Access by class name is a recommended way to access
static methods/variables.
·
Static initializer code is run at class load time.
·
Static methods may not be overridden to be non-static.
·
Non-static methods may not be overridden to be static.
·
Abstract methods may not be static.
·
Local variables cannot be declared as static.
·
Actually, static methods are not participating in the
usual overriding mechanism of invoking the methods based on the class of the
object at runtime. Static method binding is done at compile time, so the method
to be invoked is determined by the type of reference variable rather than the
actual type of the object it holds at runtime.
Let's say a sub-class has a static method
which 'overrides' a static method in a parent class. If you have a reference
variable of parent class type and you assign a child class object to that
variable and invoke the static method, the method invoked will be the parent
class method, not the child class method. The following code explains
this.
public class StaticOverridingTest {
public static void main(String s[])
{
Child c = new Child();
c.doStuff(); // This will invoke Child.doStuff()
Parent p = new Parent();
p.doStuff(); // This will invoke Parent.doStuff()
p = c;
p.doStuff(); // This will invoke Parent.doStuff(), rather than
Child.doStuff()
}
}
class Parent {
static int x = 100;
public static void doStuff() {
System.out.println("In Parent..doStuff");
System.out.println(x);
}
}
class Child extends Parent {
static int x = 200;
public static void doStuff() {
System.out.println("In Child..doStuff");
System.out.println(x);
}
}
6. native
·
Can be applied to methods only. (static methods also)
·
Written in a non-Java language, compiled for a single
machine target type.
·
Java classes use lot of native methods for performance
and for accessing hardware Java is not aware of.
·
Native method signature should be terminated by a ';',
curly braces will provide a compiler error.
·
native doesn't affect access qualifiers. Native methods
can be private.
·
Can pass/return Java objects from native methods.
·
System.loadLibrary is
used in static initializer code to load native libraries. If the library is not
loaded when the static method is called, an UnsatisfiedLinkError is
thrown.
7. transient
·
Can be applied to class level variables only.(Local
variables cannot be declared transient)
·
Transient variables may not be final or static.(But
compiler allows the declaration, since it doesn't do any harm. Variables marked
transient are never serialized. Static variables are not serialized anyway.)
·
Not stored as part of object's persistent state, i.e.
not written out during serialization.
·
Can be used for security.
8. synchronized
·
Can be applied to methods or parts of methods only.
·
Used to control access to critical code in
multi-threaded programs.
9. volatile
·
Can be applied to variables only.
·
Can be applied to static variables.
·
Cannot be applied to final variables.
·
Declaring a variable volatile indicates that it might
be modified asynchronously, so that all threads will get the correct value of
the variable.
·
Used in multi-processor environments.
Modifier
|
Class
|
Inner classes (Except local and anonymous classes)
|
Variable
|
Method
|
Constructor
|
Free floating Code block
|
|
public
|
Y
|
Y
|
Y
|
Y
|
Y
|
N
|
|
protected
|
N
|
Y
|
Y
|
Y
|
Y
|
N
|
|
(friendly)
No access modifier
|
Y
|
Y (OK for all)
|
Y
|
Y
|
Y
|
N
|
|
private
|
N
|
Y
|
Y
|
Y
|
Y
|
N
|
|
final
|
Y
|
Y (Except anonymous classes)
|
Y
|
Y
|
N
|
N
|
|
abstract
|
Y
|
Y (Except anonymous classes)
|
N
|
Y
|
N
|
N
|
|
static
|
N
|
Y
|
Y
|
Y
|
N
|
Y (static initializer)
|
|
native
|
N
|
N
|
N
|
Y
|
N
|
N
|
|
transient
|
N
|
N
|
Y
|
N
|
N
|
N
|
|
synchronized
|
N
|
N
|
N
|
Y
|
N
|
Y (part of method, also need to specify an
object on which a lock should be obtained)
|
|
volatile
|
N
|
N
|
Y
|
N
|
N
|
N
|
|
Chapter 4
Converting and Casting
Unary Numeric PromotionContexts:
·
Operand of the unary arithmetic operators + and -
·
Operand of the unary integer bit-wise complement
operator ~
·
During array creation, for example new int[x], where
the dimension expression x must evaluate to an int value.
·
Indexing array elements, for example table['a'], where
the index expression must evaluate to an int value.
·
Individual operands of the shift operators.
Binary numeric promotionContexts:
·
Operands of arithmetic operators *, / , %, + and -
·
Operands of relational operators <, <= , > and
>=
·
Numeric Operands of equality operators == and !=
·
Integer Operands of bit-wise operators &, ^ and |
Conversion of Primitives
1. 3 types of conversion - assignment conversion, method call
conversion and arithmetic promotion
2. boolean may not be converted to/from any non-boolean type.
3. Widening conversions accepted. Narrowing conversions rejected.
4. byte, short can't be converted to char and vice versa. ( but
can be cast )
5. Arithmetic promotion
5.1 Unary operators
·
if the operand is byte, short or char {
convert it to int;
}
else {
do nothing;
no conversion needed;
}
5.2 Binary operators
·
if one operand is double {
all double; convert the other
operand to double;
}
else if one operand is float {
all float; convert the other
operand to float;
}
else if one
operand is long {
all long; convert the other
operand to long;
}
else {
all int; convert all to int;
}
6. When assigning a literal value to a variable, the range of the
variable's data type is checked against the value of the literal and assignment
is allowed or compiler will produce an error.
char c = 3; // this will
compile, even though a numeric literal is by default an int since the range of
char will accept the value
int a = 3;
char d = a; // this won't
compile, since we're assigning an int to char
char e = -1; // this also won't
compile, since the value is not in the range of char
float f = 1.3; // this won't
compile, even though the value is within float range. Here range is not
important, but precision is. 1.3 is by default a double, so a specific cast or
f = 1.3f will work.
float f = 1/3; // this will
compile, since RHS evaluates to an int.
Float f = 1.0 / 3.0; // this
won't compile, since RHS evaluates to a double.
7. Also when assigning a final variable to a variable, even if the
final variable's data type is wider than the variable, if the value is within
the range of the variable an implicit conversion is done.
byte b;
final int a = 10;
b = a; // Legal, since value of
'a' is determinable and within range of b
final int x = a;
b = x; // Legal, since value of
'x' is determinable and within range of b
int
y;
final
int z = y;
b = z; // Illegal, since value
of 'z' is not determinable
8. Method call conversions always look for the exact data type or a
wider one in the method signatures. They will not do narrowing conversions to
resolve methods, instead we will get a compile error.
Here is the figure of allowable
primitive conversion.
byte à short à int à long à float à double
char
Casting of Primitives
9. Needed with narrowing conversions. Use with care - radical
information loss. Also can be used with widening conversions, to improve the
clarity of the code.
10. Can cast any non-boolean type to another non-boolean type.
11. Cannot cast a boolean or to a boolean type.
Conversion of Object references
12. Three types of reference variables to denote objects - class,
interface or array type.
13. Two kinds of objects can be created - class or array.
14. Two types of conversion - assignment and method call.
15. Permitted if the direction of the conversion is 'up' the inheritance
hierarchy. Means that types can be assigned/substituted to only super-types -
super-classes or interfaces. Not the other way around, explicit casting is
needed for that.
16. Interfaces can be used as types when declaring variables, so they
participate in the object reference conversion. But we cannot instantiate an
interface, since it is abstract and doesn't provide any implementation. These
variables can be used to hold objects of classes that implement the interface.
The reason for having interfaces as types may be, I think, several unrelated
classes may implement the same interface and if there's a need to deal with
them collectively one way of treating them may be an array of the interface
type that they implement.
17. Primitive arrays can be converted to only the arrays of the same primitive
type. They cannot be converted to another type of primitive array. Only object
reference arrays can be converted / cast.
18. Primitive arrays can be converted to an Object reference, but not to
an Object[] reference. This is because all arrays (primitive arrays and
Object[]) are extended from Object.
Casting of Object references
19. Allows super-types to be assigned to subtypes. Extensive checks done
both at compile and runtime. At compile time, class of the object may not be
known, so at runtime if checks fail, a ClassCastException is thrown.
20. Cast operator, instanceof operator and the == operator behave the
same way in allowing references to be the operands of them. You cannot cast or
apply instanceof or compare unrelated references, sibling references
or any incompatible references.
Compile-time Rules
·
When old and new types are classes, one class must be
the sub-class of the other.
·
When old and new types are arrays, both must contain
reference types and it must be legal to cast between those types (primitive
arrays cannot be cast, conversion possible only between same type of primitive
arrays).
·
We can always cast between an interface and a non-final
object.
Run-time rules
·
If new type is a class, the class of the expression
being converted must be new type or extend new type.
·
If new type is an interface, the class of the
expression being converted must implement the interface.
An Object reference can be converted to: (java.lang.Object)
·
an Object reference
·
a Cloneable interface reference, with casting, with
runtime check
·
any class reference, with casting, with runtime check
· any array referenece, with casting, with runtime check
·
any interface reference, with casting, with runtime
check
A Class type reference can be converted to:
·
any super-class type reference, (including Object)
·
any sub-class type reference, with casting, with
runtime check
·
an interface reference, if the class implements that
interface
·
any interface reference, with casting, with runtime
check (except if the class is final and doesn't implement the interface)
An Interface reference can be converted to:
·
an Object reference
·
a super-interface reference
·
any interface/class reference with casting, with
runtime check (except if the class is final and doesn't implement the
interface)
A Primitive Array reference can be converted to:
·
an Object reference
·
a Cloneable interface reference
·
a primitive array reference of the same type
An Object Array reference can be converted to:
·
an Object reference
·
a Cloneable interface reference
·
a super-class Array reference, including an Object
Array reference
·
any sub-class Array reference with casting, with
runtime check
No comments:
Post a Comment