Step 1 - Core Java Points
Step 1 - Core Java Points
About Author
He is a java-j2ee architect and has extensive experience in eCommerce and EAI domain.
He also holds PG diploma in Operations and also Sun, RUP (Rational Unified Process) and
webMethods certified.
People who want to make sure they haven’t missed important points while learning core java from
other resources.
1 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Notes 1: Language Fundamentals
2 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
12. Escape sequences are used to define special character values and can be represented also in Unicode value,
the following table shows them:
Escape Sequence Unicode Value Character
\b \u0008 Backspace
\t \u0009 Horizontal tabulation
\n \u000a Linefeed
\f \u000c Form feed
\r \u000d Carriage return
\’ \u0027 Apostrophe-quote
\” \u0022 Quotation mark
\\ \u005c Backslash
\xxx A character in octal representation; xxx must
range between 000 and 337
\uxxxx A unicode character, where xxxx is a
hexadecimal format number.
13. The single apostrophe ‘ need not to escaped in Strings, but it would be if specified as a character literal
‘\’’. Example:
String tx = “Delta values are labeled \”\u0394\” on the chart.”;
14. Regardless of the type of comment, it can’t be nested.
15. Default values for member variables table:
Data type Default value
boolean false
char ‘\u0000’
Integer(byte, short, int, long) 0
Floating-point(float, double) +0.0F or +0.0D
Object reference null
16. Static variables in a class are initialized to default values when class is loaded if they are not explicitly
initialized.
17. Instance variables are initialized to default values when the class is instantiated if they are not explicitly
initialized.
18. Local variables (Automatic) are NOT initialized when they are instantiated at method invocation. The compiler
javac reports use of un-initialized local variables.
19. There can be ONLY one package declaration in a Java file, and if it appears, it must be the first non-comment
statement.
20. The JVM expects to find a method named main with the signature as follows:
public static void main(String[] args)
The array is typically named args, but it could be named anything.
NOTE: You can have methods named main that have other signatures. The compiler will compile these without
comment, but the JVM will not run an application that does not have the required signature.
3 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Notes 2: Operator and assignments
4 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
primitive to a long value. The alternative in line 4 forces the compiler to cast the value n to an int and calls the
version of max that uses two int primitives.
int m = 93; //(1)
long n = 91; //(2)
long x = Math.max(m, n); //(3)
int y = Math.max(m, (int) n); //(4)
12) Widening primitive conversion is as follows (it doesn’t lose information about the magnitude of a value), and any
other conversion is called narrowing primitive conversion and may cause lose of information. At runtime, casts
that lose information do not cause a runtime excpetion, and it is up to the programmer to think through all the
implications of the cast.
Byte short
int long float double
Char
13) Integers of int (32-bit) or smaller can be converted to floating-point representation, but because a float also uses
only 32 bits and must include exponent information, there can be a loss of precision.
14) All six numbers types in Java are signed meaning they can be negative or positive.
15) The ONLY integer primitive that is not treated as a signed number is char, which represents a Unicode character.
16) All conversion of primitive’s data types take place at compile time.
17) Arithmetic operations:
a) For unary operators if byte – short - char Æ converted to int.
b) For Binary operands:
i) If one of operands is double the other operand is converted to a double.
ii) If one of the operand is float, the other operand is converted to float.
iii) If one of the operand is long, the other operand is converted to long.
c) Else both the operands are converted to int.
18) Ranges of primitive data types:
Type Bits Bytes Minimum range Maximum range
byte 8 1 -2 7 27 –1
short 16 2 -2 15 2 15 – 1
char 16 2 \u0000 \uFFFF
int 32 4 -2 31 2 31 – 1
long 64 8 -2 63 2 63 – 1
float 32 4 1.40129846432481707e-45 3.40282346638528860e+38
double 64 8 4.94065645841246544e-324 1.79769313486231570e+308
19) Depending on the storing type of the arithmetic operation the precision is done.
Example:
int x = 7/3; // x = 2
byte b = 64; b *= 4; // b = 0
20) The compiler pays attention to the known range of primitives.
Example:
int n2 = 4096L; // (1) would require a specific (int) cast
short s1 = 32000; // (2) OK
short s2 = 33000; // (3) out of range for short primitive
In spite the fact that 4096 would fit in an int primitive, the compiler will object on the first line because the literal
is in long format. You could force the compiler to accept line 3 with a specific (short) cast, but the result would
be a negative number due to the high bit being set.
5 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
21) Important examples for arithmetic expression evaluation:
Arithmetic Expression Evaluation Result when printed
4/0 Arithmetic Exception
4.0/0.0 (4.0/0.0) POSITIVE_INFINITY
-4.0/0.0 ((-4.0)/0.0) NEGATIVE_INFINITY
0.0/0.0 (0.0/0.0) NaN
22) NaN can result from mathematical functions that are undefined, such as taking the square root of a negative
number. In float to double conversion, if the float has one of the special values, NaN, POSITIVE_INFINITY, or
NEGATIVE_INFINITY, the double ends up with the corresponding double special values.
23) Float.NaN, Double.NaN are considered non-ordinal for comparisons, this means all that are false:
x < Float.NaN
x == Float.NaN
But you can test by Float.isNaN(float f), Double.isNan(double d).
24) While casting special floating-point values, such as NaN, POSITIVE_INFINITY to integer values, they will be
casted without any complaint from the compiler or an exception.
25) <variable> <op>=<expression>
is equivalent to
<variable> = (<variable type>) (<variable><operator>(<expression>)).
26) short h = 40; // OK, within range
h = h + 2; // Error can’t assign int to short
Solution for the above situation, choose one of the following:
h = (short) (h+2);
h += 2;
NOTE:
h = h + (short)2; // Requires additional casting
Will not work because binary numeric promotion leads to an int values as result of evaluating the expression on
the right-hand side.
27) System.out.println(“We put two and two together and get ” + 2 + 2);
Prints: We put two and two together and get 22
NOT: We put two and two together and get 4
Declaration: (((“We put two and two together and get ”) + 2) + 2).
28) If your code conducts operations that overflow the bounds of 32-bit or 64-bit integer arithmetic, that’s your
problem, i.e. Adding 1 to the maximum int value 2147483647 results in the minimum value –2147483648, i.e.
the values “wrap-around” for integers, and no over or underflow is indicated.
29) The dot operator has left associativity, in the following example the first call of the make() returns an object
reference that indicates the object to execute the next call, and so on …
SomeObjRef.make().make().make();
30) To get the 2’s complement:
a) Get the 1’s complement by converting 1’s to 0’s and 0’s to 1’s.
b) Add 1.
31) In the << left shift operator all bytes are moved to the left the number of places you specify, and zero is padded
from the right. [6]
32) >> Signed right shift and >>> unsigned right shift work identically for positive numbers, in >>> operator zeros
fill the left most bits, but in >> will propagate the left most one through the rest of bits.
33) When you shift a bit by a numeric value greater than the size in bits, Java does a modulus shift.
34) To shift a negative number get the 2’s complement and then shift it.
35) Object reference equality ( ==, != ):
6 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
The equality operator == and the inequality operator != can be applied to object references to test if they denote
the same object. The operands must be type compatible, i.e. it must be possible to cast one into the other’s type,
otherwise it is a compile time error.
Example:
Pizza pizza_A = new Pizza(“Sweat & Sour”);
Pizza pizza_B = new Pizza(“Hot & Spicy”);
Pizza pizza_C = pizza_A;
7 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Notes 3: Declarations and Access Control
1) Arrays are a special kind of reference type that does not fit in the class hierarchy but can always be cast to an
Object reference. Arrays also implement the Cloneable interface and inherit the clone method from the Object
class, so an array reference can be cast to a Cloneable interface.
2) Array declaration and constructor:
<elementType1> <arrayName>[] = new <elementType2> [numberofelements];
Note:
<elementType2> must be assignable to <elementType1>, i.e.: class or subclass of <elementType1>, and
when the array is constructed, all its elements are initialized to the default value for <elementType2>,
WHATEVER the array is automatic variable or member variable.
3) When constructing multi-dimensional arrays with the new operator, the length of the deeply nested arrays may be
omitted, these arrays are left unconstructed.
Example:
double matrix[][] = new double[3][];
4) Length of array object is a variable NOT a method.
5) It is legal to specify the size of an array with a variable rather than a literal.
6) The size of the array is fixed when it is created with the new operator or with special combined declaration and
initialization.
7) Anonymous arrays:
new <elementType>[] {<initialization code>}
NOTE: No array size is mentioned in the above syntax. Example of usage:
class AnonArray {
public static void main(String[] args) {
System.out.println(“Minimum value = ” + findMin(new int[] {3,5,2}));
}
public static int findMin(int[] dataSeq) {
int min = dataSeq[0];
for (int index=1; index<dataSeq.length; index++) {
if (min >= dataSeq[index])
min = dataSeq[index];
}
}
}
8) There is NO way to `bulk' initialize an array, if you want to initialize array to certain value during declaration =>
you MUST iterate with the value you want. NOTE: Initialization by means of a bracketed list can be used only
in the statement that declares the variable.
9) It is possible to create arrays of zero length of any type, a common natural occurrence of an array of zero length
is the array given as an argument to the main() method when a Java program is run without any program
arguments.
10) Primitive arrays have no hierarchy, and you can cast a primitive array reference ONLY to and from an Object
reference. Converting and casting array elements follow the same rules as primitive data types. Look to the
strange LEGAL syntax for casting an array type as shown in line 3 in the following example.
int sizes[] = {4, 6, 8, 10}; //(1)
Object obj = sizes; //(2)
int x = ((int[])obj)[2]; //(3)
8 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
11) Casting of arrays of reference types follows the same rules as casting single references.
NOTE that an array reference can be converted independantly of whether or not the array has been populated
with references to real objects. Example:
Suppose you have a class named Extend that extends a class named Base. You could then use the following code
to manipulate a reference to an array of Extend references:
Extend[] exArray = new Extend[20];
Object[] obj = exArray;
Base[]bArray = exArray;
Extend[] temp = (Extend[])bArray;
12) An import declaration does not recursively import sub-packages.
13) The order of modifiers in class declaration:
a) public. (optional)
b) final or abstract. (CANNOT appear together)
c) class. (mandatory)
d) classname. (mandatory)
e) extends. (optional)
f) superclassname. (mandatory if extends specified)
g) implements. (optional)
h) interfacelist. (mandatory if implements specified)
i) {}. (mandatory)
14) If the access modifier is omitted => (package or default accessibility), in which case they are only accessible in
the package but not in any sub-packages.
15) The ONLY access modifier allowed to the top level class is public or friendly.
16) abstract modifier implies that the class will be extended, but abstract class CANNOT be instantiated.
17) The compiler insists that a class that has an abstract method must be declared abstract, and this forces its
subclasses to provide implementation for this method, and if a subclass does not provide an implementation of its
inherited methods must be declared abstract.
18) It is NOT a MUST for an abstract class to have an abstract method.
19) Interfaces as classes CANNOT be declared protected, private, native, static, synchronized.
20) An interface is different from a class in also it can extend MORE than one interface, this follows from the fact
that a class can implement more than one interface.
Example:
public interface RunObs extends Runnable, Observer
Any class implementing this interface will have to provide methods required by both Runnable and Observer.
21) The order of modifiers in method declaration:
a) public or private or protected. (optional for package declaration)
b) abstract or final or native or static or synchronized. (optional)
c) returntype. (mandatory)
d) methodname. (mandatory)
e) throws clause. (optional)
f) {}. (mandatory)
22) abstract methods or methods defined in an interface must end with ‘;’. (i.e. abstract method is non-functional
methods that haven’t body), and abstract methods declared ONLY on interface or abstract classes.
23) The class must be declared abstract if:
a) The class has one or more abstract methods.
b) The class inherits one or more abstract methods (from an abstract parent) for which it doesn’t provide
implementation for one or more of the abstract methods of the parent class.
c) The class declares that it implements an interface but doesn’t provide implementation for EVERY method of
that interface.
9 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
24) When an abstract class implements interface there is no need to this class to implement all members of that
interface.
25) Interfaces just specify the method prototypes and not the implementation; they are by their nature, implicitly
abstract, i.e. they CANNOT be instantiated. Thus specifying an interface with the keyword abstract is not
appropriate, and should be omitted, but it won’t give compile error if specified.
26) final classes CANNOT be extended. Only a class whose definition is complete (i.e. has implementation of all the
methods) can be specified to be final.
27) The order of modifiers in variable declaration:
a) public or private or protected. (optional)
b) final or static or transient or volatile. (optional)
c) variable type. (mandatory)
d) variable name. (mandatory)
28) Within a class definition, reference variables of this class’s type can be used to access all NOT INHERITED
members regardless of their accessibility modifiers.
Example:
Class Light {
// Instance variables
private int noOfWatts;
private boolean indicator;
private String location;
10 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
33) Summary of accessibility modifiers for members:
More restrictive
Modifiers Members
public Accessible everywhere.
Protected Accessible by any class in the same package as its class, and accessible
only by subclasses of its class in other packages.
default(no modifier) Only accessible by classes, including subclasses, in the same package as
its class(package accessibility).
private Only accessible in its own class and not anywhere else.
11 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
41) Summary of other modifiers for members:
Modifiers Variables Methods
static Defines a class variable. Defines a class method.
Final Defines a constant. The method cannot be overridden.
abstract Not relevant. No method body is defined; its class is then
implicitly abstract.
synchronized Not relevant. Methods can only be executed by one thread at a
time.
native Not relevant. Declares that the method is implemented in
another language.
transient This variable’s value will not be Not applicable.
persistent (do not need to be saved)
if its object is serialized.
volatile The variable’s value can change Not applicable.
asynchronously; the compiler should
not attempt to optimize it, i.e. signal the
compiler that the designated variable
may be changed by multiple threads
and that it cannot take any shortcuts
when retrieving the value in this variable.
42) When you declare a return primitive type from a method you can return less number of bits:
Return type Can return
short byte – short
int byte – short – int
float byte – short – int – long – float
double byte – short – int – long – float – double
43) Instance variables may not be accessed from static methods.
44) The scope (visibility) of local variables is restricted to the code block in which they are declared.
12 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Notes 4: Flow Control and Exception handling
1. The rule of matching an else clause is that an else clause always refers to the nearest if which is not already
associated with another else clause.
2. The compiler always checks for unreachable code, and give “Statement not reachable” error.
Example:
for (int i = 0; i < 10; i++) {
continue;
System.out.println(“Hello” + i); // Statement not reachable
}
3. The compiler always checks for that all paths that will initialize local variables before they are used.
4. State Diagram for switch statement: [I changed the diagram a little]
13 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
6. Label rules:
Identifiers used for labels on statements do not share the same namespace as the variables, classes, and methods
of the rest of a Java program. The naming rules, as far as legal characters, are the same as for variables except
that labels are always terminated with a colon (there can be a space between the name and the colon). You can
reuse the same label name multiple points in a method as long as one usage is not nested inside another. Labels
cannot be freestanding, i.e. they must be associated with a statement.
7. break statement immediately terminates the loop code block, and can be used with an optional identifier which is
the label of an enclosing statement => control is then transferred to the statement following this enclosing
labeled statement.
Example:
class LabeledBreakOut {
public static void main(String args[]) {
int[][] squareMatrix = {{4, 3, 5},{2, 1, 6},{9, 7, 8}};
int sum = 0;
outer: // label
for (int i = 0; i < squareMatrix.length; i++ ) { // (1)
for ( int j = 0; j < squareMatrix[i].length; j++) { // (2)
if ( j == i )
break; // (3) Terminate this loop control to (5)
System.out.println( “Element[” + i + “, ” + j + “]:” + squareMatrix[i][j]);
sum += squareMatrix[i][j];
if (sum > 10)
break outer; // (4) Terminate both loops control to (6)
} // (5) Continue with the outer loop
} // end outer loop
// (6) Continue here
System.out.println(“sum: ” + sum);
}
}
8. break statement can be used in:
a. Labeled blocks.
b. Loops (for, while, do-while).
c. switch statement.
9. continue statement skips any remaining code in the block and continues with the next loop iteration, and can be
used with an optional identifier which is the label of an arbitrary enclosing loop => Control is then transferred to
the end of that enclosing labeled loop.
Example:
class LabeledSkip {
public static void main(String args[]) {
int[][] squareMatrix = {{4, 3, 5},{2, 1, 6},{9, 7, 8}};
int sum = 0;
outer: // label
for (int i = 0; i < squareMatrix.length; i++ ) { // (1)
for ( int j = 0; j < squareMatrix[i].length; j++) { // (2)
if ( j == i )
continue; // (3) Control to (5)
System.out.println( “Element[” + i + “, ” + j + “]:” + squareMatrix[i][j]);
sum += squareMatrix[i][j];
if (sum > 10)
continue outer; // (4) Control to (6)
} // (5) Continue with the outer loop
} // end outer loop
14 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
// (6) Continue here
System.out.println(“sum: ” + sum);
}
}
10. continue statement can be used ONLY in loops:
for, while, do-while
11. while statement:
12. Any variable used in the expression of while loop must be declared before the expression evaluated.
13. do-while statement:
15. None of the for-loop sections are required for the code to compile, i.e. everything in a for loop is optional.
16. All the sections of the for loop are independent of each other. The three expressions in the for statement doesn’t
need to operate on the same variables. In fact, the iterator expression does not even need to iterate a variable; it
could be a separate Java command.
Example:
for (int x1 = 0; x1 < 6; System.out.println(“iterate” + x1))
x1 += 2;
Output:
iterate2
iterate4
iterate6
NOTE: Most of who study for the certification solved the above example wrong, and say it just iterate till iterate4
only, in fact this is wrong, look to (14) for tracing help.
15 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
17. In the initialization part in the for loop, it is legal to mix expression with expressions, or variable declaration with
variable declaration, BUT it is illegal to mix variable declaration with expressions.
Example:
for (int x1 = 0, x2 = 0; x1 < 15; x1++) {} // valid
int k = 0;
for ( System.out.println(“Initial”), k = 1; k < 10; k++) {} // valid
16 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
21. try-catch-finally:
a. Block notation is MANDATORY.
b. When an exception or error is thrown, the JVM works back through the chain of method calls that led to the
error, looking for an appropriate handler to catch the object, if no handler is found, the Thread that created
the error or exception dies.
c. For each try block there can be zero or more catch blocks but only one finally block.
d. The catch blocks & finally block must appear in conjunction with a try block, and in the above order.
e. A try block must be followed by either at least one catch block or one finally block.
f. Each catch block defines an exception handler, and the header takes exactly one argument, which is the
exception, its block willing to handle.
g. The exception must be of the Throwable class or one of its subclasses.
h. When an exception is thrown, java will try to find a catch clause for the exception type. If it doesn’t found
one, it will search for a handler for a super type for the exception.
i. The compiler complains if a catch block for a superclass exception shadows the catch block for a subclass
exception, as the catch block of the subclass exception will never be executed, so the order of the catch
clauses must reflect the exception hierarchy, with the most specific exception first.
j. The finally block encloses code that is always executed at some time after the try block, regardless of
whether an exception was thrown, it executed after the try block in case of no catch block or after the catch
block if found, EXCEPT in the case of exiting the program with System.exit(0); .
k. Even if there is a return statement on the try block, the finally block will be executed after the return
statement.
l. If a method doesn’t handle an exception the finally block is executed before the exception is propagated.
22. Subclasses of Error are used to signal errors that are usually fatal and are not caught by catch statements in the
program.
23. throws clause:
The exception type specified in the throws clause in the method header can be a superclass type of the actual
exceptions thrown.
24. A subclass can override a method defined in its superclass by providing a new implementation, but the method
definition in the subclass can only specify all or subset of the exception classes (including their subclass)
specified in the throws clause of the overridden method in the superclass else it will give compilation error.
25. Runtime exceptions are referred to as unchecked exceptions because the compiler does not require explicit
provision in the code for catching them. All other exceptions, meaning all those that DO NOT derive from
java.lang.RuntimeException, are checked exceptions because the compiler will insist on provisions in the code
for cathing them. A checked exception must be caught somewhere in your code. If you use a method that throws
a checked exception but do not catch this checked exception somewhere, your code will not compile.
26. Each method must however either handle all checked exceptions by supplying a catch clause or list each
unhandled exceptions as a thrown exceptions in the throws clause.
27. To throw your exception you just use the throw keyword with an instance of an exception object to throw, and
you must caught this thrown exception if this exception is checked but if it is runtime exception or unchecked
exception you needn’t to catch.
28. If you want to handle an exception in more than one handler you can re-throw the exception, and the throw
statement must be the LAST line of your block because any line under it is unreachable.
29. Runtime exceptions are a special case in Java. Because they have a special purpose of signaling events that
happen at runtime, usually as the result of a programming error, or bug, they do not have to be caught. If not
handled they terminate the application.
30. If class extends Exception => class represent checked exception, but if the class extends RuntimeException it
mean it is unchecked.
31. getMessage() method in the Throwable class prints the error message string of this Throwable object if it was
created with an error message string; or null if it was created with no error message.
17 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
32. toString() method returns a short description of this Throwable object. If this Throwable object was created with
an error message string, then the result is the concatenation of three strings:
a. The name of the actual class of this object.
b. ": " (a colon and a space).
c. The result of the getMessage() method for this object.
If this Throwable object was created with no error message string, then the name of the actual class of this object
is returned.
33. printStackTrace() method in the Throwable class prints this Throwable and its backtrace to the standard error
stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of
the field System.err. The first line of output contains the result of the toString() method for this object. Remaining
lines represent data previously recorded by the method fillInStackTrace(). The format of this information depends
on the implementation, but the following example may be regarded as typical:
Example:
java.lang.NullPointerException
at MyClass.mash(MyClass.java:9)
at MyClass.crunch(MyClass.java:6)
at MyClass.main(MyClass.java:3)
34. fillInStackTrace() method fills in the execution stack trace. This method records within this Throwable object
information about the current state of the stack frames for the current thread. This method is useful when an
application is re-throwing an error or exception.
Example:
try {
a = b / c;
} catch(ArithmeticThrowable e) {
a = Number.MAX_VALUE;
throw e.fillInStackTrace();
}
18 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Notes 5: Object Oriented programming
1. Object is the highest-level java class and all classes are subclass of the Object class.
2. One class may only be a subclass of another class or an implementation of interface(s) if this class of a
relation (is a) of the superclass.
3. Constructing a relationship of objects:
a. is a => superclass.
b. has a => member variables.
Example:
A home is a house and has a family.
4. Methods are overloaded when there are multiple methods in the same class with the same name but with
different unique parameter list.
5. The number, type, and order of the input parameters plus the method name determines the signature.
6. As return type, visibility, throws exceptions, keywords are NOT part of the signature, changing it is NOT
ENOUGH to overload methods.
7. Java always chooses the overloaded method with the closest matching parameter list, the less to cast.
8. Why cannot final & private be overridden?
final : because final prevents method overriding.
private : means that it is not accessible outside the class in which it is defined therefore a subclass
cannot override it.
9. A subclass may override non-static methods inherited from the superclass, noting the following aspects:
a. A new method definition MUST have the SAME method signature ( method name and parameters types
not essential the parameters name) and the SAME return type.
b. The new method definition, in addition, CANNOT 'NARROW' the accessibility of the method, but it can
'WIDEN' it, i.e. can’t replace with weaker access privileges.
c. The new method definition in the subclass can only specify all or a subset of the exception classes
(including their subclasses) specified in the throws clause of the overridden method in the superclass.
d. Whether the parameters in the overriding method should be final is at the discretion of the subclass. A
method's signature does not encompass the final modifier of parameters, only their types and order.
e. An overridden method and a method in the superclass may declare their methods synchronized
independently of one other.
10. When a method is invoked on an object using a reference, it is the class of the current object denoted by the
reference, NOT the type of the reference.
When a variable of an object is accessed using a reference, it is the type of the reference, NOT the class of the
current object denoted by the reference.
References to member methods are resolved at runtime using the type of the object.
References to member variables are computed at compile time using the type of the reference. [NOTE, I found in
one of the exams [ref. 13] that this differs for static methods, and the superclass method will be always executed]
Example:
// Exceptions
class InvalidHoursException extends Exception {}
class NegativeHoursException extends InvalidHoursException {}
class ZeroHoursException extends InvalidHoursException {}
class Light {
protected String billType = “Small bill”;
protected double getBill(int noOfHours)
throws InvalidHoursException {
double smallAmount = 10.0,
smallBill = smallAmount * noOfHours;
System.out.println(billType + “: ” + smallBill);
19 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
return smallBill;
}
}
class TubeLight extends Light {
public String billType = “Large bill”;
public double getBill(final int noOfHours)
throws ZeroHoursException {
double largeAmount = 100.0,
largeBill = largeAmount * noOfHours;
System.out.println(billType + “: ” + largeBill);
return largeBill;
}
public double getBill() {
System.out.println(“No bill”);
Return 0.0;
}
}
public class Client {
public static void main(String args[])
throws InvalidHoursException {
TubeLight tubeLightRef = new TubeLight();
Light lightRef1 = tubeLightRef;
Light lightRef2 = new Light();
20 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
15. You CANNOT call constructor recursively.
16. Java specifies that when using this() call & super()
a. It MUST occur as the first statement in a constructor, followed by any other relevant statements.
b. It CAN ONLY be used in a constructor Y¨ this() and super() calls CANNOT both occur in the same
constructor.
17. If a constructor at the end of such a this() - chain (which may not be a chain at all if no this() call is invoked)
does not have explicit call to super(), then the call super() (without the parameters) is implicitly inserted to
invoke the default constructor of the superclass Y¨ subclass without any default constructor will fail to
compile if the superclass does not have default constructor (i.e. provides only non-default constructors).
18. Interface is non-functional reference type class that contains constants and methods declarations but not
functional methods.
19. We define a method within the interface but instead ending with {} end with ‘;’.
20. Interface can’t implements another interface but it can extend another interface(s).
21. The methods in an interface are all abstract by virtue of their declaration, and should not be declared abstract,
an interface is abstract by definition & therefore CANNOT be instantiated.
22. All interface methods will have public accessibility when implemented in the class (or its subclasses).
23. A class can choose to implement only some of the methods of its interfaces, i.e. give a partial implementation
of its interfaces Y¨ the class must then be declared as abstract.
24. Interfaces methods CANNOT be declared static, because they comprise the contract fulfilled by the objects
of the class implementing the interface and are therefore instance methods.
25. There are three different inheritance relations at work when defining inheritance between classes and
interfaces:
a. Linear implementation inheritance hierarchy between classes: a class extends another class.
b. Multiple inheritance hierarchy between interfaces: an interface extends other interfaces.
c. Multiple interface inheritance hierarchy between interfaces and classes: a class implements interfaces.
26. An interface can define constants, such constants are considered to be public, static and final regardless of
whether these modifiers are specified, so interface may not however declare variables unless they are
initialized (i.e. the assigning must be at the declaration statement).
27. The rule of thumb for reference values is that conversions up the hierarchy are permitted (called upcasting),
but conversions down the hierarchy require explicit casting (called downcasting). In other words,
conversions which preserve the inheritance is a relationship are allowed, other conversions require explicit
cast or are illegal.
28. Casting to a different type will compile fine but will throw ClassCastException.
29. What is reference type & object?
Example:
Component c = new Button();
a. c reference type is Component but as an object is Button.
b. At compile time Java treat c as a Component for conversion and casting, at runtime the Java treat c as
Button.
21 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
30. The rules for reference assignment are stated on the following code:
SourceType srcref;
DestinationType destRef = srcRef#
a. If the SourceType is a class type, the reference value srcRef may be assigned to the destRef reference,
provided is one of the following:
• DestinationType is a superclass of the subclass SourceType.
• DestinationType is an interface type which is implemented by the class SourceType.
b. If SourceType is an interface type, the reference value is srcRef may be assigned to destRef reference,
provided DestinationType is one of the following:
• DestinationType is Object.
• DestinationType is a super interface of sub-interface SourceType.
c. If the SourceType is an array type, the reference value in srcRef may be assigned to destRef reference,
provided DestiationType is one of the following:
• DestinationType is Object.
• DestinationType is an array type, where the element type of the SourceType can be
converted to the element type of DestinationType.
Note:
The above rules also apply for parameter passing conversions; this is reasonable, as parameters
in java are passed by value, requiring that values of actual parameters must be assignable to
formal parameters of compatible types.
31. The types of references variables can hold depened on the object hierarchy.
Example:
Object anyRef;
String myString;
Because every class in Java descends from Object, anyRef could refer to any object. However, because String
cannot be subclassed, myString can refer to a String object only.
22 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Notes 6: Garbage Collection & Object Lifetime
1. JVMs typically run the garbage collection as a low priority Thread, which is activated when the JVM feels that it
is running short of available memory.
2. Local variable are set to null after use Y¨ this makes the objects denoted by the local variable eligible for garbage
collection from this points onwards, rather than after the method terminates, this optimization technique should
ONLY be used as a last resort when resources are scarce.
3. The object is eligible for collecting after last reference that refers to it is dropped.
4. The finalizer of the object is simply a method of an object that is called just before the object is deleted (i.e. the
finalizer is the destructor of the object).
5. All the processing in the virtual machine stops while the garbage collectors run (disadvantage).
6. If the garbage collector didn’t free enough memory then the request fails (java.Lang.OutOfMemoryError).
7. The automatic garbage collection calls the finalize() method in an object which is eligible for garbage collection
(i.e. an object is being out of scope or unreachable) before actually destroying the object, finalize method is an
instance method which is defined in the class Object as protected void finalize() throws Throwable.
• A finalizer can be overridden in a subclass to take appropriate action before the object is destroyed.
• A finalizer can catch & throw exception, HOWEVER, any exception thrown but not caught by a finalizer
when invoked by the garbage collection is ignored.
• In case of finalization failure, the object still remains eligible to be disposed of at the discretion of the
garbage collection(unless it has been resurrected).
• The finalizer is only called ONCE on an object, regardless of being interrupted by any exception during its
exception.
8. Finalizers are NOT implicitly chained like constructors for subclasses Y¨ a finalizer in a subclass should
explicitly call the finalizer in its superclass as its LAST action (in a finally block).
9. The finalize method is called directly from the system and never called by the programmer directly. If called by
the programmer it acts as an ordinary method and it don’t count by the JVM Y¨ so the JVM can call it when
applying garbage collection.
10. Static members are considered always to be lived objects.
11. A finalize method can make object accessible again, 'resurrect' it, thus avoiding it being garbage collected, one
simple technique is to assign its this reference to a static variable, from which it can be retrieved later.
12. A finalizer is called ONLY ONCE on an object before being garbage collected Y¨ an object can only resurrected
ONCE.
13. Method System.gc()or Runtime.getRuntime().gc()in the java.lang package can be used to SUGGEST to the JVM
that now is a good time to run the garbage collection but you CANNOT guarantee that all objects eligible for
garbage collection will be collected). Method System.runFinalization() can be used to SUGGEST that the JVM
expend effort toward running the finalizers (which have not been executed before) for objects eligible for garbage
collection.
14. There are NO guarantees that the objects no longer in use will be garbage collected and their finalizers executed
at all. Garbage collection MIGHT NOT even be run if the program execution might remain allocated after
program termination, unless reclaimed by the operating system or by other means.
15. There are also NO guarantees on the order in which the objects will be garbage collected, or on the order in
which the finalizers will be executed. Therefore, the program should not make any decisions based on these
assumptions.
16. You should directly invoke the garbage collection system before entering a time critical section of code.
17. Instance initializer expressions are executed in the order in which the instance member variable are defined in the
class, the same is true for static initializer expressions Y¨ if a constant expression is used in the initialization of a
member variable then all its operands must be defined before they can be used in the expression.
23 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
18. A LOGICAL error can occur if the order of the initializer expressions is not correct.
Example:
Class Hotel {
private int NO_OF_ROOMS = 12;
private int MAX_NO_OF_GUEST = initMaxGuests();
private int OCCUPANCY_PER_ROOM = initOccupancy();
24 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
21. Instance initializer blocks:
• Code is executed every time an instance of the class is created.
• Is NOT contained in any method.
• A typical use of an instance initializer block is an anonymous classes, which cannot have constructors.
• A class can have more than one instance initializer block.
• Exception handling differs from that in static initializer blocks in the following respect: if an instance
initializer block does not catch a checked exception that can occur during its execution, then the exception
must be declared in the throws clause of every constructor in the class.
Example:
class InstanceInitializers {
long[] squares = new long[10];
// …
{
for(int i = 0; i < squares.length; i++)
squares[i] = i*i;
}
// …
}
22. The action of creating a new object is the biggest use of memory in a Java application.
23. Constructing initial object state:(when invoking new operator):
• Instance variables are initialized to their default values.
• Constructor is invoked which can lead to local chaining of constructors, the invocation of the constructor at
the end of the local chain of constructor invocations results in the following actions, BEFORE the
constructor’s execution resumes:
(a) Invocation of superclass's constructor implicitly or explicitly. Constructor chaining ensures that
the inherited state of the object is constructed first.
(b) Initialization of instance member variables by executing their instance initializer expressions
and any instance initializer blocks in the order they are specified in the class definition.
Example:
class SuperclassA {
Public SuperclassA() { System.out.println(“Constructor in SuperclassA”);
}
}
class SubclassB extends SuperclassA {
public SubclassB() {
this(3);
System.out.println(“Default constructor in SubclassB”);
}
public SubclassB(int i) {
System.out.println(“Non-default constructor in SubclassB”);
value = i;
}
{
System.out.println(“Instance initializer block in SubclassB”);
// value = 2; // Not Ok
}
private int value = initializerExpression();
private int initializerExpression() {
System.out.println(
“Instance initializer expression in SubclassB”);
return 1;
}
}
25 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
public class ObjectConstruction {
public static void main(String args[]) {
new SubclassB();
}
}
Output:
Constructor in SuperclassA
Instance initializer block in SubclassB
Instance initializer expression in SubclassB
Non-default constructor in SubclassB
Default constructor in SubclassB
26 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Notes 7: Inner classes
1. Inner classes are classes defined at a scope smaller than a package, i.e. you can define an inner class inside
another class, inside a method and even as part of an exception.
2. Why make a nested class?
(a) You might need to make use of the special functionality of class A from within class B without
complicating the inheritance hierarchy of either class.
(b) From the point of view of programming philosophy, if class A exists solely to help work with
class B, you might as well make class A a member of class B. This helps to keep all of the code related
to class B in a single source code file.
3. Just as member methods in a class have unlimited access to all private and other variables and methods in the
class, nested classes also have unlimited access.
4. Notes on nested top level classes:
• Is considered NOT included in inner classes as mentioned in , but considered included in inner classes as
mentioned in & also while solving question, STILL confusing till NOW. When I took my exam, I had
several question in it that makes it included in the inner classes.
• They behave much like top-level classes except that they are defined within the scope of another class.
• Interfaces are implicitly static, nested interfaces can optionally be prefixed with the keyword static and have
public accessibility.
• CANNOT have the same name as an enclosing class or package.
• static methods do NOT have a this reference & can therefore access other static methods & variables directly
in the class, this also applies to methods in a nested top- level class.
• Top-level nested class can define both static & non-static & instance members, however the code can ONLY
directly access static members in the enclosing context regardless of their accessibility.
• CAN implement any arbitrary interface.
Example:
// Filename: TopLevelClass.java
public class TopLevelClass { // (1)
// …
static class NestedTopLevelClass { // (2)
// …
interface NestedTopLevelInterface1 { // (3)
// …
}
static class NestedTopLevelClass1 // (4)
implements NestedTopLevelInterface1 {
// …
}
}
}
The full name of nested top-level class at (4) is:
TopLevelClass.NestedTopLevelClass.NestedTopLevelClass1
When compiled:
TopLevelClass$NestedTopLevelClass$NestedTopLevelClass1.class
TopLevelClass$NestedTopLevelClass$NestedTopLevelInterface1.class
TopLevelClass$NestedTopLevelClass.class
TopLevelClass.class
• import statement can be used by clients to provide shortcut for the names of nested top-level classes
and interfaces.
27 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Example:
// Filename: Client1.java
import TopLevelClass.*;
public class Client1 {
NestedTopLevelClass.NestedTopLevelClass1 objRef1 = new
NestedTopLevelClass.NestedTopLevelClass1();
}
// Filename: Client2.java
import TopLevelClass. NestedTopLevelClass.*;
public class Client2 {
NestedTopLevelClass1 = objRef1 = new NestedTopLevelClass1();
}
28 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
public void printMessage() {
System.out.println(msg);
System.out.println(this.msg);
System.out.println(InnerC.this.msg);
System.out.println(InnerB.this.msg);
InnerB.this.printMessage();
System.out.println(TLClassA.this.msg);
TLClassA.this.printMessage();
}
}
}
}
public class Client2 {
public static void main(String args[]) {
TLClassA a = new TLClassA(“1”);
TLClassA.InnerB b = a.new InnerB (“1”);
TLClassA.InnerB.InnerC c = b.new InnerC (“1”);
c.printMessage();
TLClassA.InnerB bb = new TLClassA(“2”).new InnerB (“2”);
TLClassA.InnerB.InnerC cc = bb.new InnerC (“2”);
cc.printMessage();
TLClassA.InnerB.InnerC ccc = new TLClassA(“3”).new InnerB (“3”).new
InnerC(“3”);
}
}
Output of the program:
InnerC object 1
InnerC object 1
InnerC object 1
InnerB object 1
InnerB object 1
TLClassA object 1
TLClassA object 1
InnerC object 2
InnerC object 2
InnerC object 2
InnerB object 2
InnerB object 2
TLClassA object 2
TLClassA object 2
When compiled:
TLClassA$InnerB$InnerC.class
TLClassA$InnerB.class
TLClassA.class
Client2.class
• CAN extend other classes and can themselves be extended. BUT if a name conflict arises, the inherited
member shadows the member with the same name in the enclosing class. The compiler, however,
REQUIRES that explicit references be used.
Example:
class B {
protected double x = 2.17;
}
class A {
private double x = 3.14;
class C extends B {
// private double w = x; // Compile time error
private double y = this.x; // x from the superclass
private double u = super.x; // x from the superclass
private double z = A.this.x; // x from the enclosing class
}
}
29 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
6. Notes on Local classes:
• Is a class that is defined in a block. This could be a method body, a constructor, a local block, a static
initializer or an instance initializer.
• Is ONLY visible within the context of the block, i.e. the name of the class is only valid in the context of the
block in which it is defined. Clients outside the context of a local class CANNOT create or access these
classes directly, because they are all local.
• CANNOT be specified with the keyword static. However, if the context is static (i.e. a static method or a
static initializer) then the local class is implicitly static. Otherwise, the local class is non-static.
• CANNOT have static members as they can’t provide class specific services.
• CANNOT have any accessibility. This restriction applies to local variables, and is also enforced for local
classes.
• Can access members defined within the class.
• Can access final local variables, final method parameters and final catch-block parameters in the scope of the
local context.
• Can access members inherited from its superclass in the usual way, also the standard this reference or the
super keyword can be used.
• A non-static local class can access members defined in the enclosing class explicitly, or the special form of
the this can be used.
• A non-static local class can directly access members inherited by the enclosing class, or the special form of
the this can be used.
Example:
class SuperB {
protected double x;
protected static int n;
}
class SuperC {
protected double y;
protected static int m;
}
class TopLevelA extends SuperC { // Top level class
private double z;
private static int p;
30 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
double xx = x; // non-static inherited from superclass
int nn = n; // static from superclass
}
}
}
When compiled: [as in reference ]
TopLevelA$1$NonStaticLocalD.class
TopLevelA$1$StaticLocalE.class
TopLevelA.class
SuperB.class
SuperC.class
When compiled: [as I tried with Oracle jdeveloper 3.1, I don’t know which is right]
TopLevelA$1$NonStaticLocalD.class
TopLevelA$2$StaticLocalE.class
TopLevelA.class
SuperB.class
SuperC.class
• A method can return an instance of the local class. The local class must be assignable to the return type of the
method, often supertype of the local class is specified as the return type.
7. Notes on Anonymous classes:
• It combines the process of definition and instantiation into a single step, as they are defined at the location
they are instantiated, using additional syntax with the new operator.
• The context determines whether the anonymous class is static, and the keyword static is NOT used explicitly.
• It CANNOT define constructors (as it does not have name).
• It implicitly extends the Object class.
• Syntax for defining and instantiation of anonymous classes:
new <superclass> (<optional argument list>) {<class declaration>}
• It provides a SINGLE interface implementation, and NO arguments are passed.
• Syntax for defining and instantiating anonymous class that implements an interface:
new <interface name> () {<class declaration>}
Example:
interface IDrawable {
void draw();
}
class Shape implements IDrawable {
public void draw() {
System.out.println(“Drawing a Shape.”);
}
}
class Painter { // Top level class
public Shape createShape() { // Non-static method
return new Shape() { // Extends superclass Shape
public void draw() {
System.out.println(“Drawing a new Shape.”);
}
};
}
public static IDrawable createIDrawable() { // static method
return new IDrawable() { // implements interface
public void draw() {
System.out.println(“Drawing a new IDrawable.”);
}
}
}
}
public class Client {
public static void main(String args[]) {
IDrawable[] drawables = {
new Painter().createShape(),
Painter.createIDrawable(),
newPainter().createIDrawable()
};
31 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
for (int I = 0; I < drawables.length; I++)
drawables[I].draw();
System.out.println(“Anonymous Class Names:”);
System.out.println(drawables[0].getClass());
System.out.println(drawables[1].getClass());
}
}
When compiled:
class Painter$1
class Painter$2
8. All inner classes can define ONLY non-static members, and can have static final members.
9. Summary of classes and interfaces:
32 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Notes-8: Threads
1. At most ONE object is executing per CPU, while others might be waiting for resources or waiting for
chances to execute or sleeping or dead.
2. The main() method can be finished, but the program will keep running until all the user threads are done, i.e.
Program terminates when the last non-deamon thread ends.
3. Daemon threads run in the background and do not prevent a program from terminating. For example, the
garbage collector is a daemon thread, a daemon thread is at the mercy of the runtime system, it is stopped if
there are no more user threads running.
4. The Thread class provide:
public final void setDaemon(boolean on)
Marks this thread as either a daemon thread or a user thread.
public final boolean isDaemon()
Tests if this thread is a daemon thread.
5. If the code spawning threads is not put within try - catch block in the main() method, the main thread
would finish executing before the child thread; however, the program would run until the child thread
completes.
6. Implementing threads is achieved in one of two ways:
Implementing Extending
java.lang.Runnable java.lang.Thread
1. A class implements the Runnable interface providing the 1. A class extending the Thread class overrides
run() method, which will be executed by the thread. the run() method from the Thread class to
define the code executed by the thread.
2. An object of the Thread class is created. An object of a class 2. This subclass may call a Thread constructor
implementing the Runnable interface is passed as an explicitly in its constructors to initialize the
argument to a constructor of the Thread class. thread.
Thread(Runnable threadTarget)
Thread(Runnable threadTarget, String
threadName)
3. The start() method is invoked on the Thread object created 3. The start() method inherited from the
in 2. However, the start() method returns immediately Thread class is invoked on the object of the
after a thread has been spawned. This method is defined in class to make the thread eligible for running.
the Thread class.
4. It is possible to attach more than one Thread to a Runnable
object.
7. run methods CANNOT throw exceptions so all checked exception MUST be caught using try - catch.
8. When a thread is started, it gets connected to the JVM scheduling mechanism and executes a method
declared as follows:
public void run()
NOTE: The run method in the Thread class is empty.
9. Calling your thread’s start() method doesn’t immediately cause the thread to run, it just make it eligible to
run, and the instructions after the start() call is executed before or after the thread is NOT determined. The
JVM sets up some resources and puts the Thread in the list of runnable Threads. Exactly when a thread gets
to execute depends on its priority, the activity of the other threads, and the characteristics of the particular
JVM.
33 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
10. When creating threads, implementing the Runnable interface is usually preferred to extending the Thread
class for two main reasons:
(a) Extending the Thread class means that the subclass cannot extend any other class, whereas by implementing
the Runnable interface it has this option.
(b) A class might only be interested in being Runnable, and therefore inheriting the full overhead of the Thread
class would be excessive.
11. You can simulaneously create and start a thread as in the following method:
public void startThread() {
new Thread(this).start();
}
NOTE: You might think that the new thread in the preceding example would be garbage-collected because no
reference to it is being kept, but the JVM created a reference in its list of threads.
12. A thread might be halted in mid-calculation and another can be allowed to use the same data, resulting in a
disaster => that’s why we need synchronization.
13. Java provides the foundation for solving synchronization in the Object class. Each object has an associated
lock variable that can be manipulated only by the JVM. This lock provides a monitor mechanism that can be
used to allow only one thread at a time to have access to an object (mutually exclusive lock).
14. Because it would take additional time for the JVM to check the lock condition of an object every time it is
accessed, the lock is ignored by default. The keyword synchronized is used to indicate a method or block
of code that needs to be guarded by the lock mechanism.
15. When synchronized is used as a statement, it requires a reference to the object to be locked. For
convenience, synchronized can be used as a method modifier, in which case the entire method is the block
of code, and this is automatically the object reference.
16. The monitor mechanism enforces the following rules of synchronization:
• NO other thread can enter a monitor if a thread has already acquire the monitor. Threads wishing to acquire
the monitor will wait for the monitor to become available.
• When a thread exits a monitor, a waiting thread is given the monitor, and can proceed the shared resource
associated with the monitor.
34 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
17. There are two ways in which code can be synchronized:
Synchronized methods Synchronized blocks
1. Are useful in situations where methods can manipulate 1. Allows arbitrary code to be synchronized on the
the state of an object in ways that can corrupt the state if monitor of an arbitrary object; the code block is
executed concurrently. usually related to the object on which the
synchronization is being done.
syncronized (<objectreference>) {…}
2. While a thread is inside a synchronized method of an 2. The braces of the block CANNOT be left out even
object, all other threads that wish to execute this if the code block has just one statement.
synchronized method or any other synchronized method
of the object will have to wait.
3. The non-synchronized methods of the object can of 3. Once a thread has entered the code block after
course be called at any time by any thread. acquiring the monitor of the specified object, no
other thread will be able to execute the code block
or another code requiring monitor until the monitor
is released by the object.
4. Synchronized methods can be static. 4. Inner classes can access data in their enclosing
context; An inner object might need to synchronize
on its associated outer object, in order to ensure
integrity of data in the latter.
5. Classes also have a class-specific monitor, which is 5. DO NOT synchronize on a local variable, because
analogous (similar) to the object monitor. it will accomplish nothing because every thread
has its own copy of local variables, so you should
use an instance object reference variable instead.
6. Synchronization of static methods in a class is 6. Be sure that the object chosen really protects the
independent from the synchronization of instance data you want to protect.
methods on objects of the class (i.e. A thread acquiring
the monitor on any object of the class to execute a
static synchronized method has no bearing on any
thread acquiring the monitor on any object of the class to
execute a synchronized instance method.
7. A subclass decides whether the new definition of an
inherited synchronized method will remain synchronized
in the subclass.
8. Consumes extra CPU cycles on entry and exit, so you
should not synchronize without good cause.
18. Thread objects have a distinct life cycle with four basic states:
(a) new.
(b) Runnable.
(c) Blocked (Non-runnable).
(d) Dead.
The transitions from new to runnable and from runnable to dead are simple and permanent; the transitions between
runnable and blocked occupy most of the Java programmer’s attention.
35 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
19. Thread states: [I modified the graph a little]
Ready-to-run: Means thread is eligible for running. A call to static method yield() will cause current running thread
to move to ready-to-run. Here the thread awaits its turn to get the CPU time, if the thread is carrying out a complex
computation, you should insert an occasional call to yield() in the code to ensure that other threads get a chance to
run.
Running: The CPU is currently executing the thread, the “thread schedular” decides which thread is in the running
state.
Non Runnable states: A thread can go from the running state into one of the non-runnable states, depending on the
transition, & remains their till a special transition moves it to ready-to-run state.
(a) waiting: A thread can call wait() method, it must be notified by another thread, in order to move to 'ready-
to-run' state. In the java.lang.Object class:
public final void wait()throws InterruptedException
The calling thread gives up the CPU.
The calling thread gives up the lock.
The calling thread goes into the waiting state.
The thread that calls the wait must be the owner of the object's monitor.
The following two methods in the Object class causes current thread to wait until either
another thread invokes the notify() method or the notifyAll() method for this object, or a
specified amount of time has elapsed.
void wait(long timeout) throws InterruptedException
void wait(long timeout,int nanos)throws InterruptedException
(b) sleeping: Can call sleep(), wakesup after specified amount of time elapsed.
public static void sleep(long millis) throws
InterruptedException
public static void sleep(long millis, int nanos) throws
InterruptedException
NOTE: Sleeping is not a high-precision timing operation because it depends on the clock of the underlying
operating system. In addition, there is no guarantee that the thread will immediately begin to execute
after the time delay is up; that is up to the JVM thread scheduler.
(c) blocked state: A running thread on executing a blocking operation requiring resource(like I/O method), and
also a thread is blocked if it fails to acquire the monitor on an object; the blocking opertaion must complete
before the thread can proceed to ready-to-run state.
Dead: when the thread is completed as it exits the run method to which it is attached, you CANNOT restart a dead
thread.
20. JVM also dies when the System.exit or exit method of Runtime is called.
21. Priorities: Are Integer values from 1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY), if no explicit
thread priority is specified for a thread, it is given default priority(Thread.NORM_PRIORITY).
22. A thread inherits priority of parent thread not Thread.NORM_PRIORITY & can be explicitly set or read using
methods in the Thread class:
public final void setPriority(int newPriority)
public final int getPriority()
36 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
23. Thread schedules are implementation and platform dependent.
24. If a thread that does not have a lock on an object attempts to call the object’s wait or notify method, an
IllegalMonitorStateException is thrown – typically with the message “current thread not owner”. To
ensure that is never happens, the wait(), notify(), and notifyAll() must be executed in synchronized
code.
25. When notify is called, a thread is removed from the wait set and returned to the list of runnable threads. If
more than one thread is waiting, you CANNOT control or predict which one it will be, a call to notify() has
no consequence if there are not any threads waiting. If there is a chance that more than one thread is waiting,
you can use notifyAll(), it removes all waiting threads from the wait list, ONLY one of these will actually
get a lock on the object and be allowed to execute the synchronized method, the others will run and find that
the object is still locked.
26. It is a good thing to put the wait() in a loop that test the waiting condition to guarantee that the connection
for waiting is fulfilled when this thread is notified.
27. A thread becomes the owner of the object's monitor in one of three ways:
(a) By executing a synchronized instance method of that object (i.e. by executing a synchronized method
inside this method you can call the wait method)
(b) By executing the body of a synchronized block that synchronizes on the object.
(c) For objects of type Class, by executing a synchronized static method of that class.
28. Automatic variables CANNOT be shared between threads each thread has it’s copy and can’t modify the
value of the other thread.
29. public final boolean isAlive() Tests if this thread is alive. A thread is alive if it has been started and
has not yet died.
Example:
Parent thread finds if any child threads are alive before terminating itself isAlive() will return true at all
states (including suspended) except when the thread is in new or dead state.
30. public final void join() throws InterruptedException
Waits for this thread to die. A call to this method invoked in a thread will wait and not return until thread has
completed. A parent thread can use this method to wait for its child thread to complete before continuing.
31. The programmer is ultimately responsible for avoiding deadlocks.
32. To avoid common mistakes in the exam, here is a summary of methods used with threads:
Class Method Type Needs Timeout Form
Thread yield() static no
Thread sleep(#) static try-catch always
Thread start() instance no
Thread run() instance no
Thread interrupt() instance no
Object wait() instance synchronized, try-catch optional
Object notify() instance synchronized no
Object notifyAll() instance synchronized no
37 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Notes-9: Fundamental classes
1. Object class: Is the mother class of all classes; A class definition, without the extends clause, implicitly
extends the Object class.
Method Notes
public int hashCode() Returns a hash code value for the object. If two objects are equal
according to the equals method, then calling the hashCode method
on each of the two objects must produce the same integer result.
public final Class getClass() Returns the runtime class of an object.
public boolean equals(Object obj) This method returns true if and only if x and y refer to the same
object (x==y has the value true).
Usually overridden to provide semantics of the object value equality.
Expression obj.equals(null) is always false.
protected Object clone() throws Creates and returns a copy of this object.
CloneNotSupportedException.
public String toString() Returns a string representation of the object. If the subclass does not
override this method, it returns a textual representation of the object,
which has the following fomat:
< getClass().getName()> @
<Integer.toHexString(hashCode())>
The println() method in the PrintStream will convert its argument
to a textual representation using this method.
protected void finalize() throws Called just before an object is garbage collected, so that cleanup can
Throwable be done. The default finalize() method in the Object class does
nothing.
public final void wait() throws Throws IllegalMonitorStateException if the current thread is
InterruptedException not the owner of this object's monitor.
public final void wait(long timeout)
throws InterruptedException Throws InterruptedException if this thread is interrupted by
public final void wait(long timeout, another thread.
int nanos) throws
InterruptedException
public final void notify() Wakes up a single thread that is waiting on this object's monitor. If
any threads are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the
implementation.
public final void notifyAll() Wakes up all threads that are waiting on this object's monitor.
2. The wrapper classes:
• The objects of all wrapper classes that can be instantiated are immutable.
• The Void class is not instantiable.
• Common wrapper class constructors:
Each wrapper class (except Character class has only one constructor) has the following two constructors:
i. A constructor that takes a primitive value and returns an object of the corresponding
wrapper class.
Character charObj = new Character('\n');
ii. A constructor that takes a String object representing the primitive value, and returns an
object of the corresponding wrapper class; these constructor throw
NumberFormatException if the String parameter is not valid.
Boolean b1Obj = new Boolean(“True”); // case ignored : true
Boolean b2Obj = new Boolean(“XX”); // false
Double b3Obj = new Double(“3.142”);
38 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
• Common wrapper class utility methods:
i. Each wrapper class (except Character) defines static method valueOf(String s) that
returns the wrapper new object corresponding to the primitive value represented by the String object
passed as argument; throws NumberFormatException if the String parameter is not valid.
Boolean bObj = Boolean.valueOf(“false”);
Integer intObj = Integer.valueOf(“2010”);
ii. Each overrides the equals() comparing two wrapper objects for object value equality.
iii. Each overrides the toString() returning a String representing the primitive value.
iv. Each overrides the hashCode() returning a hash value based on the primitive value in the
wrapper object.
• Numeric wrapper classes:
i. Each is a subclass of the abstract java.lang.Number class.
ii. Each defines typeValue() methods for converting primitive value in the wrapper object to
a value of any numeric primitive datatype.
Byte byteObj = new Byte ((byte)16);
Integer intObj = new Integer(42030);
short s = intObj.shortValue ();
long l = byteObj.longValue ();
Can cause potiential loss of information when primitive value in wrapper object is converted to a
narrower primitive datatype.
iii. Each numeric wrapper class defines a static method parseType(String s) that returns the
primitive numeric value represented by String represented by String Object passed as argument; these
methods throws NumberFormatException if the String parameter is not a valid argument.
iv. Most important constants: <wrapper class>.MIN_VALUE, <wrapper class>.MAX_VALUE
• Void class does not wrap any primitive value; it only denotes the class object representing the primitive
type void.
39 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
3. The Math class:
• Is a final class => CANNOT be subclassed.
• constructor is private => CANNOT be instantiated.
• All constants and methods are public and static => just access using class name.
Category Methods Example & declaration
Constants Math.PI
Math.E
Random public static double random() 0.0 ≤ random number < 1.0 Returned values are
chosen pseudo randomly with (approximately)
uniform distribution from that range.
Absolute public static <type> abs(<type> a) Returns the absolute value of a type value. If the
Overloaded methods for int, long, argument is not negative, the argument is returned.
float, double versions. NOTE: that if the argument is equal to the value of
Integer.MIN_VALUE, or Long.MIN_VALUE the most
negative representable int/long value, the result is
that same value, which is negative.
Comparing public static<type>max(<type>a, Returns the greater of two type values. NOTE: If
<type>b) Overloaded methods for int, either value is NaN, then the result is NaN. Math.max(-
long, float, double versions. 0.0, +0.0) returns +0.0
public static<type>min(<type> a, Returns the smaller of two type values. NOTE: If
<type> b) Overloaded methods for either value is NaN, then the result is NaN. Math.min(-
int,long, float, double versions. 0.0, +0.0) returns –0.0
Rounding public static double ceil(double Smallest integer greater than this number.
a) double x = 0;
x = Math.ceil(8.4); // x = 9.0
x = Math.ceil(8.9); // x = 9.0
x = Math.ceil(-9.4); // x = -9.0
x = Math.ceil(-9.8); // x = -9.0
public static double floor(double Greatest integer smaller than this number.
a) double x = 0;
x = Math.floor(8.4); // x = 8.0
x = Math.floor(8.9); // x = 8.0
x = Math.floor(-9.4); // x = -10.0
x = Math.floor(-9.8); // x = -10.0
public static long round(double a) Returns the closest long/int to the argument. If the
public static int round(float a) argument is negative infinity or any value less than or
equal to the value of WrapperClass.MIN_VALUE, the
result is equal to the value of
wrapperClass.MIN_VALUE. If the argument is positive
infinity or any value greater than or equal to the value
of WrapperClass.MAX_VALUE, the result is equal to the
value of WrapperClass.MAX_VALUE. Its algorithm
works by +0.5/-0.5 to the argument if it is
positive/negative and truncate to the nearest integer
equivalent.
int x = 0;
x = Math.round(8.4); // x = 8
x = Math.round(8.9); // x = 9
x = Math.round(-9.4); // x = -9
x = Math.round(-9.8); // x = -10
40 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
public static double rint (double Returns the closest double value to a that is equal to
a)
a mathematical integer. If two double values that are
mathematical integers are equally close to the value of
the argument, the result is the integer value that is
even.
double x = 0;
x = Math.rint(12.9); // x = 13.0
x = Math.rint(12.5); // x = 12.0
x = Math.rint(11.5); // x = 12.0
Exponential public static double exp(double a) Returns the exponential number e (i.e., 2.718...) raised
to the power of a double value.
public static double pow(double a, Returns of value of the first argument raised to the
double b) power of the second argument. If (a == 0.0), then b
must be greater than 0.0; otherwise an exception is
thrown. An exception also will occur if (a <= 0.0)
and b is not equal to a whole number.
public static double log(double a) Returns the natural logarithm (base e) of a double
value.
public static double sqrt(double Returns the square root of a double value. If the
a)
argument is NaN or less than zero, the result is NaN.
Trigonometric public static double sin(double a) Returns the trigonometric sine of an angle.
(angle input public static double cos(double a) Returns the trigonometric cosine of an angle.
in radians) public static double tan(double a) Returns the trigonometric tangent of an angle.
4. The String class:
• Is a final class implements immutable character strings, which are read only,once the string has been
created and initialized.
• Characters are represented as Unicode.
• There is no limitation in java on the length of a String, however the operating system may impose
limitations.
• A String literal is implemented as an anonymous String object; Java optimizes handling of string literals:
ONLY ONE anonymous String object is shared by all String literals with the same contents EVEN across
classes, but a String created by the new operator is always a different new object, EVEN if it’s created from
a previously predefined literal.
41 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Example:
public class AnonStrings {
static String str1 = “You cannot touch me!”;
public static void main(String args[]) {
public char charAt(int Returns the character at the specified index. An index ranges
index) from 0 to length() - 1. if index is not valid
IndexOutOfBoundsException is thrown. (case sensitive)
Search public int indexOf(int ch) Returns the index within this string of the first occurrence of
the specified character. (case sensitive)
public int indexOf(int ch, Returns the index within this string of the first occurrence of
int fromIndex) the specified character, starting the search at the specified
index. (case sensitive)
public int indexOf(String Returns the index within this string of the first occurrence of
str) the specified substring. (case sensitive)
public int indexOf(String Returns the index within this string of the first occurrence of
str, the specified substring, starting at the specified index. (case
int fromIndex)
sensitive)
public int lastIndexOf(int Returns the index within this string of the last occurrence of
ch) the specified character. (case sensitive)
42 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
public int lastIndexOf(int Returns the index within this string of the last occurrence of
ch, the specified character, searching backward starting at the
int fromIndex)
specified index. (case sensitive)
public int Returns the index within this string of the rightmost occurrence
lastIndexOf(String str) of the specified substring. (case sensitive)
public int Returns the index within this string of the last occurrence of
lastIndexOf(String str, the specified substring. (case sensitive)
int fromIndex)
Comparing public boolean Compares this string to the specified object. The result is true
equals(Object anObject)
if and only if the argument is not null and is a String object
that represents the same sequence of characters as this object.
(case sensitive)
public boolean Compares this String to another String, ignoring case
equalsIgnoreCase(String considerations.
anotherString)
public int Compares this String to another Object. If the Object is a
compareTo(Object o)
String, this function behaves like compareTo(String).
Otherwise, it throws a ClassCastException (as Strings are
comparable only to other Strings).
public int Compares two strings lexicographically. The comparison is
compareTo(String based on the Unicode value of each character in the strings.
anotherString)
The character sequence represented by this String object is
compared lexicographically to the character sequence
represented by the argument string. 0 strings are equals > 0 the
string is lexicographically greater than the argument < 0 the
string is lexicographically less than the argument.
public int Compares two strings lexicographically, ignoring case
compareToIgnoreCase(String considerations.
str)
Case public String Converts all of the characters in this String to lower case
conversion toLowerCase() using the rules of the default locale, which is returned by
Locale.getDefault(). If no character in the string has a
different lowercase version, based on calling the toLowerCase
method defined by Character, then the original string is
returned.
public String Converts all of the characters in this String to upper case
toUpperCase() using the rules of the default locale, which is returned by
Locale.getDefault(). If no character in this string has a
different uppercase version, based on calling the toUpperCase
method defined by Character, then the original string is
returned.
Concatenation public String Concatenates the specified string to the end of this string.
concat(String str)
Extracting public String trim() Removes whitespaces from both ends of this string. If this
String object represents an empty character sequence, or the
first and last characters of character sequence represented by
this String object both have codes greater than '\u0020' (the
space character), then a reference to this String object is
returned. It trims all ASCII control characters as well.
Whitespaces include:
‘\t’ \u0009 Horizontal tabulation
‘\n’ \u000A new line
‘\f’ \u000C form feed
‘\r’ \u000D carriage return
‘ ’ \u0020 space
43 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
public String Returns a new string that is a substring of this string. The
substring(int beginIndex) substring begins with the character at the specified index and
extends to the end of this string.
public String Returns a new string that is a substring of this string. The
substring(int beginIndex, substring begins at the specified beginIndex and extends to
int endIndex)
the character at index endIndex - 1. Thus the length of the
substring is endIndex-beginIndex.
Getting string public static String if the argument is null, then a string equal to "null";
representation valueOf(Object obj)
otherwise, the value of obj.toString() is returned.
for various public static String Returns the string representation of the char array argument.
types valueOf(char[] data)
public static String Returns the string representation of a specific subarray of the
valueOf(char[] data, char array argument. The offset argument is the index of the
int offset, int count)
first character of the subarray. The count argument specifies
the length of the subarray.
public static String Returns the string representation of the <primitive type>
valueOf(<primitive type> argument.
value)
• Passing null to indexOf or lastIndexOf will throw NullPointerException, passing empty string
returns 0, passing a string that’s not in the target string returns –1.
• - + and += operators are overloaded for Strings.
44 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
5. The StringBuffer class:
• Is a final thread-safe class, implements mutable character strings.
• The capacity of a StringBuffer is the maximum number of characters that a String class can
accommodate, before its size is automatically augmented.
Category Methods Example & declaration
Constructors public StringBuffer() Constructs a string buffer with no characters in it and an
initial capacity of 16 characters
public StringBuffer (int Constructs a string buffer with no characters in it and an
length) initial capacity specified by the length argument.
public StringBuffer The initial contents of the string buffer is a copy of the
(String str) argument string. The initial capacity of the string buffer is 16
plus the length of the string argument.
Changing & public int length() Returns the length of this string.
Reading public char charAt(int Returns the character at the specified index. An index ranges
characters index) from 0 to length() - 1. if index is not valid
IndexOutOfBoundsException is thrown. (case sensitive)
public void setCharAt(int The character at the specified index of this string buffer is
index, char ch) set to ch.
Appending, public StringBuffer Appends the string representation of the <primitive type>
(increase append(<primitive type> b) argument to the string buffer.
length) public StringBuffer Appends the string representation of the char array
append(char[] str) argument to this string buffer.
public StringBuffer Appends the string representation of a subarray of the char
append(char[] str, int array argument to this string buffer. Characters of the
offset, int len)
character array str, starting at index offset, are appended,
in order, to the contents of this string buffer. The length of
this string buffer increases by the value of len.
public StringBuffer Appends the string representation of the Object argument to
append(Object obj) this string buffer.
public StringBuffer Appends the string to this string buffer
append(String str)
Inserting public StringBuffer Inserts the string representation of the <primitive type>
(increase insert(int offset, argument into this string buffer.
<primitive type> b)
length) public StringBuffer Inserts the string representation of the char array argument
insert(int offset, char[] into this string buffer.
str)
public StringBuffer Inserts the string representation of a subarray of the str
insert(int index, char[] array argument into this string buffer. The subarray begins at
str, int offset, int len)
the specified offset and extends len characters. The
characters of the subarray are inserted into this string buffer
at the position indicated by index. The length of this
StringBuffer increases by len characters.
public StringBuffer Inserts the string representation of the Object argument into
insert(int offset, Object this string buffer.
obj)
public StringBuffer Inserts the string into this string buffer.
insert(int offset, String
str)
Deleting public StringBuffer Removes the characters in a substring of this
(decrease delete(int start, int end) StringBuffer. The substring begins at the specified start
length) and extends to the character at index end - 1 or to the end
of the StringBuffer if no such character exists. If start is
equal to end, no changes are made.
45 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
public StringBuffer Removes the character at the specified position in this
deleteCharAt(int index) StringBuffer (shortening the
StringBuffer by one character).
Reversing public StringBuffer The character sequence contained in this string buffer is
(maintain the reverse() replaced by the reverse of the sequence.
same length)
Manipulating public int capacity() Returns the current capacity of the String buffer. The
capacity capacity is the amount of storage available for newly
inserted characters; beyond which an allocation will occur.
public void Ensures that the capacity of the buffer is at least equal to the
ensureCapacity(int specified minimum. If the current capacity of this string
minimumCapacity)
buffer is less than the argument, then a new internal buffer is
allocated with greater capacity. The new capacity is the
larger of:
- The minimumCapacity argument.
- Twice the old capacity, plus 2.
If the minimumCapacity argument is nonpositive, this
method takes no action and simply returns.
public void setLength(int Sets the length of this String buffer. This string buffer is
newLength) altered to represent a new character sequence whose length
is specified by the argument. if the newLength argument is
less than the current length of the string buffer, the string
buffer is truncated to contain exactly the number of
characters given by the newLength argument.
• The compiler uses StringBuffer to implement the String concatenation operator + (code optimization)
Example:
String str = 4 + “U” + “Only”;
is equivalent to:
String str = new stringBuffer().append(4).append(“U”).append(“Only”).toString();
The code does not create any temporary String object when concatenating several things, where a single
StringBuffer object is modified and finally converted to a String.
46 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Notes-10: Collections
1. A collection allows a group of objects to be treated as a single unit. Arbitrary objects can be stored, retrieved and
manipulated as elements of these collections.
2. Collections Framework presents a set of standard utility classes to manage such collections.
(a) It contains core interfaces which allow collections to be manipulated independent of their implementations. These
interfaces define the common functionality exhibited by collections and facilitate data exchange between
collections.
(b) A small set of implementations that are concrete implementations of the core interfaces, providing data structures
that a program can use.
(c) A variety of algorithms to perform various operations such as, sorting and searching.
3. Collections framework is interface based, collections are implemented according to their interface type, rather
than by implementation types. By using the interfaces whenever collections of objects need to be handled,
interoperability and interchangeability are achieved.
4. Core Interfaces in the Collection Framework:
Interface Description
Collection A basic interface that defines the operations that all classes that maintain collections of objects
typically implement.
Set Extends the Collection interface for sets that maintain unique elements.
SortedSet Augments the Set interface for sets that maintain their elements in a sorted order.
List Extends the Collection interface for lists that maintain their elements in a sequence and
need NOT be unique, i.e. the elements are in order.
Map A basic interface that defines operations that classes that represent mappings of keys to
values typically implement.
SortedMap Extends the Map interface for maps that maintain their mappings in key order.
5. There is NO direct implementation of the Collection interface.
47 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
6. Implementations of the core interfaces:
Interfaces
Data structure Set SortedSet List Map SortedMap
Hash table HashSet HashMap
(√ null) (√ null)
Hashtable
( × null )
48 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
public boolean Retains only the elements in this collection that are
retainAll(Collection c) contained in the specified collection. In other words,
(optional operation). removes from this collection all of its elements that are not
contained in the specified collection.
public void clear() (optional Removes all of the elements from this collection.
operation).
Array public Object[] toArray() Returns an array containing all of the elements in this
collection. If the collection makes any guarantees as to what
order its elements are returned by its iterator, this method
must return the elements in the same order.
public Object[] Returns an array containing all of the elements in this
toArray(Object[] a) collection whose runtime type is that of the specified array.
Iterators public Iterator iterator() Returns an iterator over the elements in this collection. There
Interface has the following methods: are NO guarantees concerning the order in which the
boolean hasNext(); elements are returned (unless this collection is an instance of
Object next();
void remove();
some class that provides a guarantee).
11. The operations performed by the addAll(), removeAll(), retainAll() methods can be visualized by Venn
diagrams.
12. The class java.util.Collections class (NOT to be confused with the Collection interface) provides static
methods which implement polymorphic algorithms including sorting, searching and shuffling elements. Operates
on the collection passed as first argument of the method;most methods accept a List object while a few operate
on arbitrary Collection objects.
Methods Example & declaration
public static int Searches the specified list for the specified object using the binary search
binarySearch(List list, Object algorithm.
key)
public static void fill(List Replaces all of the elements of the specified list with the specified element.
list, Object o)
public static void Randomly permutes the specified list using a default source of randomness.
shuffle(List list)
public static void sort(List Sorts the specified list into ascending order, according to the natural
list) ordering of its elements. All elements in the list must implement the
Comparable interface. Furthermore, all elements in the list must be
mutually comparable (that is, e1.compareTo(e2) must not throw a
ClassCastException for any elements e1 and e2 in the list).
49 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
13. Sets:
• Does not define any new method, but adds the restriction that duplicated are prohibited.
• It models a mathematical set.
Set methods Corresponding mathematical operations
a.containsAll(b) b ⊆ a ? (subset)
a.addAll(b) a = a ⋃ b (union)
a.removeAll(b) a = a – b (difference)
a.retainAll(b) a = a ⋂ b (intersection)
a.clear() a = Ø (empty set)
• HashSet class as an example of sets:
HashSet()
Constructs a new, empty set.
HashSet(Collection c)
Constructs a new set containing the elements in the specified collection, but it will contain no
duplicates.
HashSet(int initialCapacity)
Constructs a new, empty set with the specified initial capacity.
HashSet(int initialCapacity, float loadFactor)
Constructs a new, empty set with the specified initial capacity and the specified load factor(the ratio
of number of elements stored to its current capacity).
Example:
Import java.util.*;
public class CharacterSets {
int nArgs = args.length;
if (areDisjunct)
System.out.println(characters + “ and ” + encountered +
“ are disjunct”);
else {
// Determine superset and subset relations
boolean isSubset = encountered.containsAll(characters);
boolean isSuperset = characters.containsAll(encountered);
if (isSubset && isSuperSet)
System.out.println(characters + “ is equivalent to ” +
encountered);
else if (isSubset)
System.out.println(characters + “ is a subset of ” +
encountered);
else if (isSuperset)
50 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
System.out.println(characters + “ is a superset of ” +
encountered);
else
System.out.println(characters + “ and ” + encountered + “
have ” + commonSubset + “ in common”);
}
// Remember the characters
encountered.addAll( characters );
}
}
Running the program with the following arguments:
Java CharacterSets i said i am maids
51 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
ListIterator Returns a view of the portion of this list between the specified
listIterator(int index) fromIndex, inclusive, and toIndex, exclusive.
Open range List subList(int Returns a view of the portion of this list between the specified
view fromIndex, int fromIndex, inclusive, and toIndex, exclusive.
toIndex)
interface ListIterator extends Iterator {
boolean hasNext();
boolean hasPrevious();
Object next();
Object previous();
int nextIndex();
int previousIndex();
void remove();
void add(Object o);
void set(Object o);
}
15. Maps:
• Defines mappings from keys to values NOT allowing duplicate keys, each key maps to at most one value.
• HashMap class is not thread-safe, the Hashtable class is.
52 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
16. Sorted Sets and Sorted Maps:
• Objects can specify their natural order by implementing the Comparable interface, or be dictated a total
order by a comparator which implements the Comparator interface.
• All comparators implement the Comparator interface, which has the following single method:
int compare(Object obj1, Object obj2)
The compare() method returns a negative integer, zero or a positive integer if the first object is less than,
equal to or greater than the second object, according to the total order.
• Objects can specify their natural order by implementing Comparable interface. Many of the standard classes
in Java API, such as wrapper classes, String, Date and File implement this interface. This interface
defines a single method:
int compareTo(Object o)
returns negative, zero, positive if the current object is less than, equal to or greater than the specified
object.
In this case a natural comparator queries objects implementing Comparable about their natural order.
Objects implementing this interface can be used:
As elements in a sorted set.
As keys in sorted map.
In lists which can be sorted automatically by the Collections.sort() method.
SortedSet interface methods SortedMap interface method
SortedSet headSet(Object toElement) returns a view SortedMap headMap(Object toElement)
of a portion of this sorted set, whose elements are strictly less
than the specified element.
SortedSet tailSet(Object toElement) returns a view SortedMap tailMap(Object toElement)
of a portion of this sorted set, whose elements are greater
than or equal the specified element.
SortedSet subSet(Object fromElement, Object SortedMap subMap(Object fromElement,
toElement) returns a view of a portion of this sorted set, Object toElement)
whose elements range from fromElement inclusive to
toElement exclusive.
Object first() returns the first (minimum) element Object firstKey()
currently in this sorted set.
Object last() returns the last (maximum) element Object lastKey()
currently in this sorted set.
Comparator comparator() returns the comparator associated Comparator comparator()
with this sorted set, or null if the natural ordering is used.
TreeSet TreeMap
TreeSet() TreeMap()
TreeSet(Comparator c) TreeMap(Comparator c)
TreeSet(Collection c) TreeMap(Map m)
TreeSet(SortedSet s) TreeMap(SortedMap m)
53 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
FINAL NOTES:
• Vector(5,10) means initial capacity 5, additional allocation (capacity increment) by 10.
• Stack extends Vector and implements a LIFO stack. With the usual push() and pop() methods, there is a
peek() method to look at the object at the top of the stack without removing it from the stack.
• BitSet class implements a Vector of bits that grows as needed. Each component of the bit set has a
boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be
examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through
logical AND, logical inclusive OR, and logical exclusive OR operations. By default, all bits in the set
initially have the value false. A BitSet has a size of 64, when created without specifying any size.
• ConcurrentModificationException exception (extends RuntimeException) may be thrown by methods
that have detected concurrent modification of a backing object when such modification is not permissible.
For example, it is not permssible for one thread to modify a Collection while another thread is iterating over
it. In general, the results of the iteration are UNDEFINED under these circumstances. Some Iterator
implementations (including those of all the collection implementations provided by the JDK) may choose to
throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they
fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in
the future.
54 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Generic Types
Generic types have been widely anticipated by the Java Community and are now part of J2SE 5.0. One of the first
places to see generic types in action is the Collections API. The Collections API provides common functionality like
LinkedLists, ArrayLists and HashMaps that can be used by more than one Java type. The next example uses the 1.4.2
libraries and the default javac compile mode.
The cast to Integer on the last line is an example of the typecasting issues that generic types aim to prevent. The issue
is that the 1.4.2 Collection API uses the Object class to store the Collection objects, which means that it cannot pick
up type mismatches at compile time. The first notification of a problem is a ClassCastException at runtime.
The same example with the generified Collections library is written as follows:
The user of a generified API has to simply declare the type used at compile type using the <> notation. No casts are
needed and in this example trying to add a String object to an Integer typed collection would be caught at compile
time.
Generic types therefore enable an API designer to provide common functionality that can be used with multiple data
types and which also can be checked for type safety at compile time.
Designing your own Generic APIs is a little more complex that simply using them. To get started look at the
java.util.Collection source and also the API guide.
55 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Autoboxing and Auto-Unboxing of Primitive Types
Converting between primitive types, like int, boolean, and their equivalent Object-based counterparts like Integer and
Boolean, can require unnecessary amounts of extra coding, especially if the conversion is only needed for a method
call to the Collections API, for example.
The autoboxing and auto-unboxing of Java primitives produces code that is more concise and easier to follow. In the
next example an int is being stored and then retrieved from an ArrayList. The 5.0 version leaves the conversion
required to transition to an Integer and back to the compiler.
Before
After
Before
After
ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i : list) { ... }
Enumerated Types
This type provides enumerated type when compared to using static final constants. If you have previously used the
identifier enum in your own application, you will need to adjust the source when compiling with javac -source 1.5 (or
its synonym -source 5).
56 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
Static Import
The static import feature, implemented as "import static", enables you to refer to static constants from a class without
needing to inherit from it. Instead of BorderLayout.CENTER each time we add a component, we can simply refer to
CENTER.
Formatted Output
Developers now have the option of using printf-type functionality to generate formatted output. This will help migrate
legacy C applications, as the same text layout can be preserved with little or no change.
Most of the common C printf formatters are available, and in addition some Java classes like Date and BigInteger
also have formatting rules. See the java.util.Formatter class for more information. Although the standard UNIX
newline '\n' character is accepted, for cross-platform support of newlines the Java %n is recommended.
System.out.printf("name count%n");
System.out.printf("%s %5d%n", user,total);
Formatted Input
The scanner API provides basic input functionality for reading data from the system console or any data stream. The
following example reads a String from standard input and expects a following int value.
The Scanner methods like next and nextInt will block if no data is available. If you need to process more complex
input, then there are also pattern-matching algorithms, available from the java.util.Formatter class.
Varargs
The varargs functionality allows multiple arguments to be passed as parameters to methods. It requires the simple ...
notation for the method that accepts the argument list and is used to implement the flexible number of arguments
required for printf.
argtest("test", "data");
57 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)
Asking is Good, so keep it up!
58 | S u m i t A g r a w a l | J 2 E E A r c h i t e c t (s u m i t _ a @ h c l. c o m)