SCJP Notes
SCJP Notes
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.
b 1 fal fa true
o se lse
ol
ea
n
by 8 0 - 127 (27 - 1)
te 12
8
(-
27
)
sh 1 0 - 215 - 1
or 6 215
t
in 3 0 - 231 - 1
t 2 231
lo 6 0L - 263 - 1
n 4 263
g
fl 3 0. 1. 3.4028235E
o 2 0F 4E 38
at -
45
d 6 0. 4. 1.79769313
o 4 0 9E 48623157E
u - 308
bl 32
e 4
Accessible
anywhere in the
class.
Automatically
13. All numeric data types initialized before
are signed. char is the invoking any
only unsigned integral constructor.
type.
Static variables
are initialized at
14. Object reference
class load time.
variables are initialized to
null. Can have the same
name as the class.
15. Octal literals begin
with zero. Hex literals b. Automatic variables
begin with 0X or 0x. method local Must be
initialized explicitly. (Or,
16. Char literals are single compiler will catch it.)
quoted characters or Object references can be
unicode values (begin initialized to null to make
with \u). the compiler happy. The
following code won't
17. A number is by default compile. Specify else part
an int literal, a decimal or initialize the local
number is by default a variable explicitly.
double literal.
public String testMethod (
18. 1E-5d is a valid double int a) {
literal, E2d is not (since it
starts with a letter, String tmp;
compiler thinks that it's
an identifier) if ( a > 0 ) tmp =
"Positive";
19. Two types of
variables. return tmp;
a. Member variables }
Array.length returns int i[][] = { {1,2}, new
· Can have the same name array's size. (Use Vectors int[2] }; // Correct
as a member variable, for dynamic purposes).
resolution is based on int i[] = { 1, 2, 3, 4, } ; //
scope. 24. Array size is never Correct
specified with the
20. Arrays are Java reference variable, it is 28. Array indexes start
objects. If you create an always maintained with with 0. Index is an int
array of 5 Strings, there the array object. It is data type.
will be 6 objects created. maintained in
array.length, which is a 29. Square brackets can
21. Arrays should be final instance variable. come after datatype or
before/after variable
Declared. (int[] a; 25. Anonymous arrays name. White spaces are
String b[]; Object can be created and used fine. Compiler just ignores
[]c; Size should not like this: new int[] {1,2,3} them.
be specified now) or new int[10]
Allocated 30. Arrays declared even
(constructed). ( a 26. Arrays with zero as member variables also
= new int[10]; c = elements can be created. need to be allocated
new args array to the main memory explicitly.
String[arraysize] ) method will be a zero
element array if no static int a[];
Initialized. for (int command parameters are
i = 0; i < a.length; specified. In this case static int b[] = {1,2,3};
a[i++] = 0) args.length is 0.
public static void
22. The above three can
27. Comma after the last main(String s[]) {
be done in one step.
initializer in array
declaration is ignored. System.out.println(a[0]);
int a[] = { 1, 2, 3 }; (or )
// Throws a null pointer
int[] i = new int[2] { 5, exception
int a[] = new int[] { 1, 2,
10}; // Wrong
3 }; But never specify the
System.out.println(b[0]);
size with the new
int i[5] = { 1, 2, 3, 4, 5}; // // This code runs fine
statement.
Wrong
System.out.println(a); //
23. Java arrays are static
int[] i[] = {{}, new int[] Prints 'null'
arrays. Size has to be
{} }; // Correct
specified at compile time.
System.out.println(b); //
Prints a string which is static public void mechanism for reclaiming
returned by toString main(String[] s) memory from objects that
are no longer in use, and
} 35. args array's name is making the memory
not important. args[0] is available for new objects.
31. Once declared and the first argument.
allocated (even for local args.length gives no. of 43. An object being no
arrays inside methods), arguments. longer in use means that
array elements are it can't be referenced by
automatically initialized 36. main method can be any 'active' part of the
to the default values. overloaded. program.
32. If only declared (not 37. main method can be 44. Garbage collection
constructed), member final. runs in a low priority
array variables default to thread. It may kick in
null, but local array 38. A class with a when memory is too low.
variables will not default different main signature No guarantee.
to null. or w/o main method will
compile. But throws a 45. It's not possible to
33. Java doesn't support runtime error. force garbage collection.
multidimensional arrays Invoking System.gc may
formally, but it supports 39. A class without a main start garbage collection
arrays of arrays. From the method can be run by process.
specification - "The JVM, if its ancestor class
number of bracket pairs has a main method. (main 46. The automatic
indicates the depth of is just a method and is garbage collection
array nesting." So this can inherited) scheme guarantees that a
perform as a reference to an object is
multidimensional array. 40. Primitives are passed always valid while the
(no limit to levels of array by value. object is in use, i.e. the
nesting) object will not be deleted
41. Objects (references) leaving the reference
34. In order to be run by are passed by reference. "dangling".
JVM, a class should have a The object reference itself
main method with the is passed by value. So, it 47. There are no
following signature. can't be changed. But, the guarantees that the
object can be changed via objects no longer in use
public static void the reference. will be garbage collected
main(String args[]) and their finalizers
42. Garbage collection is a executed at all. gc might
not even be run if the being garbage collected. list that can be thrown by
program execution does this method.
not warrant it. Thus any 51. We can set the
memory allocated during reference variables to 54. finalize is called only
program execution might null, hinting the gc to once for an object. If any
remain allocated after garbage collect the exception is thrown in
program termination, objects referred by the finalize, the object is still
unless reclaimed by the variables. Even if we do eligible for garbage
OS or by other means. that, the object may not collection (at the
be gc-ed if it's attached to discretion of gc)
48. There are also no a listener. (Typical in case
guarantees on the order of AWT components) 55. gc keeps track of
in which the objects will Remember to remove the unreachable objects and
be garbage collected or listener first. garbage-collects them,
on the order in which the but an unreachable object
finalizers are called. 52. All objects have a can become reachable
Therefore, the program finalize method. It is again by letting know
should not make any inherited from the Object other objects of its
decisions based on these class. existence from its finalize
assumptions. method (when called by
53. finalize method is gc). This 'resurrection'
49. An object is only used to release system can be done only once,
eligible for garbage resources other than since finalize is called
collection, if the only memory. (such as file only one for an object.
references to the object handles and network
are from other objects connections) The order in 56. finalize can be called
that are also eligible for which finalize methods explicitly, but it does not
garbage collection. That are called may not reflect garbage collect the
is, an object can become the order in which objects object.
eligible for garbage are created. Don't rely on
collection even if there it. This is the signature of 57. finalize can be
are references pointing to the finalize method. overloaded, but only the
the object, as long as the method with original
objects with the protected void finalize() finalize signature will be
references are also throws Throwable { } called by gc.
eligible for garbage
collection. In the descendents this 58. finalize is not
method can be protected implicitly chained. A
50. Circular references do or public. Descendents finalize method in sub-
not prevent objects from can restrict the exception class should call finalize
in super class explicitly as of statement. checking is done at
its last action for proper compile and runtime to
functioning. But compiler x = 5; y = 0; y = x++; Result ensure type-safety.
doesn't enforce this check. will be x = 6, y = 5
2. Arithmetic operators -
*, /, %, +, -
59. x = 5; y = 0; y = ++x; Result
System.runFinalization will be x = 6, y = 6 · Can be applied to all
can be used to run the numeric types.
finalizers (which have not Implicit narrowing
been executed before) for conversion is done, when · Can be applied to only
the objects eligible for applied to byte, short or the numeric types, except
garbage collection. char. '+' - it can be applied to
Strings as well.
Chapter 2 Operators 1.2 Unary minus and
and assignments unary plus + -
· All arithmetic operations
The Java programming + has no effect than to are done at least with
language has included stress positivity. 'int'. (If types are smaller,
five simple arithmetic promotion happens.
operators like + - negates an expression's Result will be of a type at
(addition), - value. (2's complement least as wide as the wide
(subtraction), * for integral expressions) type of operands)
(multiplication), /
1.3 Negation !
(division) · Accuracy is lost silently
Inverts the value of a when arithmetic
1. Unary operators
boolean expression. overflow/error occurs.
1.1 Increment and Result is a nonsense value.
1.4 Complement ~
Decrement operators ++
-- · Integer division by zero
Inverts the bit pattern of
throws an exception.
an integral expression.
We have postfix and
(1's complement - 0s to 1s
prefix notation. In post-fix · % - reduce the
and 1s to 0s)
notation value of the magnitude of LHS by the
variable/expression is magnitude of RHS.
Cannot be applied to non-
modified after the value is (continuous subtraction)
integral types.
taken for the execution of
statement. In prefix 1.5 Cast () · % - sign of the result
notation, value of the entirely determined by
variable/expression is Persuades compiler to sign of LHS
modified before the value allow certain
is taken for the execution assignments. Extensive · 5 % 0 throws an
ArithmeticException. that object is called. changes the sign of a
("Vel" + 3 will work.) negative number to be
· Floating point positive. So don't use it
calculations can produce · Be aware of associativity with negative numbers, if
NaN (square root of a when multiple operands you want to preserve the
negative no) or Infinity are involved. sign. Also don't use it with
( division by zero). Float types smaller than int.
and Double wrapper System.out.println( 1 + 2 (Since types smaller than
classes have named + "3" ); // Prints 33 int are promoted to an int
constants for NaN and before any shift operation
infinities. System.out.println( "1" + and the result is cast
2 + 3 ); // Prints 123 down again, so the end
· NaN's are non-ordinal result is unpredictable.)
3. Shift operators - <<, >>,
for comparisons. x ==
>>>
Float.NaN won't work. · Shift operators can be
Use Float.IsNaN(x) But · << performs a signed left applied to only integral
equals method on shift. 0 bits are brought in types.
wrapper objects(Double from the right. Sign bit
or Float) with NaN values (MSB) is preserved. Value · -1 >> 1 is -1, not 0. This
compares Nan's correctly. becomes old value * 2 ^ x differs from simple
where x is no of bits division by 2. We can
· Infinities are ordinal. X shifted. think of it as shift
== operation rounding down.
Double.POSITIVE_INFINI · >> performs a signed
TY will give expected right shift. Sign bit is · 1 << 31 will become the
result. brought in from the left. minimum value that an
(0 if positive, 1 if negative. int can represent. (Value
· + also performs String Value becomes old value / becomes negative, after
concatenation (when any 2 ^ x where x is no of bits this operation, if you do a
operand in an expression shifted. Also called signed right shift sign bit
is a String). The language arithmetic right shift. is brought in from the left
itself overloads this and the value remains
operator. toString method · >>> performs an negative.)
of non-String object unsigned logical right
operands are called to shift. 0 bits are brought in · Negative numbers are
perform concatenation. In from the left. This represented in two's
case of primitives, a operator exists since Java complement notation.
wrapper object is created doesn't provide an (Take one's complement
with the primitive value unsigned data type and add 1 to get two's
and toString method of (except char). >>> complement)
can be cast to RHS type.
· Shift operators never · If x instanceof Y is not
shift more than the · LHS should be an object allowed by compiler, then
number of bits the type of reference expression, Y y = (Y) x is not a valid
result can have. ( i.e. int variable or an array cast expression. If x
32, long 64) RHS operand reference. instanceof Y is allowed
is reduced to RHS % x and returns false, the
where x is no of bits in · RHS should be a class above cast is valid but
type of result. (abstract classes are fine), throws a
an interface or an array ClassCastException at
int x; type, castable to LHS runtime. If x instanceof Y
object reference. Compiler returns true, the above
x = x >> 33; // Here error if LHS & RHS are cast is valid and runs fine.
actually what happens is unrelated.
4.3 Equality comparisons
x >> 1
- ==, !=
· Can't use java.lang.Class
4. Comparison operators -
or its String name as RHS. · For primitives it's a
all return boolean type.
straightforward value
4.1 Ordinal comparisons - · Returns true if LHS is a comparison. (promotions
<, <=, > , >= class or subclass of RHS apply)
class
· Only operate on numeric
· For object references,
types. Test the relative · Returns true if LHS this doesn't make much
value of the numeric implements RHS sense. Use equals method
operands. interface. for meaningful
comparisons. (Make sure
· Arithmetic promotions · Returns true if LHS is an that the class implements
apply. char can be array reference and of equals in a meaningful
compared to float. type RHS. way, like for X.equals(Y)
4.2 Object type to be true, Y instance of X
· x instanceof must be true as well)
comparison - instanceof
Component[] - legal.
· Tests the class of an · For String literals, ==
object at runtime. · x instanceof [] - illegal. will return true, this is
Checking is done at Can't test for 'any array of because of compiler
compile and runtime any type' optimization.
same as the cast operator.
· Returns false if LHS is 5. Bit-wise operators - &,
· Returns true if the object null, no exceptions are ^, |
denoted by LHS reference thrown.
· Operate on numeric and · That's why there's no · Simple assignment =.
boolean operands. logical XOR operator.
Both bits need to be · op= calculate and assign
· & - AND operator, both known to calculate the operators extended
bits must be 1 to produce result. assignment operators.
1.
· Short-circuiting doesn't · *=, /=, %=, +=, -=
· | - OR operator, any one change the result of the
bit can be 1 to produce 1. operation. But side effects · x += y means x = x + y.
might be changed. (i.e. But x is evaluated only
· ^ - XOR operator, any some statements in RHS once. Be aware.
one bit can be 1, but not might not be executed, if
both, to produce 1. short-circuit happens. Be · Assignment of reference
careful) variables copies the
· In case of booleans true reference value, not the
7. Ternary operator
is 1, false is 0. object body.
· Format a = x ? b : c ;
· Can't cast any other type · Assignment has value,
to boolean. · x should be a boolean value of LHS after
expression. assignment. So a = b = c =
6. Short-circuit logical
0 is legal. c = 0 is executed
operators - &&, ||
· Based on x, either b or c first, and the value of the
· Operate only on boolean is evaluated. Both are assignment (0) assigned
types. never evaluated. to b, then the value of that
assignment (again 0) is
· RHS might not be · b will be assigned to a if assigned to a.
evaluated (hence the x is true, else c is assigned
name short-circuit), if the to a. · Extended assignment
result can be determined operators do an implicit
only by looking at LHS. · b and c should be cast. (Useful when applied
assignment compatible to to byte, short or char)
· false && X is always a.
false. byte b = 10;
· b and c are made
· true || X is always true. identical during the b = b + 10; // Won't
operation according to compile, explicit cast
· RHS is evaluated only if promotions. required since the
the result is not certain expression evaluates to an
8. Assignment operators. int
from the LHS.
b += 10; // OK, += does an final public static void Type of Ope Ass
implicit cast from int to main(String args[]) { Operators rat ocia
byte ors tivit
int i = 0; y
9. General
Postfix [] . Left
· In Java, No overflow or i = i++;
operators (par to
underflow of integers ame Righ
happens. i.e. The values i = i++;
ters t
wrap around. Adding 1 to ) ++
the maximum int value i = i++;
--
results in the minimum
value. System.out.println(i); // Prefix ++ Righ
prints 0, since = operator Unary -- + t to
· Always keep in mind has the lowest operators - ~ ! Left
that operands are precedence.
Object new Righ
evaluated from left to creation (typ t to
right, and the operations int array[] = new int[5];
and cast e) Left
are executed in the order
of precedence and int index = 0; Multiplicat * / Left
associativity. ion/Divisio % to
array[index] = index = n/Modulus Righ
· Unary Postfix operators 3; // 1st element gets t
and all binary operators assigned to 3, not the 4th
Addition/S +- Left
(except assignment element
ubtraction to
operators) have left to
Righ
right assoiciativity. for (int c = 0; c <
array.length; c++) t
· · Used to control e l
System.loadLibrary is access to critical code in p o
used in static initializer multi-threaded programs. t c
code to load native l k
9. volatile
libraries. If the library is o
not loaded when the · Can be applied to c
static method is called, an variables only. a
UnsatisfiedLinkError is l
thrown. · Can be applied to a
static variables. n
7. transient
d
· Cannot be applied
· Can be applied to a
to final variables.
class level variables only. n
(Local variables cannot · Declaring a o
be declared transient) variable volatile indicates n
that it might be modified y
· Transient asynchronously, so that m
variables may not be final all threads will get the o
or static.(But compiler correct value of the u
allows the declaration, variable. s
since it doesn't do any c
harm. Variables marked · Used in multi- l
transient are never processor environments. a
serialized. Static variables s
M C I V M C F
are not serialized s
o l n a et o r
anyway.) e
d a n r ho n e
if s e i d s e s
· Not stored as part
i s r a t fl )
of object's persistent
state, i.e. not written out e c b r o p Y Y Y Y Y N
during serialization. r l l u a u
a e c t bl
· Can be used for s t i ic
security. s o n
e r g p N Y Y Y Y N
8. synchronized r
s C
· Can be applied to ( o o
methods or parts of E d t
methods only. x e e
c b ct
e
d n ti s
y c t
(f Y Y Y Y Y N
m a
ri (
o ti
e O
u c
n K
s i
d f
cl n
ly o
a it
) r
s i
a
N s a
ll
o e li
)
a s z
c ) e
c r
a Y Y N Y N N
e )
b (
ss
st E n N N N Y N N
m
r x a
o
a c ti
d
ct e v
if
p e
ie
t
r tr N N Y N N N
a
a
p N Y Y Y Y N n
n
ri o
si
v n
e
a y
n
t m
t
e o
u s N N N Y N Y
fi Y Y Y Y N N s y (
n ( cl n p
a E a c a
l x s h r
c s r t
e e o o
p s n f
t ) iz m
a
e e
n st N Y Y Y N Y
d t
o a (
h s · During array
o h creation, for example new
d o int[x], where the
, u dimension expression x
a l must evaluate to an int
l d value.
s b
· Indexing array
o e
elements, for example
n o
table['a'], where the index
e b
expression must evaluate
e t
to an int value.
d a
t i · Individual
o n operands of the shift
s e operators.
p d
e ) Binary numeric
c promotion
v N N Y N N N
if
ol Contexts:
y
a
a · Operands of
ti
n arithmetic operators *, / ,
le
o %, + and -
b
j · Operands of
e Chapter 4 Converting relational operators <,
c and Casting <= , > and >=
t Unary Numeric · Numeric Operands
o Promotion of equality operators ==
n and !=
w Contexts:
h · Integer Operands
· Operand of the
i of bit-wise operators &, ^
unary arithmetic
c and |
operators + and -
h
Conversion of Primitives
a · Operand of the
l unary integer bit-wise 1. 3 types of
o complement operator ~ conversion - assignment
c conversion, method call
k
conversion and arithmetic else if one char e = -1; // this also
promotion operand is float { won't compile, since the
value is not in the range
2. boolean may not all float; convert the other
of char
be converted to/from any operand to float;
non-boolean type. float f = 1.3; // this won't
}
compile, even though the
3. Widening
else if one operand is long value is within float
conversions accepted.
{ range. Here range is not
Narrowing conversions
important, but precision
rejected. all long; convert the other is. 1.3 is by default a
operand to long; double, so a specific cast
4. byte, short can't
be converted to char and or f = 1.3f will work.
}
vice versa. ( but can be
float f = 1/3; // this will
cast ) else {
compile, since RHS
5. Arithmetic all int; convert all to int; evaluates to an int.
promotion
} Float f = 1.0 / 3.0; // this
5.1 Unary operators won't compile, since RHS
6. When assigning a evaluates to a double.
· if the operand is literal value to a variable,
byte, short or char { the range of the variable's 7. Also when
data type is checked assigning a final variable
convert it to int; against the value of the to a variable, even if the
literal and assignment is final variable's data type
}
allowed or compiler will is wider than the variable,
else { produce an error. if the value is within the
range of the variable an
do nothing; no conversion char c = 3; // this will implicit conversion is
needed; compile, even though a done.
numeric literal is by
} byte b;
default an int since the
5.2 Binary operators range of char will accept
final int a = 10;
the value
· if one operand is b = a; // Legal, since value
double { int a = 3;
of 'a' is determinable and
all double; convert the char d = a; // this won't within range of b
other operand to double; compile, since we're
final int x = a;
assigning an int to char
}
b = x; // Legal, since value 10. Can cast any non- instantiate an interface,
of 'x' is determinable and boolean type to another since it is abstract and
within range of b non-boolean type. doesn't provide any
implementation. These
int y; 11. Cannot cast a
variables can be used to
boolean or to a boolean
final int z = y; hold objects of classes
type.
that implement the
b = z; // Illegal, since interface. The reason for
Conversion of Object
value of 'z' is not having interfaces as types
references
determinable may be, I think, several
12. Three types of unrelated classes may
reference variables to implement the same
8. Method call denote objects - class, interface and if there's a
conversions always look interface or array type. need to deal with them
for the exact data type or collectively one way of
13. Two kinds of
a wider one in the method treating them may be an
objects can be created -
signatures. They will not array of the interface type
class or array.
do narrowing conversions that they implement.
to resolve methods, 14. Two types of
17. Primitive arrays
instead we will get a conversion - assignment
can be converted to only
compile error. and method call.
the arrays of the same
Here is the figure of 15. Permitted if the primitive type. They
allowable primitive direction of the cannot be converted to
conversion. conversion is 'up' the another type of primitive
inheritance hierarchy. array. Only object
byte à short à int à long à reference arrays can be
Means that types can be
float à double converted / cast.
assigned/substituted to
only super-types - super-
18. Primitive arrays
classes or interfaces. Not
char can be converted to an
the other way around,
Object reference, but not
explicit casting is needed
Casting of Primitives to an Object[] reference.
for that.
This is because all arrays
9. Needed with
16. Interfaces can be (primitive arrays and
narrowing conversions.
used as types when Object[]) are extended
Use with care - radical
declaring variables, so from Object.
information loss. Also can
they participate in the
be used with widening Casting of Object
object reference
conversions, to improve references
conversion. But we cannot
the clarity of the code.
19. Allows super-types · We can always · any super-class
to be assigned to cast between an interface type reference, (including
subtypes. Extensive and a non-final object. Object)
checks done both at
Run-time rules · any sub-class type
compile and runtime. At
reference, with casting,
compile time, class of the · If new type is a
with runtime check
object may not be known, class, the class of the
so at runtime if checks expression being · an interface
fail, a ClassCastException converted must be new reference, if the class
is thrown. type or extend new type. implements that interface
20. Cast operator, · If new type is an · any interface
instanceof operator and interface, the class of the reference, with casting,
the == operator behave expression being with runtime check
the same way in allowing converted must (except if the class is final
references to be the implement the interface. and doesn't implement
operands of them. You the interface)
cannot cast or apply An Object reference can
instanceof or compare be converted to: An Interface reference
unrelated references, (java.lang.Object) can be converted to:
sibling references or any
· an Object · an Object
incompatible references.
reference reference
Compile-time Rules
· a Cloneable · a super-interface
· When old and new interface reference, with reference
types are classes, one casting, with runtime
· any
class must be the sub- check
interface/class reference
class of the other.
· any class with casting, with
· When old and new reference, with casting, runtime check (except if
types are arrays, both with runtime check the class is final and
must contain reference doesn't implement the
· any array
types and it must be legal interface)
referenece, with casting,
to cast between those
with runtime check A Primitive Array
types (primitive arrays
reference can be
cannot be cast, conversion · any interface
converted to:
possible only between reference, with casting,
same type of primitive with runtime check · an Object
arrays). reference
A Class type reference can
be converted to:
· a Cloneable enclosing block, therefore · In the first section
interface reference visible in a nested block of for statement, we can
cannot be re-declared have a list of declaration
· a primitive array
inside the nested block. statements or a list of
reference of the same type
expression statements,
· A local variable in
An Object Array reference but not both. We cannot
a block may be re-
can be converted to: mix them.
declared in another local
· an Object block, if the blocks are · All expressions in
reference disjoint. the third section of for
statement will always
· a Cloneable · Method
execute, even if the first
interface reference parameters cannot be re-
expression makes the loop
declared.
condition false. There is
· a super-class
1. Loop constructs no short -circuit here.
Array reference, including
an Object Array reference 2. Selection
· 3 constructs - for,
while, do Statements
· any sub-class
Array reference with · if takes a boolean
· All loops are
casting, with runtime arguments. Parenthesis
controlled by a boolean
check required. else part is
expression.
optional. else if structure
Chapter 5 Flow Control
· In while and for, provides multiple
and Exceptions
the test occurs at the top, selective branching.
Unreachable so if the test fails at the
first time, body of the loop · switch takes an
statements produce a
might not be executed at argument of byte, short,
compile-time error.
all. char or int.(assignment
while (false) { x = 3; } // compatible to int)
won't compile · In do, test occurs
at the bottom, so the body · case value should
for (;false;) { x =3; } // is executed at least once. be a constant expression
won't compile that can be evaluated at
· In for, we can compile time.
if (false) {x = 3; } // will declare multiple variables
compile, to provide the in the first part of the loop · Compiler checks
ability to conditionally separated by commas, each case value against
compile the code. also we can have multiple the range of the switch
statements in the third expression's data type.
· Local variables The following code won't
part separated by
already declared in an compile.
commas.
byte b; 3. Branching · An exception is an
statements event that occurs during
switch (b) {
the execution of a
· break statement
case 200: // 200 not in program that disrupts the
can be used with any kind
range of byte normal flow of
of loop or a switch
instructions.
default: statement or just a
labeled block. · There are 3 main
} advantages for
· continue
exceptions:
· We need to place a statement can be used
break statement in each with only a loop (any kind 1. Separates error
case block to prevent the of loop). handling code from
execution to fall through "regular" code
other case blocks. But this · Loops can have
is not a part of switch labels. We can use break 2. Propagating
statement and not and continue statements errors up the call stack
enforced by the compiler. to branch out of multiple (without tedious
levels of nested loops programming)
· We can have using labels.
multiple case statements 3. Grouping error
execute the same code. · Names of the types and error
Just list them one by one. labels follow the same differentiation
rules as the name of the
· default case can be · An exception
variables.(Identifiers)
placed anywhere. It'll be causes a jump to the end
executed only if none of · Labels can have of try block. If the
the case values match. the same name, as long as exception occurred in a
they don't enclose one method called from a try
· switch can be another. block, the called method
nested. Nested case labels is abandoned.
are independent, don't · There is no
clash with outer case restriction against using · If there's a catch
labels. the same identifier as a block for the occurred
label and as the name of a exception or a parent
· Empty switch package, class, interface, class of the exception, the
construct is a valid method, field, parameter, exception is now
construct. But any or local variable. considered handled.
statement within the
switch block should come 4. Exception · At least one 'catch'
under a case label or the Handling block or one 'finally' block
default case label. must accompany a 'try'
statement. If all 3 blocks thread is killed and can be thrown within the
are present, the order is message stack trace is scope of that method.
important. dumped to System.err.
· All objects of type
(try/catch/finally)
· Use throw new java.lang.Exception are
· finally and catch xxxException() to throw checked exceptions.
can come only with try, an exception. If the (Except the classes under
they cannot appear on thrown object is null, a java.lang.RuntimeExcepti
their own. NullPointerException will on) If any method that
be thrown at the handler. contains lines of code that
· Regardless of
might throw checked
whether or not an · If an exception
exceptions, compiler
exception occurred or handler re-throws an
checks whether you've
whether or not it was exception (throw in a
handled the exceptions or
handled, if there is a catch block), same rules
you've declared the
finally block, it'll be apply. Either you need to
methods as throwing the
executed always. (Even if have a try/catch within
exceptions. Hence the
there is a return the catch or specify the
name checked exceptions.
statement in try block). entire method as
throwing the exception · If there's no code
· System.exit() and
that's being re-thrown in in try block that may
error conditions are the
the catch block. Catch throw exceptions
only exceptions where
blocks at the same level specified in the catch
finally block is not
will not handle the blocks, compiler will
executed.
exceptions thrown in a produce an error. (This is
· If there was no catch block - it needs its not the case for super-
exception or the exception own handlers. class Exception)
was handled, execution
· The method ·
continues at the
fillInStackTrace() in Java.lang.RuntimeExcep
statement after the
Throwable class throws a tion and java.lang.Error
try/catch/finally blocks.
Throwable object. It will need not be handled or
· If the exception is be useful when re- declared.
not handled, the process throwing an exception or
· An overriding
repeats looking for next error.
method may not throw a
enclosing try block up the
· The Java language checked exception unless
call hierarchy. If this
requires that methods the overridden method
search reaches the top
either catch or specify all also throws that
level of the hierarchy (the
checked exceptions that exception or a super-class
point at which the thread
of that exception. In other
was created), then the
words, an overriding | Error IndexOutOfBoundsExcepti
method may not throw on--
|
checked exceptions that >ArrayIndexOutOfBounds
are not thrown by the | Exception,
overridden method. If we StringIndexOutOfBounds
allow the overriding Exception-- Exception
methods in sub-classes to >ClassNotFoundException
, IOException--
throw more general
ClassNotSupportedExcept >EOFException,
exceptions than the
ion, FileNotFoundException,
overridden method in the
IllegalAccessException, InterruptedIOException,
parent class, then the
InstantiationException, UTFDataFormatExceptio
compiler has no way of
IterruptedException, n,
checking the exceptions
NoSuchMethodException, MalformedURLException,
the sub-class might
RuntimeException, ProtocolException,
throw. (If we declared a
AWTException, SockException,
parent class variable and
IOException UnknownHostException,
at runtime it refers to
UnknownServiceExceptio
sub-class object) This
RuntimeException-- n.
violates the concept of
>EmptyStackException,
checked exceptions and Chapter 6 - Objects and
NoSuchElementException,
the sub-classes would be Classes (Part 1)
ArithmeticException,
able to by-pass the
ArrayStoreException,
enforced checks done by Implementing OO
ClassCastException,
the compiler for checked relationships
IllegalArgumentExceptio
exceptions. This should
n, · "is a" relationship
not be allowed.
IllegalMonitorStateExcep is implemented by
Here is the exception tion, inheritance (extends
hierarchy. keyword)
IndexOutOfBoundsExcepti
Object on, · "has a"
NegativeArraySizeExcepti relationship is
| on, NullPointerException, implemented by providing
SecurityException. the class with member
|
variables.
IllegalArgumentExceptio
Throwable
n-- Overloading and
| |
>IllegalThreadStateExcep Overriding
| | tion,
· Overloading is an
NumberFormatException
| | example of polymorphism.
(operational / methods. other overridden
parametric) by method by
Excep Overriding
provid super.met
· Overriding is an tion methods
ing hodName(
example of runtime list may not
appro ), this can
polymorphism (inclusive) may throw
priate be used
vary more
· A method can have argu only to
freely. checked
the same name as ment access the
exceptions
another method in the list. immediate
than the
same class, provided it super-
overridden
forms either a valid class's
methods.
overload or override method.
Just Related super.super
the directly to won't
name sub- work. Also,
Overl Overridin
is classing. a class
oadin g
reuse Overrides outside the
g
d. the parent inheritance
Signat Signature Metho class hierarchy
ure has to be ds are method. can't use
has to the same. indep Resolved at this
be (including enden run-time technique.
differe the return t based on
Metho static
nt. type) metho type of the
ds can methods
Just a ds. object.
be don't
differe Resolv
static participate
nce in ed at
or in
return compi
non- overriding,
type is le-
static. since they
not time
Since are
enoug based
the resolved at
h. on
metho compile
metho
Access Overriding ds are time based
d
ibility methods indep on the type
signat
may cannot be enden of
ure.
vary more t, it reference
freely. private Can Overriding doesn' variable. A
than the call method t static
overridden each can call matte method in
r. But a sub- signatures reference variable type.
if two class can't are Only methods are
metho use 'super' different, it resolved at run-time.
ds (for the would have
public class Shadow {
have same formed a
the reason valid public static void
same that it overload) main(String s[]) {
signat can't use
There' Each S1 s1 = new
ure, 'this' for)
s no parent S1();
declar
limit class
ing
on method S2 s2 = new
one as Remembe numb may be S2();
static r that a er of overridden
and static
overlo at most
anoth method System.out.println(s1.s); /
aded once in any
er as can't be / prints S1
metho sub-class.
non- overridde ds a (That is,
static n to be class you cannot System.out.println(s1.getS
does non-static can have two ()); // prints S1
not and a non- have. identical
provid static
methods in
e a method System.out.println(s2.s); /
the same
valid can't be / prints S2
class)
overlo overridde
ad. n to be · Variables can also
It's a static. In be overridden, it's known System.out.println(s2.getS
compi other as shadowing or hiding. ()); // prints S2
le words, a But, member variable
s1 = s2;
time static references are resolved at
error. method compile-time. So at the
and a non- runtime, if the class of the System.out.println(s1.s)
static object referred by a ; // prints S1, not S2 -
method parent class reference
variable, is in fact a sub-
cannot
class having a shadowing // since
have the
member variable, only the variable is resolved at
same name
parent class variable is compile time
and
signature accessed, since it's
(if already resolved at
compile time based on the
class and if we call the public static void
System.out.println(s1.g method from sub-class main(String s[]) {
etS()); // prints S2 - reference variable, the
S2 s2 = new
method will return only
S2();
the super-class member
variable value. For s2.display();
// since method is
explanation, see the // Produces an output -
resolved at run
following points. S1, S2
time
· Also, methods S1 s1 = new
}
access variables only in S1();
} context of the class of the
object they belong to. If a
sub-class method calls System.out.println(s1.getS
explicitly a super class ()); // prints S1
class S1 {
method, the super class
public String s = "S1"; method always will
System.out.println(s2.getS
access the super-class
()); // prints S1 - since
variable. Super class
super-class method
public String getS() { methods will not access
the shadowing variables // always
return s; declared in subclasses accesses super-class
because they don't know variable
}
about them. (When an
object is created, }
}
instances of all its super- }
class S2 extends S1{ classes are also created.)
But the method accessed class S1 {
public String s = "S2";
will be again subject to
String s = "S1";
dynamic lookup. It is
always decided at public String getS() {
public String getS() { runtime which
implementation is called. return s;
return s;
(Only static methods are
}
} resolved at compile-time)
void display() {
}
public class Shadow2 {
In the above code, if we
System.out.println(s);
didn't have the overriding String s = "main";
getS() method in the sub- }
} · JVM knows about object, not the type of
the variable's real type at reference variable. So it is
class S2 extends S1{
any time since when it not at all possible to
String s = "S2"; allocates memory for an access a method in a
object, it also marks the super-super-class from
void display() { type with it. Objects a subclass.
always know 'who they
public class ShadowTest
are'. This is the basis of
super.display(); // {
instanceof operator.
Prints S1
public static
· Sub-classes can
void main(String s[]){
use super keyword to
System.out.println(s); //
access the shadowed
prints S2
variables in super-classes. new STChild().demo();
} This technique allows for
accessing only the }
} immediate super-class.
}
· With OO super.super is not valid.
languages, the class of the But casting the 'this' class STGrandParent {
object may not be known reference to classes up
above the hierarchy will double wealth
at compile-time (by virtue
do the trick. By this way, = 50000.00;
of inheritance). JVM from
the start is designed to variables in super- public double
support OO. So, the JVM classes above any level getWealth() {
insures that the method can be accessed from a
sub-class, since
called will be from the
variables are resolved System.out.println("Gran
real class of the object
at compile time, when dParent-" + wealth);
(not with the variable
type declared). This is we cast the 'this'
accomplished by virtual reference to a super-
return wealth;
method invocation (late super-class, the
binding). Compiler will compiler binds the }
form the argument list super-super-class
variable. But this }
and produce one method
invocation instruction - technique is not possible
class STParent extends
its job is over. The job of with methods since
STGrandParent {
identifying and calling the methods are resolved
proper target code is always at runtime, and double wealth
performed by JVM. the method gets called = 100000.00;
depends on the type of
public double // Compiler error, andParent)
getWealth() { GrandParent method (this)).wealth);
cannot be accessed
}
System.out.println("Paren /
}
t-" + wealth); /super.super.getWealth();
/
return wealth; / Calls Child method, due · An inherited
to dynamic method method, which was not
}
lookup abstract on the super-
} class, can be declared
((STParent)this).getWeal
abstract in a sub-class
class STChild extends th();
(thereby making the
STParent {
// Calls Child method, due sub-class abstract).
double wealth to dynamic method There is no restriction.
= 200000.00; lookup
· In the same
token, a subclass can be
((STGrandParent)this).ge declared abstract
public double tWealth(); regardless of whether
getWealth() { the super-class was
abstract or not.
System.out.println(wealth
System.out.println("Child- ); // Prints Child wealth · Private members
" + wealth); are not inherited, but they
do exist in the sub-classes.
System.out.println(super.
Since the private
return wealth; wealth); // Prints Parent
methods are not
wealth
} inherited, they cannot
// Prints be overridden. A method
public void in a subclass with the
Parent wealth
demo() { same signature as a
System.out.println(((STPa private method in the
rent)(this)).wealth); super-class is essentially a
getWealth(); // Calls
Child method new method, independent
// Prints GrandParent
from super-class, since the
wealth
private method in the
super.getWealth(); // super-class is not visible
Calls Parent method System.out.println(((STGr in the sub-class.
public class PrivateTest { implementation always overrides super-class hi,
calls superclass hello calls subclass hello
public static
void main(String s[]){
hello(); try {
new PTSuper().hi(); // }
Prints always Super hello();
private void
hello() { // This method is }
new PTSub().hi(); // not inherited by
Prints Super when subclasses, but exists in
catch(Exception e) {}
subclass doesn't have hi them.
method }
// Commenting void hello()
// out both the methods in throws Exception { //
Prints Sub when subclass the subclass show this. This method is
has hi method independent from super-
class hello
// The test will
PTSuper sup; then print "hello-Super"
for all three calls //
Evident from, it's allowed
sup = new PTSub();
to throw Exception
// i.e. Always
the super-class
sup.hi(); // Prints Super
implementations are System.out.println("hello-
when subclass doesn't
called Sub");
have hi method
}
System.out.println("hello-
// Prints Sub }
Super");
when subclass has hi
method }
public void static String name = public void
doSomething() { "Sharmi"; doSomething() {