Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1K views

Searchable Core Java Durga Sir - Java - Notes - Teachmint

This document discusses key concepts in Java language fundamentals including identifiers, reserved words, data types, and variables. It defines identifiers and reserved words, lists common data types like byte, short, int, long, float and double, and describes rules for defining valid identifiers in Java. It also provides examples of valid and invalid identifiers.

Uploaded by

Parth thakkare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Searchable Core Java Durga Sir - Java - Notes - Teachmint

This document discusses key concepts in Java language fundamentals including identifiers, reserved words, data types, and variables. It defines identifiers and reserved words, lists common data types like byte, short, int, long, float and double, and describes rules for defining valid identifiers in Java. It also provides examples of valid and invalid identifiers.

Uploaded by

Parth thakkare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 459

Language Fundamentals

1. Identifiers
2. Reserved words
3. Data types
4. Litera Is
5. Arrays
6. Types of variables
7. Var arg method
8. Main method
9. Command line arguments
10. Java coding standards
Identifier: A name in java program is called identifier. It may be class name, method name,
variable name and label name.
Example:
class Test
-C__1
{
public static void main(String[] args){
int x=lO; T TT
}T 2 3 4
} 5
Rules to define java identifiers:
Rule 1: The only allowed characters in java identifiers are:
1) a to z
2) A to Z
3) a to 9
4) _
5) $
Rule 2: If we are using any other character we will get compile time error.
Example:
1) total_number-------valid
2) Tota I#------------------i nva Iid
Rule 3: identifiers are not allowed to starts with digit.
Example:
1) ABC123---------valid
2) 123ABC---------invalid
Rule 4: java identifiers are case sensitive up course java language itself treated as case sensitive
language.

1
Example:
class Test{
int number=10;
int Number=20;
int NUMBER=20; we can differentiate with case.
int NuMbEr=30;

Rule 5: There is no length limit for java identifiers but it is not recommended to take more than
15 lengths.
Rule 6: We can't use reserved words as identifiers.
Example: int if=10; m-mm-minvalid
Rule 7: All predefined java class names and interface names we use as identifiers.
Example 1:
class Test

public static void main(String[] args){


int String=10;
System.out.println(String);
}}
Output:
10
Example 2:
class Test

public static void main(String[] args){


int Runnable=10;
System.out.println(Runnable);
}}
Output:
10
Even though it is legal to use class names and interface names as identifiers but it is not a good
programming practice.
Which of the following are valid java identifiers?

2
lLS_(valid)
2)Ca$h (valid)
3)Java2share (valid)
4)all@hands(invalid)
S)123abc (invalid)
6)Total# (invalid)
7)lnt(invalid)
8)lnteger(valid)
Reserved words:
• In java some identifiers are reserved to associate some functionality or meaning such
type of reserved identifiers are called reserved words.
Diagram:

Used keywords(48)
L...---null--7 ob·ect reference.
goto

const
Reserved words for data types:
1) byte
2) short
3) int
4) long
5) float
6) double
7) char
8) boolean
Reserved words for flow control:
1) if
2) else
3) switch
4) case
5) default
6) for
7) do

3
8) while
9) break
10) continue
11) return
Keywords for modifiers:
1) public
2) private
3) protected
4) static
5) final
6) abstract
7) synchronized
8) native
9) strictfp(1.2 version)
10) transient
11) volatile
Keywords for exception handling:
1) try
2) catch
3) finally
4) throw
5) throws
6) assert(1.4 version)
Class related keywords:
1) class
2) package
3) import
4) extends
5) implements
6) interface
Object related keywords:
1) new
2) instanceof
3) super
4) this
Void return type keyword:
• If a method won't return anything compulsory that method should be declared with the
void return type in java but it is optional in C++.

4
1) void
Unused keywords:
goto: Create several problems in old languages and hence it is banned in java.
Const: Use final instead of this.
• By mistake if we are using these keywords in our program we will get compile time
error.
Reserved literals:
1) true} values for boolean data type.
2) false
3) null----------------- default value for object reference.
Enum:
• This keyword introduced in 1.5v to define a group of named constants
Example:
enum Beer

KF, RC, KO, FO;


}
Note: All reserved words in java contain only lowercase alphabet symbols.
New keywords are:
Stri ctfp-----------1. 2
Assert -------------1.4
Enum--------------1. 5
Which of the following list contains only java reserved words?
1) final, finally, finalize (invalid)/ /here finalize is a method in Object class.
2) throw, throws, thrown(invalid)//thrown is not available in java
3) break, continue, return, exit(invalid)/ /exit is not reserved keyword
4) goto, constant(invalid)/ /here constant is not reserved keyword
5) byte, short, Integer, long(invalid)/ /here Integer is a wrapper class
6) extends, implements, imports(invalid)/ /imports keyword is not available in java
7) finalize, synchronized(invalid)/ /finalize is a method in Object class
8) instanceof', sizeOf(invalid)/ /sizeOf is not reserved keyword
9) new, delete(invalid)/ /delete is not a keyword
10) None of the above(valid)
Which of the following are valid java keywords?
1) public(valid)
2) static(valid)
3) void(valid)
4) main(invalid)
5) String(invalid)
6) args(invalid)

5
Data types: Every variable has a type, every expression has a type and all types are strictly
define more over every assignment should be checked by the compiler by the type
compatibility hence java language is considered as strongly typed language.
Java is pure object oriented programming or not?
• Java is not considered as pure object oriented programming language because several
oops features (like multiple inheritance, operator overloading) are not supported by
java moreover we are depending on primitive data types which are non objects.
Diagram:

Numeric data types char datatypes boolean data types


(to represent numbers) (to represent characters) (to represent logical values)

Integral data types floating point data types


(to represent whole (to represent real
numbers)
numb7ers ~
I--___':':::~byte
1---:;-3>-5 ho rt
t---~c:7int
;
float double
t---_:::-3>-long
• Except Boolean and char all remaining data types are considered as signed data types
because we can represent both "+ve" and"-ve" numbers.
Byte:
Size: lbyte (8bits)
Maxvalue: +127
Minvalue:-128
Range:-128to 127[-27 to 27-1]

signbit 26*1+25*1+24*1+23*1+22*1+21*1+20*1
0-----------( +ve) 64*1+32*1+16*1+8*1+4*1+2*1+1*1
1------------( -ve) +127
• The most significant bit acts as sign bit. "0" means "+ve" number and "1" means "-ve"
number.
• "+ve" numbers will be represented directly in the memory whereas "-ve" numbers will
be represented in 2's complement form.

6
Example:
byte b=10;
byte b2=130;/ /C.E:possible loss of precision
byte b=10.5;//C.E:possible loss of precision
byte b=true;/ /C.E:incompatible types
byte b="durga";/ /C.E:incompatible types
• byte data type is best suitable if we are handling data in terms of streams either from
the file or from the network.
Short:
• The most rarely used data type in java is short.
Size: 2 bytes
Range: -32768 to 32767(-215 to 215_1)
Example:
short s=130;
short s=32768;/ /C.E:possible loss of precision
short s=true;/ /C.E:incompatible types
• Short data type is best suitable for 16 bit processors like 8086 but these processors are
completely outdated and hence the corresponding short data type is also out data type.

• This is most commonly used data type in java.


Size: 4 bytes
Range:-2147483648 to 2147483647 (_231 to 231_1)
Example:
int i=130;
int i=10.5;//C.E:possible loss of precision
int i=true;/ /C.E:incompatible types
long:
• Whenever int is not enough to hold big values then we should go for long data type.
Example:
• To hold the no. Of characters present in a big file int may not enough hence the return
type of length() method is long.
long I=f.length();/ /f is a file
Size: 8 bytes
Range:-263 to 263_1
Note: All the above data types (byte, short, int and long) can be used to represent whole
numbers. If we want to represent real numbers then we should go for floating point data types.
Hoatinz Point Data types'
float double
1) If we want to 5 to 6 decimal places of 1) If we want to 14 to 15 decimal places
accuracy then we should go for float. of accuracy then we should go for
double.
2) Size:4 bytes. 2) Size:8 bytes.
3) Range:-3.4e38 to 3.4e38. 3) -1.7e308 to1.7e308.

7
4) float follows single precision. 4) double follows double precision.
boolean data type:
Size: Not applicable (Virtual machine dependent)
Range: Not applicable but allowed values are true or false.
Which of the following boolean declarations are valid?
Example 1:
boolean b=true;
boolean b=True;/ /C.E:cannot find symbol
boolean b="True";//C.E:incompatible types
boolean b=O;//C.E:incompatible types
Example 2:

incompatible types
System.out.println("hello");
found : int
System.out.println("hello");
required: boolean }
else

System.out.println("hi");
}
Char data type:
• In java we are allowed to use any worldwide alphabets character and java is Unicode
based to represent all these characters one byte is not enough compulsory we should go
for 2 bytes.
Size: 2 bytes
Range: 0 to 65535
Example:
char ch1=97;
char ch2=65536;/ /C.E:possible loss of precision
Summarv of iava orimitive data tvoe·
data type size Range Corresponding Default value
Wrapper class
byte 1 byte _27to 27_1 Byte 0
(-128 to 127)
short 2 bytes _215 to 215_1 Short 0
(-32768 to
32767)
int 4 bytes _231 to 231_1 Integer 0
(-2147483648 to
2147483647)
long 8 bytes _263 to 263_1 Long 0
float 4 bytes -3.4e38 to Float 0.0
3.4e38

8
double 8 bytes -1.7e308 to Double 0.0
1.7e308
boolean Not applicable Not Boolean false
applicable(but
allowed values
true I false)
char 2 bytes o to 65535 Character O(represents
blank space)
• The default value for the object references is "null".
literals:
• Any constant value which can be assigned to the variable is called literal.
Example:
int x=10
I 1_>constant value Iliteral
~name of variable I identifier
'------~ datatype Ikeyword
Integral literals: For the integral data types (byte, short, int and long) we can specify literal
value in the following ways.
1) Decimal literals: Allowed digits are 0 to 9.
Example: int x=10;
2) Octal literals: Allowed digits are 0 to 7. Literal value should be prefixed with zero.
Example: int x=010;
3) Hexa Decimal literals: The allowed digits are 0 to 9, A to Z. For the extra digits we can
use both upper case and lower case characters. This is one of very few areas where java
is not case sensitive. Literal value should be prefixed with ox(or)oX.
Example: int x=Ox10;
• These are the only possible ways to specify integral literal.
Which of the following are valid declarations?
1) int x=0786;IIC.E:integer number too large: 0786(invalid)
2) int x=OxFACE;(valid)
3) int x=Oxbeef;(valid)
4) int x=OxBeer;IIC.E:';' expected(invalid)
II:int x=OxBeer;
1\

5) int x=Oxabb2cd;(valid)
Example:
int x=10;
int y=010;
int z=Ox10;
System.out.printl n(x+" ----" +y+" "+Z); 1/10----8----16
• By default every integral literal is int type but we can specify explicitly as long type by
suffixing with small "I" (or) capital "l".

9
Example:
int x=10;(valid)
long 1=10L;(valid)
long 1=10;(valid)
int x=101;//C.E:possible loss of precision(invalid)
• There is no direct way to specify byte and short literals explicitly. But whenever we are
assigning integral literal to the byte variables and its value within the range of byte
compiler automatically treats as byte literal. Similarly short literal also.
Example:
byte b=10;(valid)
byte b=130;/ /C.E:possible loss of precision(invalid)
short s=32767;(valid)
short s=32768;/ /C.E:possible loss of precision(invalid)
Floating Point literals: Floating point literal is by default double type but we can specify
explicitly as float type by suffixing with f or F.
Example:
float f=123.456;/ /C.E:possible loss of precision(invalid)
float f=123.456f;(valid)
double d=123.456;(valid)
• We can specify explicitly floating point literal as double type by suffixing with d or D.
Example:
double d=123.456D;
• We can specify floating point literal only in decimal form and we can't specify in octal
and hexadecimal forms.
Example:
double d=123.456;(valid)
double d=0123.456;(valid)
double d=Ox123.456;//C.E:malformed floating point literal(invalid)
Which of the following floating point declarations are valid?
1) float f=123.456;/ /C.E:possible loss of precision(invalid)
2) float f=123.456D;/ /C.E:possible loss of precision(invalid)
3) double d=Ox123.456;/ /C.E:malformed floating point literal(invalid)
4) double d=OxFace;(valid)
5) double d=OxBeef;(valid)
• We can assign integral literal directly to the floating point data types and that integral
literal can be specified in octal and Hexa decimal form also.
Example:
double d=OxBeef;
System.out.println(d);/ /48879.0
• But we can't assign floating point literal directly to the integral types.
Example:
int x=10.0;/ /C.E:possible loss of precision
• We can specify floating point literal even in exponential form also(significant notation).

10
Example:
double d=10e2;//==>10*102(valid)
System.out.println( d);/ /1000.0
float f=10e2;//C.E:possible loss of precision(invalid)
float f=10e2F;(valid)
Boolean literals: The only allowed values for the boolean type are true (or) false where case is
important.
Example:
1) boolean b=true;(valid)
2) boolean b=O;//C.E:incompatible types(invalid)
3) boolean b=True;/ /C.E:cannot find symbol(invalid)
4) boolean b=ltrue";//C.E:incompatible types(invalid)
Char literals:
1) A char literal can be represented as single character within single quotes.
Example:
1) char ch='a';(valid)
2) char ch=a;/ /C.E:cannot find symbol(invalid)
3) char ch="a";/ /C.E:incompatible types(invalid)
4) char ch='ab';/ /C.E:unciosed character literal(invalid)
2) We can specify a char literal as integral literal which represents Unicode of that
character. We can specify that integral literal either in decimal or octal or hexadecimal
form but allowed values range is 0 to 65535.
Example:
1) char ch=97;(valid)
2) char ch=OxFace; (valid)
System.out.println( ch);/ /7
3) char ch=65536;/ /C.E: possible loss of precision(invalid)
3) We can represent a char literal by Unicode representation which is nothing but '\uxxxx'.
Example:
1) char ch1='\u0061';
System.out.println(ch1);/ /a
2) char ch2=\u0062;/ /C.E:cannot find symbol
3) char ch3='\iface';//C.E:illegal escape character
4) Every escape character in java acts as a char literal.
Example:
1) char ch='\n';//(valid)
2) char ch='\I';//C.E:illegal escape character(invalid)
Escape Character Description
\n New line
\t Horizontal tab
\r Carriage return
\f Form feed
\b Back space character

11
\' Single quote
\/1 Double quote
\\ Back space
Which of the following char declarations are valid?
1) char ch=a;/ /C.E:cannot find symbol(invalid)
2) char ch='ab';/ /C.E:unciosed character literal(invalid)
3) char ch=65536;//C.E:possible loss of precision(invalid)
4) char ch=\uface;/ /C.E:illegal character: \64206(invalid)
5) char ch='/n';/ /C.E:unciosed character literal(invalid)
6) none of the above.(valid)
String literals:
• Any sequence of characters with in double quotes is treated as String literal.
Example:
String s="bhaskar";(valid)
Diagram:
byte~ Short~

__.?/ int~long~float~double
char~ -

Arrays
1) Introduction
2) Array declaration
3) Array construction
4) Array initialization
5) Array declaration, construction, initialization in a single line.
6) length Vs lengthO method
7) Anonymous arrays
8) Array element assignments
9) Array variable assignments.
• An array is an indexed collection of fixed number of homogeneous data elements.
• The main advantage of arrays is we can represent multiple values with the same name
so that readability of the code will be improved.
• But the main disadvantage of arrays is:
• Fixed in size that is once we created an array there is no chance of increasing or
decreasing the size based on our requirement that is to use arrays concept compulsory
we should know the size in advance which may not possible always.
• We can resolve this problem by using collections.
Array declarations:
Single dimensional array declaration:

12
Example:
int[] a;/ /recommended to use because name is clearly separated from the type
int [Ja;
int all;
• At the time of declaration we can't specify the size otherwise we will get compile time
error.
Example:
int[] a;/ /valid
int[S] a;//invalid
Two dimensional array declaration:
Example:
int[][] a;
int [][]a;
int a[] []; All are valid.
int[] [Ja;
int[] a[J;
int []a[J;
Three dimensional array declaration:
Example:
int[][J[] a;
int [][J[]a;
int a[][J[];
int[] [J[]a;
int[] a[J[]; All are valid.
int[] [Jar];
int[][] [Ja;
int[J[] all;
int [Ja[][];
int [][]a[J;
Which of the following declarations are valid?
1) int[] a1,b1;/ /a-1,b-1(valid)
2) int[] a2[Lb2;/ /a-2,b-1(valid)
3) int[] []a3,b3;/ /a-2,b-2(valid)
4) int[] a,[Jb;//C.E:<identifier> expected(invalid)
• If we want to specify the dimension before the variable that rule is applicable only for
the 1st variable. Second variable onwards we can't apply in the same declaration.

13
Example:
int[] []a,[]b;
I I invalid
valid
Array construction: Every array in java is an object hence we can create by using new operator.
Example:
int[] a=new int[3];
Diagram:

• For every array type corresponding classes are available but these classes are part of
java language and not available to the programmer level.
Array Type corresponding class name
int[] [I
int[][] [[ I
double[] [D

Rule 1:
• At the time of array creation compulsory we should specify the size otherwise we will
get compile time error.
Example:
int[] a=new int[3];
int[] a=new int[];/ /C.E:array dimension missing
Rule 2:
• It is legal to have an array with size zero in java.
Example:
int[] a=new int[O];
System.out.println(a.length);/ /0
Rule 3:
• If we are taking array size with -ve int value then we will get runtime exception saying
NegativeArraySizeException.
Example:
int[] a=new int[-3];//R.E:NegativeArraySizeException
Rule 4:
• The allowed data types to specify array size are byte, short, char, into By mistake if we
are using any other type we will get compile time error.
Example:
int[] a=new int['a'];/ /(valid)

14
byte b=10;
int[] a=new int[b];/ /(valid)
short 5=20;
int[] a=new int[s];/ /(valid)
int[] a=new int[101];//C.E:possible loss of precision//{invalid)
int[] a=new int[10.5J;//C.E:possible loss of precision//(invalid)
Rule 5:
• The maximum allowed array size in java is maximum value of int size [2147483647].
Example:
int[] a1=new int[2147483647];(valid)
int[] a2=new int[2147483648J;/ /C.E:integer number too large: 2147483648{invalid)
Two dimensional array creation:
• In java multidimensional arrays are implemented as array of arrays approach but not
matrix form.
• The main advantage of this approach is to improve memory utilization.
Example 1:
int[][] a=new int[2][];
a[O]=new int[3];
a[l]=new int[2];
Diagram:
memory representation

Example 2:
int[][][] a=new int[2][][];
a[O]=new int[3][];
a[O][O]=new int[1];
a[O][l]=new int[2J;
a[0][2]=new int[3];
a[l]=new int[2][2];
Diagram:

15
alO] all]

Which of the following declarations are valid?


1) int[] a=new int[]//C.E: array dimension missing(invalid)
2) int[][] a=new int[3][4];(valid)
3) int[][] a=new int[3][];(valid)
4) int[][] a=new int[][4];//C.E:,], expected(invalid)
5) int[][][] a=new int[3][4][5];(valid)
6) int[][][] a=new int[3][4][];(valid)
7) int[][][] a=new int[3][][5];//C.E:']' expected(invalid)
Array initialization: Whenever we are creating an array every element is initialized with default
value automatically.
Example 1:
int[] a=new int[3];
System.out.printl n(a);/ /[1@3e25a5
System.out.println(a[O]);/ /0
Diagram:

Note: Whenever we are trying to print any object reference internally toString() method will be
executed which is implemented by default to return the following.
classname@hexadecimalstringrepresentationofhashcode.
Example 2:
~
int[][] a=new int[2][3]i base size
System.out.println(a);/ /[[1@3e25a5
System.out.println(a[O]);/ /[1@1982lf
System.out.println(a[O] [0]);//0
Diagram:

16
memory representation

Example 3:
int[J[] a=new int[2][];
System.out.println(a);/ /[[1@3e25a5
System.out.printl n(a[0]);/ /null
System.out.println( a[0] [0]);/ /R. E:Null PointerException
Diagram:

• Once we created an array all its elements by default initialized with default values. If we
are not satisfied with those default values then we can replays with our customized
values.
Example:
int[] a=new int[4];
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;/ /R.E:ArraylndexOutOfBoundsException: 4
a[-4]=60;/ /R.E:ArraylndexOutOfBoundsException: -4
Diagram:

Note: if we are trying to access array element with out of range index we will get Runtime
Exception saying ArraylndexOutOfBoundsException.
Declaration construction and initialization of an array in a single line:
• We can perform declaration construction and initialization of an array in a single line.
Example:

int[) a={lO,20,30};

17
chart] ch={'a', 'e', 'i','o','u'};(valid)
Stri ng[] s=]" balayya", "venki"," nag", "chiru"};(val id)
• We can extend this short cut even for multi dimensional arrays also.

Example:
int[][] a={{10,20,30},{40,SO}};'
Diagram:
a-----7j

Example:
int[][][] a={{{10,20,30},{40,SO}t{{60U70,80t{90,100,l10}}};
Diagram:
a

int[][][] a={{{10,20,30},{40,SO}t{{60U70,80t{90,100,l10}}};
System.out.println(a[O] [1] [1]);/ /SO(valid)
System.out.printl n(a[1] [0] [2]);/ /R. E:Arrayl ndexOutOfBoundsException: 2( inva lid)
System.out.println(a[l] [2] [1]);/ /100(valid)
System.out.println( a[1] [2] [2]);/ /110(val id)
System.out.printl n(a[2] [1] [0]);/ /R. E:Arrayl ndexOutOfBoundsException: 2(invalid)
System.out.println(a[l] [1] [1]);/ /80(valid)
• If we want to use this short cut compulsory we should perform declaration, construction
and initialization in a single line. If we are trying to divide into multiple lines then we will
get compile time error.
Example:

intl] x;
x=new intI3];
x={lO,20,30};
C.E:illegal start of expression

length Vs lengthO:
length:
1) It is the final variable applicable only for arrays.
2) It represents the size of the array.
Example:

18
int[] x=new int[3];
System.out.println(x.length());//C.E: cannot find symbol
System.out.println(x.length);/ /3

lengthO method:
1) It is a final method applicable for String objects.
2) It returns the no of characters present in the String.
Example:
String s="bhaskar";
System.out.println(s.length);/ /C.E:cannot find symbol
System.out.println (s.length());/ /7
• In multidimensional arrays length variable represents only base size but not total size.
Example:
int[][] a=new int[6][3];
System.out.println(a.length);/ /6
System.out.printl n(a[O].length);/ /3
Diagram:

I I
• length variable applicable only for arrays where as length()method is applicable for
String objects.
Anonymous Arrays:
• Sometimes we can create an array without name such type of nameless arrays are
called anonymous arrays.
• The main objective of anonymous arrays is "just for instant use".
• We can create anonymous array as follows.
new int[]{10,20,30AO};(valid)
new int[][]{{10,20},{30AO}};(valid)
• At the time of anonymous array creation we can't specify the size otherwise we will get
compile time error.
Example:
new int[3]{10,20,30AO};/ /C.E:';' expected(invalid)
new int[]{10,20,30AO};(valid)
• Based on our programming requirement we can give the name for anonymous array
then it is no longer anonymous.
Example:
int[] a=new int[]{10,20,30AO};(valid)

19
Example:
class Test

public static void main(String[] args)


{
System.out.println(sum(new int[]{10,20,30,40}));/ /100

public static int sum(int[] x)


{
int total=O;
for(int xl:x)
{
total=total+xl;

return total;

Array element assignments:


Case 1: In the case of primitive array as array element any type is allowed which can be
promoted to declared type.
Example 1: For the int type arrays the allowed array element types are byte, short, char into
int[] a=new int[lO];
a[0]=97;/ /(valid)
a[l]='a';/ /(valid)
byte b=lO;
a[2]=b;/ /(valid)
short s=20;
a[3]=s;/ /(valid)
a[4]=101;/ /C.E:possible loss of precision
Example 2: For float type arrays the allowed element types are byte, short, char, int, long, float.
Case 2: In the case of Object type arrays as array elements we can provide either declared type
objects or its child class objects.
Example 1:
Object[] a=new Object[lO];
a[O]=new Integer(lO);/ /(valid)
a[l]=new Objectll./ /(valid)
a[2]=new String(" bhaskar");/ /(valid)
Example 2:

20
Number[] n=new Number[10];
n[O]=new Integer(10);/ /(valid)
n[l]=new Double(10.5);/ /(valid)
n[2]=new String("bhaskar");/ /C.E:incompatible types/ /(invalid)
Diagram:
Object
I
Number
I
I I I I I I
I B S l F D

Case 3: In the case of interface type arrays as array elements we can provide its implemented
class objects.
Example:
Runnable[] r=new Runnable[10];
r[O]=new Threadl):
r[l]=new String("bhaskar");/ /C.E: incompatible types
Array Type Allowed Element Type
1) Primitive arrays. 1) Any type which can be promoted to
declared type.
2) Object type arrays. 2) Either declared type or its child class
objects.
3) Interface type arrays. 3) Its implemented class objects.
4) Abstract class type arrays. 4) Its child class objects are allowed.
Array variable assignments:
Case 1:
• Element level promotions are not applicable at array level.
• A char value can be promoted to int type but char array cannot be promoted to int
array.
Example:
int[] a={10,20,30};
chart] ch={'a','b','c'};
int[] b=a;//(valid)
int[] c=ch;//C.E:incompatible types(invalid)
Which of the following promotions are valid?

21
l)char int (valid)
2)char[] int[] (invalid)
3)int long (valid)
4)int[] long[](invalid)
S)double float (invalid)
6)double[]-- float[] (invalid)
7)String Object (valid)
8)String[] Object[] (valid)
Note: In the case of object type arrays child type array can be assign to parent type array
variable.

Example:
String[] s={"A","B"};
Object[] o=s:
Case 2: Whenever we are assigning one array to another array internal elements won't be copy
just reference variables will be reassigned hence sizes are not important but types must be
matched.
Example:
int[] a={10,20,30,40,SO,60,70};
int[] b={80,90};
a=b;/ /(valid)
b=a;/ /(valid)
Diagram:

Case 3: Whenever we are assigning one array to another array dimensions must be matched
that is in the place of one dimensional array we should provide the same type only otherwise
we will get compile time error.
Example:
int[][] a=new int[3][];
a[O]=new int[4][S];//C.E:incompatible types(invalid)
a[O]=10;/ /C.E:incompatible types(invalid)
a[O]=new int[4];//(valid)
Note: Whenever we are performing array assignments the types and dimensions must be
matched but sizes are not important.
Example1:

22
int[][] a=new int[3][2];
a[O]=new int[3];
a[l]=new int[4];
a=new int[4][3];
Diagram:

Total how many objects created?


Ans: 11
How many objects eligible for GC: 6
Example 2:
class Test

public static void main(String[] args)


{
String[] argh={IAI,IB"};
args=argh;
System.out.println(args.length);/ /2
for(int i=O;i<=args.length;i++)

System.out.println(args[i]l;

Output:
java Test x y
R.E: ArraylndexOutOfBoundsException: 2
java Test x

23
R.E: ArraylndexOutOfBoundsException: 2
java Test
R.E: ArraylndexOutOfBoundsException: 2
Note: Replace with i<args.length.
Example 3:
class Test

public static void main(String[] args)


{
String[] argh={IAI,IB"};
args=argh;
System.out.println(args.length);/ /2
for(int i=O;i<args.length;i++)

System.out.println(args[i]);

Output:
2
A
B
Types of Variables
• Based the type of value represented by the variable all variables are divided into 2
types. They are:
1) Primitive variables
2) Reference variables
Primitive variables: Primitive variables can be used to represent primitive values.
Example: int x=10;
Reference variables: Reference variables can be used to refer objects.
Example: Student s=new Studentf):
Diagram:

s-O
• Based on the purpose and position of declaration all variables are divided into the
following 3 types.
1) Instance variables
2) Static variables
3) Local variables
Instance variables:

24
• If the value of a variable is varied from object to object such type of variables are called
instance variables.
• For every object a separate copy of instance variables will be created.
• Instance variables will be created at the time of object creation and destroyed at the
time of object destruction hence the scope of instance variables is exactly same as
scope of objects.
• Instance variables will be stored on the heap as the part of object.
• Instance variables should be declared with in the class directly but outside of any
method or block or constructor.
• Instance variables can be accessed directly from Instance area. But cannot be accessed
directly from static area.
• But by using object reference we can access instance variables from static area.
Example:
class Test

int i=lO;
public static void main(String[] args)

/ /System.out.println(i);/ /C.E:non-static variable i cannot be referenced from a


static context(invalid)
Test t=new TestO;
System.out.println(t.i);/ /lO(valid)
t.methcdonet):

public void methodOneO


{
System.out.println(i);/ /lO(valid)

• For the instance variables it is not required to perform initialization JVM will always
provide default values.
Example:
class Test

boolean b;
public static void main(String[] args)
{
Test t=new TestO;

25
System.out.println(t.b );/ /false

• Instance variables also known as object level variables or attributes.


Static variables:
• If the value of a variable is not varied from object to object such type of variables is not
recommended to declare as instance variables. We have to declare such type of
variables at class level by using static modifier.
• In the case of instance variables for every object a separate copy will be created but in
the case of static variables for entire class only one copy will be created and shared by
every object of that class.
• Static variables will be crated at the time of class loading and destroyed at the time of
class unloading hence the scope of the static variable is exactly same as the scope of the
.class file.
• Static variables will be stored in method area. Static variables should be declared with in
the class directly but outside of any method or block or constructor.
• Static variables can be accessed from both instance and static areas directly.
• We can access static variables either by class name or by object reference but usage of
class name is recommended.
• But within the same class it is not required to use class name we can access directly.
1) Start NM.
2) Create and start Main Thread by NM.
3) Locate(find) Test.class by main Thread.
4) Load Test.class by main Thread.
5) Execution of mainO method.
6) Unload Test.class
7) Terminate main Thread.
8) Shutdown NM.
Example:
class Test

static int i=10;


public static void main(String[] args)
{
Test t=new TestO;
System.out.println(t.i);/ /10
System.out.println(Test.i);/ /10
System.out.println(i);/ /10

26
• For the static variables it is not required to perform initialization explicitly, JVM will
always provide default values.
Example:
class Test

static String s;
public static void main(String[] args)
{
System.out.println(s);/ /null

Example:
class Test

int x=10;
static int y=20;
public static void main(String[] args)
{
Test t1=new Test();
t1.x=888;
t1.y=999;
Test t2=new Test();
System.out.println(t2.x+ ----"+t2.y);/ /10----999
I

Diagram:

• Static variables also known as class level variables or fields.


local variables:
• Some time to meet temporary requirements of the programmer we can declare
variables inside a method or block or constructors such type of variables are called local
variables or automatic variables or temporary variables or stack variables.

27
• The local variables will be created as part of the block execution in which it is declared
and destroyed once that block execution completes. Hence the scope of the local
variables is exactly same as scope of the block in which we declared.
Example 1:
class Test

public static void main(String[] args)


{
int i=O;
for(int j=O;j<3;j++)
{
i=i+j;

System.out.println(i+"----"+j)j javac Test.java


I C.E '\. Test.java:l0: cannot find symbol
/' symbol : variable j
location: class Test

Example 2:
class Test

public static void main(String[] args)


{
try

int i=lnteger.parselnt("ten");

catch(NullPointerException e)
{
System.out.println(i)j
iavac Test.java
L.::.:........;:~ est.java:11: cannot find symbol
symbol : variable i

• The local variables will be stored on the stack.

28
• For the local variables JVM won't provide any default values compulsory we should
perform initialization explicitly before using that variable.
Example:
class Test class Test

public static void main(String[] args) public static void main(String[] args)
{ {
int Xi int xi
System.out.println("hello")i/ /hello System.out.println(x)i/ /C.E:variable x might not have been initialized
}

Example:
class Test

public static void main(String[] args)


{
int x;
if(args.length>O)
{
x=10;

System.out.println(x);//C.E:variable x might not have been initialized

Example:
class Test

public static void main(String[] args)


{
int x;
if(args.length>O)
{
x=10;

else

x=20;

System.out.printl n(x);

29
Output:
java Test x
10
java Test x y
10
java Test
20
• It is never recommended to perform initialization for the local variables inside logical
blocks because there is no guarantee of executing that block always at runtime.
• It is highly recommended to perform initialization for the local variables at the time of
declaration at least with default values.
Note: The only applicable modifier for local variables is final. If we are using any other
modifier we will get compile time error.
Example:
class Test

public static void main(String[] args)


{

public int x=10;


private int x=10;
protected int x=10; C.E: illegal start of expression
static int x=10;
volatile int x=10;
transient int x=10;
final int x=10;/ /(valid)

Conclusions:
1) For the static and instance variables it is not required to perform initialization explicitly
JVM will provide default values. But for the local variables JVM won't provide any
default values compulsory we should perform initialization explicitly before using that
variable.
2) For every object a separate copy of instance variable will be created whereas for entire
class a single copy of static variable will be created. For every Thread a separate copy of
local variable will be created.

30
3) Instance and static variables can be accessed by multiple Threads simultaneously and
hence these are not Thread safe but local variables can be accessed by only one Thread
at a time and hence local variables are Thread safe.
UN initialized arrays
Example:
class Test

int[] a;
public static void main(String[] args)
{
Test tl=new Test();
System.out.println(tl.a);/ /null
System.out.println(tl.a[O] );/ /R. E:NullPoi nterException

Instance level:
Example 1:
int[] a;
System.out.println( obj.a);/ /null
System.out.printl n(obj.a [a]);/ /R. E:NuIIPointerException
Example 2:
int[] a=new int[3];
System.out.println( obj.a);/ /[ 1@3e2SaS
System.out.println( obj.a[O]);/ /0
Static level:
Example 1:
static int[] a;
System.out.println(a);/ /null
System.out.println( a[0]);/ /R. E:Null PointerException
Example 2:
static int[] a=new int[3];
System.out.println( a);/ /[1@3e2SaS
System.out.println(a[O]);/ /0
local level:
Example 1:
int[] a;
System.out.println(a); }C.E: variable a might not have been initialized
System.out.printl n(a[0]);

31
Example 2:
int[] a=new int[3];
System.out.println( a);/ /[1@3e2SaS
System.out.println(a[Oj);/ /0
• Once we created an array every element is always initialized with default values
irrespective of whether it is static or instance or local array.
Var- arg methods (variable no of argument methods) (1.5)
• Until 1.4v we can't declared a method with variable no. Of arguments. If there is a
change in no of arguments compulsory we have to define a new method. This approach
increases length of the code and reduces readability. But from 1.5 version onwards we
can declare a method with variable no. Of arguments such type of methods are called
var-arg methods.
• We can declare a var-arg method as follows.
methodOne(int .•• x)

Lellipse

• We can call or invoke this method by passing any no. Of int values including zero
number.
Example:
class Test

public static void methodOne(int... x)


{
System.out.println("var-arg method");

public static void main(String[] args)


{
methodOne();
methodOne(lO);
methodOne(10,20,30);

Output:
var-arg method
var-arg method
var-arg method
• Internally var-arg parameter implemented by using single dimensional array hence
within the var-arg method we can different arguments by using index.
Example:

32
class Test

public static void sum(int ... x)

int total=O;
for(int i=O;i<x.length;i++)
{
total=total+x[i];

System.out.println("The sum :"+total);

public static void main(String[] args)


{
surnt):
sum(10);
sum(10,20);
sum(10,20,30AO);

Output:
The sum: 0
The sum: 10
The sum: 30
The sum: 100
Case 1:
Which of the following var-arg method declarations are valid?
1) methodOne(int x)(valid)
2) methodOne(int x)(valid)
3) methodOne(int x )(invalid)
4) methodOne(int x)(invalid)
5) methodOne(int .x..)(invalid)
Case 2: We can mix var-arg parameter with general parameters also.
Example:
methodOne(int a,int ... b) }
methodOne(String s.int ... x) valid
Case 3: if we mix var-arg parameter with general parameter then var-arg parameter should be
the last parameter.
Example:

33
methodOne(int ... a,int b)(invalid)
Case 4: We can take only one var-arg parameter inside var-arg method
Example:
methodOne(int ... a,int ... b)(invalid)
Case 5:
class Test

public static void methodOne(int i)


{
System.out.println("general method");

public static void methodOne(int ... i)


{
System.out.println("var-arg method");

public static void main(String[] args)


{
methodOneO;/ /var-arg method
methodOne(lO,20);/ /var-arg method
methodOne(lO);/ /general method

• In general var-arg method will get least priority that is if no other method matched then
only var-arg method will get the chance this is exactly same as default case inside a
switch.
Case 6: For the var-arg methods we can provide the corresponding type array as argument.
Example:
class Test

public static void methodOne(int


.r<:
... i) int[] i

System.out.println("var-arg method");

public static void main(String[] args)


{
methodOne(new int[]{lO,20,30});/ /var-arg method

34
Case 7:
class Test

public void methodOne(int[] i){}


public void methodOne(int ... i){}

Output:
Compile time error.
Cannot declare both methodOne(int. ..) and methodOne(int[]) in Test
Single Dimensional Array Vs Var-Arg Method:
Case 1: Wherever single dimensional array present we can replace with var-arg parameter.

methodOne(int[] i)c=::>methodOne(int ... i) (valid)

Example:
class Test

public static void main(String ... args)

System.out.println("var-arg main method");/ /var-arg main method

Case 2: Wherever var-arg parameter present we can't replace with single dimensional array.

I methodOne(int ... i)C=::>methodOne(int[] I


i) (invalid)

Example:
class Test

public static void methodOne(int[] ... x)


{
for(int[] a:x)
{
System.out.printl n(a[0]);

public static void main(String[] args)


{
int[]I={10,20,30};

35
int[] m={40,50};
methodOne(l,m);

Output:
10
40
Analysis:

methodOne(int ... x)
methodOne(lO,20)j x~

methodOne(int[] ... x) x
int[] 1={lO,20,30};
int[] m={40,SO};
methodOne(I,m);

Main Method
• Whether the class contains main() method or not and whether it is properly declared or
not these checking's are not responsibilities of the compiler, at runtime JVM is
responsible for this. If jvm unable to find the required main() method then we will get
runtime exception saying NoSuchMethodError: main.
Example:
class Test
{}
Output:
javac Test.java
java Test R.E: NoSuchMethodError: main
• JVM always searches for the main() method with the following signature.

method.

• If we are performing any changes to the above signature then the code won't run and
will get Runtime exception saying NoSuchMethodError. Anyway the following changes
are acceptable to main() method.

36
1) The order of modifiers is not important that is instead of public static we can take static
public.
2) We can declare string[] in any acceptable form
1) String[] args
2) String []args
3) String args[]
3) Instead of args we can use any valid java identifier.
4) We can replace string[] with var-arg parameter.
Example:
main(String ... args)
5) main() method can be declared with the following modifiers.
• final, synchronized, strictfp.
Which of the following mainO method declarations are valid?
1) public static void main(String args){}(invalid)
2) public synchronized final strictfp void main(String[] args){} (invalid)
3) public static void Main(String ... args){} (invalid)
4) public static int main(String[] args){}//int return type we can't take//(invalid)
5) public static synchronized final strictfp void main(String ... args){}(valid)
In which of the above cases we will get compile time error?
• No case, in all the cases we will get runtime exception.
• Overloading of the main() method is possible but JVM always calls string[] argument
main() method only.
Example:
class Test

public static void main(String[] args)


{
System.out.println("String[] array main method ") overloaded methods

public static void main(int[] args)


{
System.out.println("int[] array main method ");

Output:
String[] array main method
• The other overloaded method we have to call explicitly then only it will be executed.

37
• Inheritance concept is applicable for static methods including mainO method hence
while executing child class if the child class doesn't contain mainO method then the
parent class mainO method will be executed.
Example 1:
class Parent

public static void main(String[] args)


{
System.out.println("parent main"); Parent.java

class Child extends Parent


{}
Analysis:

javac Parent.java

Parent.class Child.class
java Parent
parent main
java Child
parent main
Example 2:
class Parent

public static void main(String[] args)


{
System.out.println("parent main");

class Child extends Parent Parent.java

public static void main(String[] args)


{
System.out.println("Child main");

Analysis:

38
javac Parent.java

Parent.class Child.class
java Parent
parent main
java Child
Child main
• It seems to be overriding concept is applicable for static methods but it is not overriding
it is method hiding.

Command line arguments:


• The arguments which are passing from command prompt are called command line
arguments. The main objective of command line arguments are we can customize the
behavior of the main() method.
java Test 10 20 30
I I args[Oj
~args[l]
args[2]
args.length~3
Example 1:
class Test

public static void main(String[] args)


{
for(int i=O;i<=args.length;i++)
{
System.out.println( args[i]);

Output:
java Test x y z
ArraylndexOutOfBoundsException: 3
Example 2:
• Replace i<=args.length with i<args.length then it will run successfully.
• Within the main() method command line arguments are available in the form of String
hence "+" operator acts as string concatenation but not arithmetic addition.
Example:
class Test

39
public static void main(String[] args)
{
System .out. pri ntl n(args[O]+args[1]);

Output:
E:\SCJP>javac Test.java
E:\SCJP>java Test 1020
1020
• Space is the separator between 2 command line arguments and if our command line
argument itself contains space then we should enclose with in double quotes.
Example:
class Test

public static void main(String[] args)


{
System .out.printl n(args[O]);

Output:
E:\SCJP>javac Test.java
E:\SCJP>java Test "vijaya bhaskar"
Vijaya bhaskar
Java coding standards
• It is highly recommended to follow coding standards.
• Whenever we are writing any component the name of the component should reflect the
purpose or functionality.
Example:

class A package com.durgescft.scjpderno:


{ class Calc
public int methodOne(int x,int y) {
{ public static int add(int numberl,int number2)
return X+Yi {
} return numberl+number2i
} }
Ameerpet standards }
Hitech-city standards

Coding standards for classes:

40
• Usually class names are nouns.
• Should starts with uppercase letter and if it contains multiple words every inner word
should starts with upper case letter.
Example:

String,Customer,Object,Student,StringBuffer nouns

Coding standards for interfaces:


• Usually interface names are adjectives.
• Should starts with upper case letter and if it contains multiple words every inner word
should starts with upper case letter.
Example:
1) serialiZable}
2) Runnable adjectives
3) Cloneable
Coding standards for methods:
• Usually method names are either verbs or verb noun combination.
• Should starts with lowercase character and if it contains multiple words every inner
word should starts with upper case letter.
Example:

run()} getName() }
sleep() verb 1...- _

eat() setSalary()} verb+noun


drink() nouns

Coding standards for variables:

• Usually variable names are nouns.


• Should starts with lowercase alphabet symbol and if it contains multiple words every
inner word should starts with upper case character.
Example:
length
name
salary nouns
age
mobileNumber
Coding standards for constants:
• Usually constants are nouns.
• Should contain only uppercase characters and if it contains multiple words then these
words are separated with underscore symbol.

41
• Usually we can declare constants by using public static final modifiers.
Example:
MAX_ VALU E}nouns
MIN_VALUE
Java bean coding standards:
• A java bean is a simple java class with private properties and public getter and setter
methods.

Example:
class StudentBean
class name ends
{
~ with bean is not
private String name;
officia convention
public void setName(String name)
from sun.
{
this.name=name;
}
public String getName()
{
return name;
}
}
Syntax for setter method:
1) Method name should be prefixed with set.
2) It should be public.
3) Return type should be void.
4) Compulsory it should take some argument.
Syntax for getter method:
1) The method name should be prefixed with get.
2) It should be public.
3) Return type should not be void.
4) It is always no argument method.
Note: For the boolean properties the getter method can be prefixed with either get or is.
Example:

42
private boolean empty; private boolean empty;
public boolean getEmptyO public boolean isEmptyO
{ {
return empty; return empty;
} }
(valid) (valid)
both are valid.
Coding standards for listeners:
To register a listener:
• Method name should be prefixed with add.
1) public void addMyActionListener(MyActionListener I)(valid)
2) public void registerMyActionListener(MyActionListener I)(invalid)
3) public void addMyActionListener(ActionListener I)(invalid)
To unregister a listener:
• The method name should be prefixed with remove.
1) public void removeMyActionListener(MyActionListener I)(valid)
2) pubic void unregisterMyActionListener(MyActionListener I)(invalid)
3) public void removeMyActionListener(ActionListener I)(invalid)
4) public void delete MyActionListener(MyActionListener I)(invalid)

43
Declaration and Access Modifiers
1) Java source file structure
2) Class modifiers
3) Member modifiers
4) Interfaces
Java source file structure:
• A java program can contain any no. Of classes but at mot one class can be declared as
public. "lf there is a public class the name of the program and name of the public class
must be matched otherwise we will get compile time error".
• If there is no public class then any name we gives for java source file.
Example:

class A

Casel:
• If there is no public class then we can use any name for java source file there are no
restrictions.
Example:
A.java
B.java
C.java

44
Bhaskar.java
ease2:
• If class B declared as public then the name of the program should be B.java otherwise
we will get compile time error saying "class B is public, should be declared in a file
named B.java".
Cae3:
• If both Band C classes are declared as public and name of the file is B.java then we will
get compile time error saying "class C is public, should be declared in a file named
(.java".
• It is highly recommended to take only one class for source file and name of the program
(file) must be same as class name. This approach improves readability and
understandability of the code.

Example:
class A

public static void main(String args[]H


System.out.println("A class main method is executed");

class B

public static void main(String args[]H


System.out.println("B class main method is executed");

class C

public static void main(String args[]H


System.out.println("C class main method is executed");

class D
{
}
Output:

45
javac Bhaskar .java

.: BLa ~av\java
D:\Java>java A
A class main method is executed
D:\Java>java B
B class main method is executed
D:\Java>java C
C class main method is executed
D:\Java>java D
Exception in thread "main" java.lang.NoSuchMethodError: main
D:\Java>java Bhaskar
Exception in thread "main" java.lang.NoClassDefFoundError: Bhaskar
• We can compile a java program but not java class in that program for every class one
dot class file will be created.
• We can run a java class but not java source file whenever we are trying to run a class the
corresponding class main method will be executed.
• If the class won't contain main method then we will get runtime exception saying
"NoSuchMethodError: main".
• If we are trying to execute a java class and if the corresponding .class file is not available
then we will get runtime execution saying "NoClassDefFoundError: Bhaskar".
Import statement:
class Test{
public static void main(String args[]H
ArrayList I=new ArrayList();
}
}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:3: cannot find symbol
symbol : class ArrayList
location: class Test
ArrayList I=new ArrayList();
Test.java:3: cannot find symbol
symbol : class ArrayList
location: class Test

46
ArrayList I=new ArrayList();
• We can resolve this problem by using fully qualified name "java.utiI.ArrayList I=new
java.util.Arravl.istl]:". But problem with using fully qualified name every time is it
increases length of the code and reduces readability.
• We can resolve this problem by using import statements.
Example:
import java.utiI.ArrayList;
class Test{
public static void main(String args[]H
ArrayList I=new ArrayList();
}
}
Output:
D:\Java>javac Test.java
• Hence whenever we are using import statement it is not require to use fully qualified
names we can use short names directly. This approach decreases length of the code and
improves readability.
Case 1: Types of Import Statements;
• There are 2 types of import statements.
1) Explicit class import
2) Implicit class import.
Explicit class import:
Example: Import java.util.ArrayList
• This type of import is highly recommended to use because it improves readability of the
code.
• Best suitable for Hi-Tech city where readability is important.
Implicit class import:
Example: import java.util. *;
• It is never recommended to use because it reduces readability of the code.
• Bet suitable for Ameerpet where typing is important.
Case2:
Which of the following import statements are valid?
import java.util; X
import java.util.ArrayList. *; X
importjava.util.*; V
import java.utiI.ArrayList; v
Case3:
• consider the following code.

47
class MyArrayList extends java.util.ArrayList
{
}
• The code compiles fine even though we are not using import statements because we
used fully qualified name.
• Whenever we are using fully qualified name it is not required to use import statement.
Similarly whenever we are using import statements it is not require to use fully qualified
name.
Case4:
Example:
import java.util. *;
import java.sql. *;
class Test

public static void main(String args[])


{
Date d=new Datef):
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:7: reference to Date is ambiguous, both class java.sql.Date in java.sql and class
java.util.Date in java.util match
Date d=new Oatet):
Note: Even in the List case also we may get the same ambiguity problem because it is available
in both UTIL and AWT packages.
CaseS:
• While resolving class names compiler will always gives the importance in the following
order.
1) Explicit class import
2) Classes present in current working directory.
3) Implicit class import.
Example:
import java.utiI.Date;
import java.sql. *;
class Test

public static void main(String args[]H

48
Date d=new Datef):
}}
• The code compiles fine and in this case util package Date will be considered.
Case6:
• Whenever we are importing a package all classes and interfaces present in that package
are by default available but not sub package classes.
Example:
java
~util
~regex

~pattern

To use pattern class in our program directly which import statement is required?

1.importjava.*; X
2.import java.utiL *; X
3.import java.utiLregex. *;V
4.import java.utiLregex.Pattern; V
Case7:
• In any java program the following 2 packages are not require to import because these
are available by default to every java program.
1. java.lang package
2. default package(current working directory)
CaseS:
• "Import statement is totally compile time concept" if more no of imports are there then
more will be the compile time but there is "no change in execution time".
Difference between C language #include and java language import.
• In the case of C language #include all the header files will be loaded at the time of
include statement hence it follows static loading.
• But in java import statement no ".class" will be loaded at the time of import statements
in the next lines of the code whenever we are using a particular class then only
corresponding ".class" file will be loaded. Hence it follows "dynamic loading" or "Ioad-
on -demand" or "Ioad-on-fly".
Static import:
• This concept introduced in 1.5 versions. According to sun static import improves
readability of the code but according to worldwide programming exports (like us) static

49
imports creates confusion and reduces readability of the code. Hence if there is no
specific requirement never recommended to use a static import.
1.5 versions new features
1) For-Each
2) Var-arg
3) Queue
4) Generics
5) Auto boxing and Auto unboxing
6) Co-varient return types
7) Annotations
8) Enum
9) Static import
10) String builder
• Usually we can access static members by using class name but whenever we are using
static import it is not require to use class name we can access directly.
Without static import:
class Test

public static void main(String args[]H


System.out.println(Math.sqrt( 4));
System.out.printl n(Math. max(10,20));
System.out.println(Math.randomO);
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
2.0
20
0.841306154315576
With static import:
import static java.lang.Math.sqrt;
import static java.lang.Math. *;
class Test

public static void main(String args[]H


System.out.printl n(sqrt( 4));
System.out.println(max(10,20));
System.out.println(randomO);

50
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
2.0
20
0.4302853847363891
Explain about System.out.println statement?
Example 1 and example 2:
1) 2)
class Test import java.io.*;
class System
static String name="bhaskar" {
static PrintStream out;
11 }

Test.name.length(); System.out.printl nO

it is a class. static variable. it is a method it is a class


of type string present in
present in string class
Test class.

Example 3:
import static java.lang.System.out;
class Test

public static void main(String args[]H


out. pri ntl n(" hello ");
out.println("hi ");
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
hello
hi
Example 4:
import static java.lang.lnteger. *;

51
import static java.lang.Byte. *;
class Test

public static void main(String args[]H


System.out.println(MAX_ VALUE);
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:6: reference to MAX_VALUE is ambiguous, both variable MAX_VALUE in
java.lang.lnteger and variable MAX_VALUE in java.lang.Byte match
System.out.println(MAX_ VALUE);
Note: Two packages contain a class or interface with the same is very rare hence ambiguity
problem is very rare in normal import.
• But 2 classes or interfaces can contain a method or variable with the same name is very
common hence ambiguity problem is also very common in static import.
• While resolving static members compiler will give the precedence in the following order.
1. Current class static members
2. Explicit static import
3. implict static import.
Example:
/ /import static java.lang.lnteger.MAX_ VALUE;--)7 line2
import static java.lang.Byte. *;
class Test
{
//static int MAX_VALUE=999; )Iinel
public static void main(String args[])throws Exception{
System.out.println(MAX_ VALUE);
}
}
• If we comet line one then we will get Integer class MAX_VALUE 2147483647.
• If we comet lines one and two then Byte class MAX_ VALUE will be considered 127.
Which of the following import statements are valid?
Limport java.lang.Math. *; X
2.import static java.lang.Math.*; V
3.import java.lang.Math; V
4.import static java.lang.Math;x
5.import static java.lang.Math.sqrt. *; X
6.import java.lang.Math.sqrt; X
7 .import static java.lang.Math.sqrtO;x
8.import static java.lang.Math.sqrt; V

52
Diagram:
Math;

normal import starts with


-(
util.*;
Math.sqrt;

static import starts with


-(
Math.*;

• Usage of static import reduces readability and creates confusion hence if there is no
specific requirement never recommended to use static import.
What is the difference between general import and static import?
• We can use normal imports to import classes and interfaces of a package. whenever we
are using normal import we can access class and interfaces directly by their short name
it is not require to use fully qualified names.
• We can use static import to import static members of a particular class. whenever we
are using static import it is not require to use class name we can access static members
directly.
Package statement:
• It is an encapsulation mechanism to group related classes and interfaces into a single
module.
The main objectives of packages are:
• To resolve name confects.
• To improve modularity of the application.
• To provide security.
• There is one universally accepted naming conversion for packages that is to use internet
domain name in reverse.
Example:

j·lhOUSr'n.~
client internet module submodule class
domain name name
in reverse
How to compile package program:
Example:
package com.durgajobs.itjobs;
class HydJobs

public static void main(String args[]H


System.out.println("package demo");

53
• Javac HydJobs.java generated class file will be placed in current working directory.
Diagram:
cwd

~ HydJobs.class

• Javac -d. HydJobs.java


• -d means destination to place generated class files "." means current working directory.
• Generated class file will be placed into corresponding package structure.

Diagram:
cwd
j-com
I-durgajObS
j-itjobS
I-HydJObs.class

• If the specified package structure is not already available then this command itself will
create the required package structure.
• As the destination we can use any valid directory.
If the specified destination is not available then we will get compile time error.
Example:
D:\Java>javac -d c: HydJobs.java
Diagram:
c:
j-com
I-durgajObS
j-itjObS
I- HydJobs.class
• If the specified destination is not available then we will get compile time error.
Example:
D:\Java>javac -d z: HydJobs.java
• If Z: is not available then we will get compile time error.
How to execute package program:
D:\Java>java com.durgajobs.itjobs.HydJobs
• At the time of execution compulsory we should provide fully qualified name.
Conclusion 1:

54
• In any java program there should be at most one package statement that is if we are
taking more than one package statement we will get compile time error.
Example:
package pack1;
package pack2;
class A
{
}
Output:
Compile time error.
D:\Java>javac A.java
A.java:2: class, interface, or enum expected
package pack2;
Conclusion 2:
• In any java program the 1st non cement statement should be package statement [if it is
available] otherwise we will get compile time error.
Example:
import java.uti!. *;
package pack1;
class A
{
}
Output:
Compile time error.
D:\Java>javac A.java
A.java:2: class, interface, or enum expected
package pack1;
Java source file structure:
At most one package statement
I~rder is
any number is allowea-----:;:;.t import statement
tmportant
any number class/interface/enum declarations

• All the following are valid java programs.

D Test.java
V
package pack1;

Test.java
V
import java.util. *, package pack1;

Test.java
V
Test.java
V
class Test
import java.util. *; {}

Test.java
V
Note: An empty source file is a valid java program.
Class Modifiers

55
• Whenever we are writing our own classes compulsory we have to provide some
information about our class to the jvm. Like
1) Better this class can be accessible from anywhere or not.
2) Better child class creation is possible or not.
3) Whether object creation is possible or not etc.
• We can specify this information by using the corresponding modifiers.
• The only applicable modifiers for Top level classes are:
1) Public
2) Default
3) Final
4) Abstract
5) Strictfp
• If we are using any other modifier we will get compile time error.
Example:
private class Test

public static void main(String args[]H


int i=O;
for(int j=O;j<3;j++)
{
i=i+j;

System.out.println(i);
}}
OUTPUT:
Compile time error.
D:\Java>javac Test.java
Test.java:1: modifier private not allowed here
private class Test
• But For the inner classes the following modifiers are allowed.
Diagram:
public
default private
final + protected
abstract static
strictfp

What is the difference between access specifier and access modifier?


• In old languages 'C' (or) 'C++' public, private, protected, default are considered as
access specifiers and all the remaining are considered as access modifiers.

56
• But in java there is no such type of division all are considered as access modifiers.
Public Classes:
• If a class declared as public then we can access that class from anywhere.
EXAMPLE:
Program1:
package pack1;
public class Test

public void methodOne(){


System.out.println("test class methodone is executed");
}}
Compile the above program:
D:\Java>javac -d. Test.java
Program2:
package pack2;
import pack1.Test;
class Testl

public static void main(String args[]H


Test t=new Test();
t.methodOne();
}}
OUTPUT:
D:\Java>javac -d , Testl.java
D:\Java>java pack2.Testl
Test class methodone is executed.
• If class Test is not public then while compiling Testl class we will get compile time error
saying pack1.Test is not public in pack1; cannot be accessed from outside package.
Default Classes:
• If a class declared as the default then we can access that class only within the current
package hence default access is also known as "package level access".
Example:
Program 1:
package pack1;
class Test

public void methodOne(){


System.out.println("test class methodone is executed");

57
}}
Program 2:
package pack1;
import pack1.Test;
class Testl

public static void main(String args[]H


Test t=new Test();
t.methodOne();
}}
OUTPUT:
D:\Java>javac -d. Test.java
D:\Java>javac -d , Test1.java
D:\Java>java pack1.Testl
Test class methodone is executed
Final Modifier:
• Final is the modifier applicable for classes, methods and variables.
Final Methods:
• Whatever the methods parent has by default available to the child.
• If the child is not allowed to override any method, that method we have to declare with
final in parent class. That is final methods cannot overridden.
Example:
Program 1:
class Parent

public void property(){


System.out.println("cash+gold+land");
}
public final void marriage(){
System.out.println("subbalakshmi");
}}
Program 2:
class child extends Parent

public void marriage(){


System.out.println("Thamanna");
}}
OUTPUT:

58
Compile time error.
D:\Java>javac Parent.java
D:\Java>javac child.java
child.java:3: marriage{) in child cannot override marriage{) in Parent; overridden method is
final
public void marriage{){
Final Class:
• If a class declared as the final then we cann't creates the child class that is inheritance
concept is not applicable for final classes.
EXAMPLE:
Program 1:
final class Parent
{
}
Program 2:
class child extends Parent
{
}
OUTPUT:
Compile time error.
D:\Java>javac Parent.java
D:\Java>javac child.java
child.java:1: cannot inherit from final Parent
class child extends Parent
• Note: Every method present inside a final class is always final by default whether we are
declaring or not. But every variable present inside a final class need not be final.
Example:
final class parent

static int x=10;


static

x=999;
}}
• The main advantage of final keyword is we can achieve security. Whereas the main
disadvantage is we are missing the key benefits of oops: polymorsim (because of final
methods), inheritance (because of final classes) hence if there is no specific requirement
never recommended to use final keyboard.

59
Abstract Modifier:
• Abstract is the modifier applicable only for methods and classes but not for variables.
Abstract Methods:
• Even though we don't have implementation still we can declare a method with abstract
modifier. That is abstract methods have only declaration but not implementation. Hence
abstract method declaration should compulsory ends with semicolon.
EXAMPLE:
public abstract void methodOneO; ----~ valid
public abstract void methodOneOn invalid
• Child classes are responsible to provide implementation for parent class abstract
methods.
EXAMPLE:

PROGRAM:

abstract class vehicle


{
vehicle.ja va
public abstract int getNoOfWheels();
}

r
class Bus extends vehicle
~
class Auto extends vehicle
{ {
public int getNoOfWheels(){ public int getNoOfWheelsO{
return 7; return 3;
} }
} }
Bus.java Auto.lava

• The main advantage of abstract methods is , by declaring abstract method in parent


class we can provide guide lines to the child class such that which methods they should
compulsory implement.
• Abstract method never talks about implementation whereas if any modifier talks about
implementation it is always illegal combination.
• The following are the various illegal combinations for methods.
Diagram:

60
• All the 6 combinations are illegal.
Abstract class:
• For any java class if we are not allow to create an object such type of class we have to
declare with abstract modifier that is for abstract class instantiation is not possible.
Example:
abstract class Test

public static void main(String args[]H


Test t=new Test();
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: Test is abstract; cannot be instantiated
Test t=new Test();
What is the difference between abstract class and abstract method?
• If a class contain at least on abstract method then compulsory the corresponding class
should be declare with abstract modifier. Because implementation is not complete and
hence we can't create object of that class.
• Even though class doesn't contain any abstract methods still we can declare the class as
abstract that is an abstract class can contain zero no of abstract methods also.
Example1: HttpServlet class is abstract but it doesn't contain any abstract method.
Example2: Every adapter class is abstract but it doesn't contain any abstract method.
Example1:
class Parent

public void methodOne();


}
Output:

61
Compile time error.
D:\Java>javac Parent.java
Parent.java:3: missing method body, or declare abstract
public void methodOne();
Example2:
class Parent

public abstract void methodOne(){}


}
Output:
Compile time error.
Parent.java:3: abstract methods cannot have a body
public abstract void methodOne(){}
Example3:
class Parent

public abstract void methodOne();


}
Output:
Compile time error.
D:\Java>javac Parent.java
Parent.java:l: Parent is not abstract and does not override abstract method methodOne() in
Parent
class Parent
• If a class extends any abstract class then compulsory we should provide implementation
for every abstract method of the parent class otherwise we have to declare child class as
abstract.
Example:
abstract class Parent

public abstract void methodOne();


public abstract void methodTwo();
}
class child extends Parent

public void methodOneO{}


}
Output:

62
Compile time error.
D:\Java>javac Parent.java
Parent.java:6: child is not abstract and does not override abstract method methodTwo() in
Parent
class child extends Parent
• If we declare class child as abstract then the code compiles fine but child of child is
responsible to provide implementation for methodTwo().
What is the difference between final and abstract?
• For abstract methods compulsory we should override in the child class to provide
implementation. Whereas for final methods we can't override hence abstract final
combination is illegal for methods.
• For abstract classes we should compulsory create child class to provide implementation
whereas for final class we can't create child class. Hence final abstract combination is
illegal for classes.
• Final class cannot contain abstract methods whereas abstract class can contain final
method.

Example:
final class A abstract class A
{ {
public abstract void public final void methodOne(){
methodOne(); }
} }
invalid valid
Note:
• Usage of abstract methods, abstract classes and interfaces is always good programming
practice.
Strictfp:
• strictfp is the modifier applicable for methods and classes but not for variables.
• 5trictfp modifier introduced in 1.2 versions.
• If a method declare as the 5trictfp then all the floating point calculations in that method
has to follow IEEE754 standard. 50 that we will get flat from independent results.
Example:
System.out.println(lO.O/3);
P4 P3 IEEE754
3.33333333333333 3.333333 3.333

63
• If a class declares as the Strictfp then every concrete method(which has body) of that
class has to follow IEEE754 standard for floating point arithmetic.
What is the difference between abstract and strictfp?
• Strictfp method talks about implementation where as abstract method never talks
about implementation hence abstract, strictfp combination is illegal for methods.
• But we can declare a class with abstract and strictfp modifier simultaneously. That is
abstract strictfp combination is legal for classes but illegal for methods.
Example:
public abstract strictfp void methodOneO; (invalid)
abstract strictfp class Test (valid)
{
}
Member modifiers:
Public members:
• If a member declared as the public then we can access that member from anywhere
"but the corresponding class must be visible" hence before checking member visibility
we have to check class visibility.
Example:

Program 1:
package packl;
class A

public void methodOne(){


System.out.println("a class method");
}}
D:\Java>javac -d . A.java
Program 2:
package pack2;
import packl.A;
class B

public static void main(String args[]H


A a=new A();
a.methodOne();
}}
Output:
Compile time error.

64
D:\Java>javac -d . B.java
B.java:2: packl.A is not public in pack1; cannot be accessed from outside package
import packl.A;
• In the above program even though methodOne() method is public we can't access from
class B because the corresponding class A is not public that is both classes and methods
are public then only we can access.
Default member:
• If a member declared as the default then we can access that member only within the
current package hence default member is also known as package level access.
Example 1:
Program 1:
package pack1;
class A

void methodOne(){
System.out.println("methodOne is executed");
}}
Program 2:
package pack1;
import packl.A;
class B

public static void main(String args[]H


A a=new A();
a.methodOne();
}}
Output:
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
D:\Java>java packl.B
method One is executed
Example 2:
Program 1:
package pack1;
class A

void methodOne(){
System.out.println("methodOne is executed");

65
}}
Program 2:
package pack2;
import packl.A;
class B

public static void main(String args[]H


A a=new A();
a.methodOne();
}}
Output:
Compile time error.
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
B.java:2: packl.A is not public in packl; cannot be accessed from outside package
import packl.A;
Private members:
• If a member declared as the private then we can access that member only with in the
current class.
• Private methods are not visible in child classes where as abstract methods should be
visible in child classes to provide implementation hence private, abstract combination is
illegal for methods.
Protected members:
• If a member declared as the protected then we can access that member within the
current package anywhere but outside package only in child classes.
• Protected=default+kids.
• We can access protected members within the current package anywhere either by child
reference or by parent reference but from outside package we can access protected
members only in child classes and should be by child reference only that is we can't use
parent reference to call protected members from outside language.
Example:
Program 1:
package packl;
public class A

protected void methodOne(){


System.out.println("methodOne is executed ");
}}

66
Program 2:
package packl;
class B extends A

public static void main(String args[]H


A a=new AO;
a.methcdonetl:
B b=new BO;
b.methodOneO;
A al=new BO;
a1.methodOneO;
}}
Output:
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
D:\Java>java pack1.B
method One is executed
method One is executed
method One is executed
Example 2:
package pack2;
import pack1.A;
public class e extends A
{
public static void main(String args[)){
A a=new AO; X output:
a.methodOneO; >comPile time error.
e c=new eo; v D:\Java>javac -d . (.java
c.me~hodone.O; (.java:7: methodOneO has protected access in
A al-new BO, X packl.A
a1.methodOneO; a.methodOneO;
}
}
Compression of private ! default ! protected and public
visibility private default protected public
l)With in the
same class V V V V
2)From
class of same
child
X V V V
package
3)From non-
child class of X V V V
67
same package

4)From
class
child
of X X V
but we
V
outside
should use
package
child reference
only
5)From non-
child class of X X X V
outside
package
• The least accessible modifier is private.
• The most accessible modifier is public.
• Private<default<protected<public.
• Recommended modifier for variables is private where as recommended modifier for
methods is public.
Final variables:
Final instance variables:
• If the value of a variable is varied from object to object such type of variables are called
instance variables.
• For every object a separate copy of instance variables will be created.
DIAGRAM:

slobject s2 object
• For the instance variables it is not required to perform initialization explicitly jvm will
always provide default values.
Example:
class Test

int i;
public static void main(String args[]H
Test t=new Test();
System.out.println(t.i);
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test

68
o
• If the instance variable declared as the final compulsory we should perform initialization
whether we are using or not otherwise we will get compile time error.
Example:
Program 1:
class Test

int i;

Output:
D:\Java>javac Test.java
D:\Java>
Program 2:
class Test

final int i;

Output:
Compile time error.
D:\Java>javac Test.java
Test.java:1: variable i might not have been initialized
class Test
Rule:
• For the final instance variables we should perform initialization before constructor
completion. That is the following are various possible places for this.
1) At the time of declaration:
Example:
class Test

final int i=10;

Output:
D:\Java>javac Test.java
D:\Java>
2) Inside instance block:
Example:
class Test

69
final int i;

i=10;
}}
Output:
D:\Java>javac Test.java
D:\Java>
3) Inside constructor:
Example:
class Test

final int i;
Test()
{
i=10;
}}
Output:
D:\Java>javac Test.java
D:\Java>
• If we are performing initialization anywhere else we will get compile time error.
Example:
class Test

final int i;
public void methodOne(){
i=10;
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:S: cannot assign a value to final variable i
i=10;
Final static variables:
• If the value of a variable is not varied from object to object such type of variables is not
recommended to declare as the instance variables. We have to declare those variables
at class level by using static modifier.
• For the static variables it is not required to perform initialization explicitly jvm will
always provide default values.

70
Example:
class Test

static int i;
public static void main(String args[]H
System.out.println("value of i is :"+i);
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
Value of i is: 0
• If the static variable declare as final then compulsory we should perform initialization
explicitly whether we are using or not otherwise we will get compile time error.
Example:
class Test class Test
{
valid invalid
static int i; final static int i;
}
\.;
~
D:\Java>javac Test.java
~est.java:l: variable i might not have been initialized
class Test

Rule:
• For the final static variables we should perform initialization before class loading
completion otherwise we will get compile time error. That is the following are possible
places.
1) At the time of declaration:
Example:
class Test

final static int i=10;

Output:
D:\Java>javac Test.java
D:\Java>
2) Inside static block:
Example:
class Test

final static int i;

71
static

i=10;
}}
Output:
Compile successfully.
• If we are performing initialization anywhere else we will get compile time error.
Example:
class Test

final static int i;


public static void main(String args[]H
i=10;
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:S: cannot assign a value to final variable i
i=10;

Final local variables:


• To meet temporary requirement of the programmer sometime we can declare the
variable inside a method or block or constructor such type of variables are called local
variables.
• For the local variables jvm won't provide any default value compulsory we should
perform initialization explicitly before using that variable.
Example:
class Test

public static void main(String args[]H


int i;
System.out.println("hello");
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
Hello
Example:

72
class Test

public static void main(String args[]H


int i;
System.out.println(i);
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: variable i might not have been initialized
System.out.printl n(i);
• Even though local variable declared as the final before using only we should perform
initialization.
Example:
class Test

public static void main(String args[]H


final int i;
System.out.println("hello");
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
hello
Note: The only applicable modifier for local variables is final if we are using any other
modifier we will get compile time error.
Example:
class Test
{
public static void main(String args[])
{
private int x=10; (invalid)
public int x=10; (invalid)
volatile int x=10; (invalid)
transient int x=10; -- (invalid)
final int x=10; (valid)
}
}
Output:
Compile time error.

73
D:\Java>javac Test.java
Test.java:5: illegal start of expression
private int x=10;
Formal parameters:
• The formal parameters of a method are simply access local variables of that method
hence it is possible to declare formal parameters as final.
• If we declare formal parameters as final then we can't change its value within the
method.
Example:
class Test{
public static void main(String args[]){
methodOne(lO,20);
}
public static void methodOne(final int x,int y){
/ /x=100; 1'--_---7) Formal parameters
y=200;
System.out.prin In(x+" .... "+y);
}
) output:
}
compile time error.
D:\Java>javac Test.java
Test.java:6: final parameter x may not be assigned
x=100;

Static modifier:
• Static is the modifier applicable for methods, variables and blocks.
• We can't declare a class with static but inner classes can be declaring as the static.
• In the case of instance variables for every object a separate copy will be created but in
the case of static variables a single copy will be created at class level and shared by all
objects of that class.
Example:
class Test{
static int x=10;
int y=20;
public static void main(String args[]){
Test tl=new Testt):
tl.x=888;
tl.y=999;
Test t2=new TestO;
svstem.out.prtntlnttz.x-" ....."+t2.y);
} tl
}
Output:

74
D:\Java>javac Test.java
D:\Java>java Test
888 ..... 20
• Instance variables can be accessed only from instance area directly and we can't access
from static area directly.
• But static variables can be accessed from both instance and static areas directly.
1) Int x=10;
2) Static int x=10;
3) Public void methodOnetj]
System.out. pri ntl n(x);

4) Public static void methodOne(){


System.out. pri ntl n(x);

Which are the following declarations are allow within the same class simultaneously?
a) 1 and 3
Example:
class Test

int x=10;
public void methodOne(){
System.out.println(x);
}}
Output:
Compile successfully.
b) 1 and 4
Example:
class Test

int x=10;
public static void methodOne(){
System.out.println(x);
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: non-static variable x cannot be referenced from a static context
System.out.println(x);
c) 2 and 3
Example:
class Test

75
static int x=10;
public void methodonetl]
System.out.println(x);
}}
Output:
Compile successfully.
d) 2 and 4

Example:
class Test

static int x=10;


public static void methodOneO{
System.out.println(x);
}}
Output:
Compile successfully.
e) 1 and 2
Example:
class Test

int x=10;
static int x=10;

Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: x is already defined in Test
static int x=10;
f) 3 and 4
Example:
class Test{
public void rnethodonetl]
System.out.println(x);

public static void methodOneO{


System.out.println(x);
}}
Output:
Compile time error.
D:\Java>javac Test.java

76
Test.java:5: methodOneO is already defined in Test
public static void method'Onelj]
• Overloading concept is applicable for static method including main method also.
Example:
class Test{
public static void main(String args[]){
System.out.println("StringO method is called");
}
public static void main(int args[]){
System.out.println("intO method is called");
} IThis method we have to call explicitly.1

• Inheritance concept is applicable for static methods including mainO method hence while
executing child class, if the child doesn't contain mainO method then the parent class main
method will be executed.
Example:
class Parent{
public static void main(String args[]){
System.out.println("parent mainO method called");
}
}
class child extends Parent{

Output:

ial' parentIva
Parent.class Child.class
java parent~
D:\Java>java Parent
parent mainO method called
D:\Java>java child
parent mainO method called

Example:
class Parent{
public static void main(String args(]){
System.out.println("parent mainO method called"};
}
}
class child extends Parent{
public static void main(String args[]){
System.out.println("child main!} method called");
lit is not overriding but method hiding.1
Output:

77
javac Parent.java

I
Parent.class
1
Child.class

java Parent~
D:\Java>java Parent
parent mainO method called
D:\Java>java child
child mainO method called
• It seems to be overriding concept is applicable for static methods but it is not overriding it is
method hiding.
• For static methods compulsory implementation should be available where as for abstract
methods implementation should be available hence abstract static combination is illegal for
methods.
Native modifier:
• Native is a modifier applicable only for methods but not for variables and classes.
• The methods which are implemented in non java are called native methods or foreign methods.
The main objectives of native keyword are:
• To improve performance of the system.
• To use already existing legacy non java code.
To use native keyword:

Pseudo code:
classNative{
static

Il)load native library.i S{yst em. Ioadtib


I rary
("N atorve lOb ")
I rary ;

}
i2)native method declaration.if-public native void methodOnel);
}
classClient

public static void main(String args(]){


Native n=new Nativel);
13) invoke a native method.lf---n.methodOnel);
}
}
• For native methods implementation is already available and we are not responsible to
provide implementation hence native method declaration should compulsory ends with
semicolon.
);- Public native void methodOneO----invalid
);- Public native void methodOneO;---valid

78
• For native methods implementation is already available where as for abstract methods
implementation should not be available child class is responsible to provide that, hence
abstract native combination is illegal for methods.
• We can't declare a native method as strictfp because there is no guaranty whether the
old language supports IEEE754 standard or not. That is native strictfp combination is
illegal for methods.
• For native methods inheritance, overriding and overloading concepts are applicable.
• The main disadvantage of native keyword is usage of native keyword in java breaks
platform independent nature of java language.
Synchronized:
• Synchronized is the modifier applicable for methods and blocks but not for variables and
classes.
• If a method or block declared with synchronized keyword then at a time only one thread
is allow to execute that method or block on the given object.
• The main advantage of synchronized keyword is we can resolve data inconsistency
problems, but the main disadvantage is it increases waiting time of the threads and
effects performance of the system. Hence if there is no specific requirement never
recommended to use synchronized keyword.
Transient modifier:
• Transient is the modifier applicable only for variables but not for methods and classes.
• At the time of serialization if we don't want to serialize the value of a particular variable
to meet the security constraints then we should declare that variable with transient
modifier.
• At the time of serialization jvm ignores the original value of the transient variable and
save default value that is transient means "not to serialize".
• Static variables are not part of object state hence serialization concept is not applicable
for static variables duo to this declaring a static variable as transient there is no use.
• Final variables will be participated into serialization directly by their values due to this
declaring a final variable as transient there is no impact.
Volatile modifier:
• Volatile is the modifier applicable only for variables but not for classes and methods.
• If the value of variable keeps on changing such type of variables we have to declare with
volatile modifier.
• If a variable declared as volatile then for every thread a separate local copy will be
created by the jvm, all intermediate modifications performed by the thread will takes
place in the local copy instead of master copy.

79
• Once the value got finalized before terminating the thread that final value will be
updated in master copy.
• The main advantage of volatile modifier is we can resolve data inconsistency problems,
but creating and maintaining a separate copy for every thread increases complexity of
the programming and effects performance of the system. Hence if there is no specific
requirement never recommended to use volatile modifier and it's almost outdated.
• Volatile means the value keep on changing where as final means the value never
changes hence final volatile combination is illegal for variables.
Modifier Classes Methods Variables Blocks Interfaces Enum Constructors
Outer Inner
Public
-vi -vi -vi -vi X -vi -vi -vi
Private
X -vi -vi -vi X X X -vi
Protected
X -vi -vi -vi X X X -vi
Default
-vi -vi -vi -vi X -vi -vi -vi
Final
-vi -vi -vi -vi X X X X
Abstract
-vi -vi -vi X X -c/ X X
Strictfp
-vi -vi -vi X X -vi -vi X
Static
X -vi -vi -vi -vi X X X
Synch ron ized
X X -vi X -vi X X X
Native
X X -vi X X X X X
Transient
X X X -vi X X X X
Volatile
X X X -vi X X X X
Summary of modifier:
• The modifiers which are applicable for inner classes but not for outer classes are
private, protected, static.
• The modifiers which are applicable only for methods native.
• The modifiers which are applicable only for variables transient and volatile.
• The modifiers which are applicable for constructor public, private, protected, default.
• The only applicable modifier for local variables is final.
Interfaces:
1) Introduction
2) Interface declarations and implementations.
3) Extends vs implements
4) Interface methods
5) Interface variables
6) Interface naming conflicts
a) Method naming conflicts

80
b) Variable naming conflicts
7) Marker interface
8) Adapter class
9) Interface vs abstract class vs concrete class.
10) Difference between interface and abstract class?
11) Conclusions
Def1: Any service requirement specification (srs) is called an interface.
Example1: Sun people responsible to define JDBC API and database vendor will provide
implementation for that.
Diagram:

Example2: Sun people define SERVLETAPI to develop web applications web server vendor is
responsible to provide implementation.

Diagram:

Def2: From the client point of view an interface define the set of services what his excepting.
From the service provider point of view an interface defines the set of services what is offering.
Hence an interface is considered as a contract between client and service provider.
Example: ATM GUI screen describes the set of services what bank people offering, at the same
time the same GUI screen the set of services what customer his excepting hence this GUI screen
acts as a contract between bank and customer.
Def3: Inside interface every method is always abstract whether we are declaring or not hence
interface is considered as 100% pure abstract class.

81
Summery def: Any service requirement specification (SRS)or any contract between client and
service provider or 100% pure abstract classes is considered as an interface.
Declaration and implementation of an interface:
Note1: Whenever we are implementing an interface compulsory for every method of that
interface we should provide implementation otherwise we have to declare class as abstract in
that case child class is responsible to provide implementation for remaining methods.
Note2: Whenever we are implementing an interface method compulsory it should be declared
as public otherwise we will get compile time error.
Example:
interface Interf

void methodonef):
void methcdTwot):
}

class SubServiceProvider extends ServiceProvider


{
}

Output:
Compile time error.
D:\Java>javac SubServiceProvider.java
SubServiceProvider.java:1: SubServiceProvider is not abstract and does not override abstract
method methodTwoO in Interf
class SubServiceProvider extends Service Provider
Extends vs implements:
• A class can extend only one class at a time.
Example:
class One{
public void methodonef)]
}
}
class Two extends One{

• A class can implements any no. Of interfaces at a time.

82
Example:
interface One{
public void methodOne();
}
interface Two{
public void methodTwo();
}
class Three implements One.Two]
public void methodOne(){
}
public void methodTwo(){
}
}
• A class can extend a class and can implement an interface simultaneously.
interface One{
void methodOne();
}
class Two

public void methodTwo(){


}
}
class Three extends Two implements One{
public void methodOne(){
}
}
• An interface can extend any no. Of interfaces at a time.
Example:
interface One{
void methodOne();
}
interface Two{
void methodTwo();
}
interface Three extends One/Two
{
}
1) Which of the following is true?

83
1. A class can extend any no. Of classes at a time.
2. An interface can extend only one interface at a time.
3. A class can implement only one interface at a time.
4. A class can extend a class and can implement an interface but not both
simultaneously.
5. None of the above.
Ans: 5
2) Consider the expression X extends V for which of the possibility of X and Y this
expression is true?
1. Both x and y should be classes.
2. Both x and y should be interfaces.
3. Both x and y can be classes or can be interfaces.
4. No restriction.
Ans: 3
3) X extends V, Z?
• X, Y, Z should be interfaces.
4) X extends V implements Z?
• X, Y should be classes.
• Z should be interface.
S) X implements Y, Z?
• X should be class.
• Y, Z should be interfaces.
6) X implements Y extend Z?
Example:
interface One{

class Two {

class Three implements One extends Two{

Output:
Compile time error.
D:\Java>javac Three.java
Three.java:5: '{' expected
class Three implements One extends Two{
• Every method present inside interface is always public and abstract whether we are
declaring or not. Hence inside interface the following method declarations are equal.
void methodOne();

84
public Void methodOne();
abstract Void methodOne(); Equal
public abstract Void methodOne();
• As every interface method is always public and abstract we can't use the following
modifiers for interface methods.
• Private, protected, final, static, synchronized, native, strictfp.
Inside interface which method declarations are valid?
1. public void methodOne(){}
2. private void methodOne();
3. public final void methodOne();
4. public static void methodOne();
5. public abstract void methodOne();
Ans: 5
Interface variables:
• An interface can contain variables to define requirement level constants.
• Every interface variable is always public static and final whether we are declaring or
not.
Example:
interface interf

int x=10;

Public: To make it available for every implementation class.


Static: Without existing object also we have to access this variable.
Final: Implementation class can access this value but cannot modify.
• Hence inside interface the following declarations are equal.
int x=10;
public int x=10;
static int x=10;
final int x=10; Equal
public static int x=10;
public final int x=10;
static final int x=10;
public static final int x=10;
• As every interface variable by default public static final we can't declare with the
following modifiers.
• Private
• Protected

85
• Transient
• Volatile
• For the interface variables compulsory we should perform initialization at the time of
declaration only otherwise we will get compile time error.
Example:
interface Interf

int x;

Output:
Compile time error.
D:\Java>javac Interf.java
Interf.java:3: = expected
int x;
Which of the following declarations are valid inside interface?
1. int x;
2. private int x=10;
3. public volatile int x=10;
4. public transient int x=10;
5. public static final int x=10;
Ans: 5
• Interface variables can be access from implementation class but cannot be modified.
Example:
interface Interf

int x=10;

Example 1:

class Test implements Interf


{
public static void main(String args[]){
x=20;
System.out.println("value of x"+x);
}
}
output:
compile time error.
D:\Java>javac Test.java
Test.java:4: cannot assign a value to final variable x
x=20;

86
Example 2:
class Test implements Interf

public static void main(String args[]H


int x=20;
/ /here we declaring the variable x.
System.out.printl n(x);
}
}
Output:
D:\Java>javac Test.java
D:\Java>java Test
20
Interface naming conflicts:
Method naming conflicts:
Case 1:
• If two interfaces contain a method with same signature and same return type in the
implementation class only one method implementation is enough.
Example 1:
interface Left

public void methodonet):


}
Example 2:
interface Right

public void methodOneO;

Example 3:
class Test implements Left,Right
{
public void methodOneO
{
}}
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java

87
Case 2:
• if two interfaces contain a method with same name but different arguments in the
implementation class we have to provide implementation for both methods and these
methods acts as a overloaded methods
Example 1:
interface Left

public void methodOne();


}
Example 2:
interface Right

public void methodOne(int i);


}
Example 3:
class Test implements Left,Right
{
public void methodOne()
{
}
public void methodOne(int i)
{
}}
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
Case 3:
• If two interfaces contain a method with same signature but different return types then
it is not possible to implement both interfaces simultaneously.
Example 1:
interface Left

public void methodOne();

Example 2:
interface Right

88
public int methodOne(int i);

• We can't write any java class that implements both interfaces simultaneously.
Is a java class can implement any no. Of interfaces simultaneously?
• Yes, except if two interfaces contains a method with same signature but different return
types.
Variable naming conflicts:
• Two interfaces can contain a variable with the same name and there may be a chance
variable naming conflicts but we can resolve variable naming conflicts by using interface
names.
Example 1:
interface Left

int x=888;

Example 2:
interface Right

int x=999;

Example 3:
class Test implements Left,Right
{
public static void main(String args[]H
j jSystem.out.println(x);
System.out.println(Left.x);
System.out.println(Right.x);
}
}
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
D:\Java>java Test
888
999

89
Marker interface: if an interface doesn't contain any methods and by implementing that
interface if our object gets some ability such type of interfaces are called Marker interface (or)
Tag interface (or) Ability interface.
Example:
Serilizable
cloneable
RandomAccess These are marked for some ability
SingleThreadModel

Example 1: By implementing Serilizable interface we can send that object across the network
and we can save state of an object into a file.
Example 2: By implementing SingleThreadModel interface Servlet can process only one client
request at a time so that we can get "Thread Safety".
Example 3: By implementing Cloneable interface our object is in a position to provide exactly
duplicate cloned object.
Without having any methods in marker interface how objects will get ability?
• Internally JVM will provide required ability.
Why JVM is providing the required ability?
• To reduce complexity of the programming.
Is it possible to create our own marker interface?
• Yes, but customization of JVM is required.
Adapter class:
• Adapter class is a simple java class that implements an interface only with empty
implementation for every method.
• If we implement an interface directly for each and every method compulsory we should
provide implementation whether it is required or not. This approach increases length of
the code and reduces readability.
Example 1:
interface X{
void miO;
void m20;
void m30;
void m40;
//.
//.

90
II.
II.
void mSO;
}
Example 2:
class Test implements X{
public void m30{
System.out.println("m30 method is called");
}
public void ml0n
public void m20n
public void m40n
public void mSon
}
• We can resolve this problem by using adapter class.
• Instead of implementing an interface if we can extend adapter class we have to provide
implementation only for required methods but not for all methods of that interface.
• This approach decreases length of the code and improves readability.
Example 1:
abstract class AdapterX implements X{
public void ml0n
public void m20n
public void m30n
public void m40n
If.
If.
If.
public void ml0000n
}
Example 2:
public class Test extend AdapterX{{
public void m30{
}}
Example:

91
Servlet(l}
GiriCServlet(Ac}

import javax.servlet. *;
class MyServlet implements Servlet{
public void init(ServletConfig config){}
public void destroyOO
public void service(ServletRequest request,ServletRespons response){}
public String getServletlnfoO{return null;}
public ServletConfig getServletConfigO{return null;}
}

import javax.servlet. *;
class MyServletl extends GenericServlet{
public void service(ServletRequest request,ServletResponse response){}
}

• Generic Servlet simply acts as an adapter class for Servlet interface.


What is the difference between interface, abstract class and concrete class?
When we should go for interface, abstract class and concrete class?
• If we don't know anything about implementation just we have requirement
specification then we should go for interface.
• If we are talking about implementation but not completely (partial implementation)
then we should go for abstract class.
• If we are talking about implementation completely and ready to provide service then we
should go for concrete class.
Example:
servlet(l)

GeLriCserv,et(AC)

HttpServlet(AC)

I
MaiISendingServlet(CC)

What is the Difference between interface and abstract class?


interface Abstract class
1) If we don't' know anything about 1) If we are talking about implementation
implementation just we have but not completely (partial
requirement specification then we implementation) then we should go for
should go for interface. abstract class.

2) Every method present inside interface 2) Every method present inside abstract
is always public and abstract whether class need not be public and abstract.
we are declaring or not.
3) We can't declare interface methods 3) There are no restrictions on abstract

92
with the modifiers private, protected, class method modifiers.
final, static, synchronized, native,
strictfp.
4) Every interface variable is always 4) Every abstract class variable need not
public static final whether we are be public static final.
declaring or not.
5) Every interface variable is always 5) There are no restrictions on abstract
public static final we can't declare with class variable modifiers.
the following modifiers. Private,
protected, transient, volatile.
6) For the interface variables compulsory 6) It is not require to perform
we should perform initialization at the initialization for abstract class variables
time of declaration otherwise we will at the time of declaration.
get compile time error.
7) Inside interface we can't take static 7) Inside abstract class we can take both
and instance blocks. static and instance blocks.
8) Inside interface we can't take 8) Inside abstract class we can take
constru ctor. constructor.
We can't create object for abstract class but abstract class can contain constructor what is the
need?
• This constructor will be executed for the initialization of child object.
Example:
class Parent{
Parent()
{
System .out. pri ntl n(th is.hashCode ());
}
}
class child extends Parent{
child(){
System .out. pri ntl n(th is.hashCode ());
}
}
class Test{
public static void main(String args[]H
child c=new childf):
System .out. pri ntl n(c.hashCode());
}
}

93
Every method present inside interface is abstract but in abstract class also we can take only
abstract methods then what is the need of interface concept?
• We can replace interface concept with abstract class. But it is not a good programming
practice. We are misusing the roll of abstract class.

Operator and assignments


1) Increment and decrement operator
2) Arithmetic operators
3) String concatenation operator
4) Relational operators
5) Equality operator
6) Instanceof operator
7) Bitwise operators
8) Short circuit operators

94
9) Type cast operator
10) Assignment operator
11) Conditional operator
12) new operator
13) [] operator
14) Java operator precedence
15) Evaluation order of java operands
Increment and decrement operator:
Diagram 1:

r-.
increment

preincrement postincrement
y=++Xj y=x++
Diagram 2:

r.
decrement

predecrement postdecrement
y=--x y=x--
Example'
Expression Initial value of x Final value of x Final value of y.
Y=++x; 10 11 11
Y=x++; 10 11 10
Y=--x; 10 9 9
Y=x--; 10 9 10
• We can apply increment or decrement operator only for variables but not for constant
values.

Example:

95
class Test{ class Test{
public static void main(String[] args){ public static void main(String[] args){
int x=4j int x=4;
int Y=++Xj int y=++4j
System.out.println("value of y :"+y)j System.out.println("value of y :"+y)j
} output: } output:
}s } comnlla time ~rror
Test.java:4: unexpected type
required: variable
found : value
int y=++4j
• Nesting of increment or decrement operators is not allowed.
Example:

class Test{
public static void main(String[] args){
int x=4j
int y=++(++x)j it will become constant
System.out.println("value of y :"+y)j
} output:
} com ile time error
Test.java:4: unexpected type
required: variable
found : value
int y=++(++x)j
• We can't apply increment or decrement operator for final variables.
Example:

class Test{
public static void main(String[] args){
final int x=4j
X++j
System.out.println("value of X:"+X)j
} output:
} com ile time error
Test.java:4: cannot assign a value to final variable x
X++j
• We can apply increment or decrement operator for any primitive type except Boolean.

Example:

96
class Test{ class Test{ class Test{
public static void main(String[] args){ public static void main(String[] args){ public static void main(String[] args){
int x=4; char ch='a'; double d=10.S;
x++; ch++; d++;
System.out.println("value of x:"+x); System.out.println("value of ch:"+ch); System.out.println("value of d:"+d);
} outpt: }output: } output:
} ",,1,,<> "f v·" } va I1lII" nf l'h'h } ,,21,,<> "f ~'11 ..

class Test{
public static void main(String[] args}{
boolean b=true;
b++j
System.out.println("value of b:"+b}j
}output:
}compile time error
Test.java:4: operator ++ cannot be applied to boolean
b++:
• If we apply any arithmetic operator between two variables "a" and "b" the result type is
always.
max(int,typeof a,typeof b)
Example 1:
byte a=10;
OperatorsDemo.java:7: possible loss of precision
byte b=20;
found : int
byte c=Sf----C-.-E----___;>~ required: byte
System.out.println(c); byte c=a+b;

Example 2:

byte b=10; byte b=10j


b++' ~E OperatorsDemo.java:6:possibleloss of precision
, b- b+l" .
System.out.println(b)i!lll' found : mt
System.out.println(b)i required: byte
b=b+li

• In the case of increment or decrement operator the required type-casting will be


performed automatically by the compiler.
b++; means
b=(type of b)(b+1);
b=(byte)(b+1);
Example:
byte b=10;
b++;
System.out.println(b);/ /11
Arithmetic operators: (+,-, *, /, %)

97
• If we apply any arithmetic operation between two variables "a" and "b". The result type
is always.
max(int, type of a, type b)
byte+byte=i nt int+long=long
byte+short=int float+double=double
byte+int=int long+long=long
char+char=int long+float=float
char+int=int
byte+ehar=int
Example:
System.out.println('a'+ 1);//98
System.out.println(,a'+'b');/ /195
System.out.println(10+0.5);/ /10.5
System.out.println(,a'+3.5);/ /100.5
Infinity:
• In the case of integral arithmetic (byte, short, int, long) there is no way to represent
infinity.
• Hence if infinity is the result then we will get ArithmeticException.
Example:

system.out.println(10/ob~]R~.E~~~~~IE~x;ce;p;t~io;n~i;n~th~r~e;ad~"m~ai~n~"~ja~v;a~.la;n~g~.A~r~it;h;m~e~ti~cE~x;ce;p;t~io;n;:7/~by~ze;r~ol
• But in floating point arithmetic(float, double), there is a way to represent infinity. For
this Float and Double classes contains the following two constants.
POSITIVE-INFINITIVE;
NEGITIVE-INFINITIVE;
• Hence if infinity is the result we won't get any runtime exception in floating point
arithmetic.
Example:
System.out.println(10/0.0);/ /+Infinity
System.out.printl n(-10/0.0);// -I nfi nity
NaN(Not a Number):
• In the case of integral arithmetic there is no way to represent "undefined results".
Hence if the result is undefined we will get runtime exception saying
Arith meticException.
Example:

System.out.println(O/O)i _..:..:.R:..::.E;__....;>~IExcePtion
in thread "main" java.lang.ArithmeticException: / by zerol

• But in floating point arithmetic (float, double), there is a way to represent undefined
result for this Float and Double classes contain "NaN".

98
• Hence if the result is undefined, we won't get any runtime exception in floating point
arithmetic.
Example:
System.out.println(O.O/O);/ /NaN
System.out.println(-O.O/O);/ /NaN
System.out.println(O/O.O);/ /NaN
• For any x value including NaN the following expressions return false.
Example:
class Test

public static void main(String[] args)


{
int x=10;
System.out.pri ntln (x>Float. Na N);/ /fa Ise
System.out.println(x<Float.NaN);/ /false
System.out.println(x>=Float. NaN);/ /false
System.out.println(x<=Float. NaN);/ /false
System.out.println(x==Float. NaN);/ /false

• For any x value including NaN the following expression return true.
Example:
class Test

public static void main(String[] args)


{
int x=10;
System.out.println(x!=Float.NaN);/ /true
System.out.println(Float.NaN !=Float. NaN);/ /true

Summary:
r-~l)lt is a RuntimeExceptionbut not compile time exception.

"'__~3)The only operators which causesArithmeticExceptionare /, %.

99
String concatenation operator:
• The only operator which is overloaded in java is 1/+" operator. Sometime it acts as
arithmetic addition operator and some time concatenation operator.
• If at least one argument is string type then U+/J operator acts as concatenation and if
both arguments are number type then it acts as arithmetic addition operator.
Example 1:
String a="bhaskar";
int b=10,c=20,d=30;
System.out.printl n(a+b+c+d);/ /bhaskar102030
System.out.println(b+c+d+a);/ /60bhaskar
System .out. pri ntl n(b+c+a+d);/ /30b haska r30
Svstern.out.printlnlb+a+c+dl./ /lObhaskar2030
Example 2:
String a="bhaskar",' E:\ sqpc-javac
. . .
OperatorsDemo.java
int b=10,c=20,d=30i OperatorsDemo.java:7: incompatible types
a~)-___;C:.:..:.E---~)lfound : int
System.out.println(c)i required: java.lang.String
a=b+c+di
Example 3:
String a="bhaskar"i
int b=lO,c=20,d=30i
a=a+b+ci
E:\scjp>javac OperatorsDemo.java
c=b+di
OperatorsDemo.java:9: incompatible types
c= 8 >found : java.lang.String
System.out.println(a)i/ /bhaskarl020 required: int
System.out.println( C}i/ / 40 a...- c_=_a_+_b_+...,;di:..,._ __'
System.out.println(c}i
Relational operator: «, <=, >, =)
• We can apply relational operators for every primitive type except boolean.
Example:
System.out.println(10)10.5)illfalse
System.out.println('a'>95.5)illtrue E:\scjp>javacOperatorsDemo.java
System.out.println('z'>'a')il Itrue OperatorsDemo.java:8: operator> cannot be applied to boolean,boolean
System.out.println~rue>fabe~-c~.=E~~~L__ ~S~y~st=e~m~.~o=ut=.p~r~in~t=ln~(=tr~u=e>~f=a=ls=e~~ ~
• We can't apply relational operators for the object types.
Example:
System.out.println(lbhaskarl>lbhaskar");.....;C;..;.;.E;;.....---.
~
OperatorsDemo.java:5: operator> cannot be applied to java.lang.String,java.lang.String
System.out.printl n(" bhaskar" >" bhaskar");

100
• We can't perform nesting of relational operators.
Example:
E:\scjp>javac OperatorsDemo.java
System.out.println(lO<20<30)j C.E > OperatorsDemo.java:5: operator < cannot be applied to boolean,int
System.out.println(lO<20<30)j

Equality operator :(==,!=)


• We can apply equality operators for every primitive type including boolean type also.
Example:
System.out.println(lO==lO.O);/ /true
System.out.printl n('a'==97 .0);/ /true
System.out.printl n(true==true);/ /true
System.out.println('a' !='b');/ /true
• We can apply equality operator even for object reference also.
• In the case of object references == (double equal operator) is always meant for
reference comparison only (address comparison).
• i.e. rl==r2 return true if and only if both rl and r2 point to the same object.
Example:
Thread t1=new Thread();
Thread t2=new Thread();
Thread t3=t1;
System.out.println(t1==t2);/ /false
System.out.println(t1==t3);/ /true
Diagram:

:~=O"--0
• To use equality operator compulsory there should be some relationship between
argument type(either parent-child (or)child-parent (or) same type)otherwise we will get
compile time error saying" incomparable types".
Example:
Object o=new Object();
String s=new String("bhaskar");
StringBuffer sb=new StringBuffer();
System.out.printl n(o==s);/ /false
System.out.println( o==sb);/ /false
. __. C.E E:\scjp>javac OperatorsDemo.java
System.out.prmtln(s--sb),~ OperatorsDemo.java:l0: incomparable types: java.lang.String and java.lang.StringBuffer
System.out.println(s::sb)j

101
Diagram:

• For any object reference of, r==null is always false. But null==null is true.
== Vs .egualsO:
• ==operator is always meant for reference comparison whereas .equals() method mostly
meant for content comparison.
Example:
String sl=new String("bhaskar");
String s2=new String("bhaskar");
System.out.println(sl==s2);/ /false
System.out.println(sl.equals(s2) );/ /true
Diagram:

Instanceof operator:
• We can use this operator to check whether the given object is of particular type (or) not.
Syntax:

r instanceof

object reference class/interface

Example:
Thread t=new Thread();
System.out.println(t instanceof Thread);/ /true
System.out.println(t instanceof Object);/ /true
System.out.println(t instanceof Runnable);/ /true
Diagram:

°"f/
Thread
n bl

• •

Note:
• To use "instanceof" operator compulsory there should be some relationship between
argument types (either parent-child (or) child-parent (or) same type) otherwise we will
get compile time error saying "inconvertible types".

102
Example:

E:\scjp>javac OperatorsDemo.java
String s=new String("bhaskar"); OperatorsDemo.java:6: inconvertible types
System.out.println(s instanceof Thread); ~ found : java.lang.String
required: java.lang.Thread
System.out.println(s instanceof Thread)i

• Whenever we are comparing parent object is child type or not by using instanceof
operator then we will get "false" as output.
Example:
Object o=new Object();
System.out.println(o instanceof String);! /false
• For any class or interface x
null instanceof x the result is always "false".
Example:
System.out.println(null instanceof String);//false
Bitwise operators:
& (AND): If both arguments are true then result is true.
I (OR): if at least one argument is true. Then the result is true.
I\. (X-OR): if both are different arguments. Then the result is true.
Example:
System.out.println(true&false);/ /false
System.out.println(true I false);! /true
System.out.println(true"false);! /true
• We can apply bitwise operators even for integral types also.
Example:
System.out.println(4&S);//4 100 100 100
System.out.println(4IS)i//S 101 101 101
System.out.println(4I\.S)i//1 100 101 001
Bitwise complement (-) (tilde symbol) operator:
• We can apply this operator only for integral types but not for boolean types.
Example 1:

E:\scjp>javac OperatorsDemo.java
System.out.println("'true)i~ OperatorsDemo.java:5: operator'" cannot be applied to boolean
System .out.pri ntln("'true)i

Example 2:
System.out.println("'4);/ /5

103
3
-4

o
Boolean complement (!) operator:
• This operator is applicable only for boolean types but not for integral types.
Example:
. CE E:\scjp>javac OperatorsDemo.java
System.out.prmtln(!4};~ OperatorsDemo.java:5: operator! cannot be applied to int
System.out.println( 14};

System.out.println( !true);! /false


System.out.println( !false);! /true
Summary:

r }APPlicable for both boolean and integral types.

N--------Applicable for integral types only.


! --------Applicable for boolean types only.
Short circuit (&&, II) operators:
• These operators are exactly same as normal bitwise operators &, 1 except the following
differences.
&,1 &&,11
1) Both arguments should be evaluated 1) Second argument evaluation is
always. optional.
2) Relatively performance is low. 2) Relatively performance is high.
3) Applicable for both integral and 3) Applicable only for boolean types but
boolean types. not for integral types.
1) r1&&r2
• r2 will be evaluated if and only if rl is true.
2) r111 r2
• r2 will be evaluated if and only if rl is false.
Example 1:
class OperatorsDemo

public static void main(String[] args)


{

104
int x=10, y=15;
if( ++x> 10( operator)++y<15)
{
++x;

else

++y;

System .out. pri ntl n(x+" ------------" +y);

Outnut:
operator x y
& 11 17
I 12 16
&& 11 17
II 12 15
Example 2:
class OperatorsDemo

public static void main(String[] args)


{
int x=10;
if( ++x<10( operator)x/O> 10)
{
System.out.println("hello");

else

System.out.printl n(" hi");

&& Output: Hi
& Output: R.E: Exception in thread "main"
java.lang.ArithmeticException: / by zero
Type-cast operator (primitive type casting):
• There are two types of primitive type casting.

105
1) Implicit type casting.
2) Explicit type casting.
Implicit type casting:
• Compiler is the responsible for this typecasting.
• Whenever we are assigning smaller data type value to the bigger data type variable this
type casting will be performed.
• Also known as widening or up casting.
• There is no lose of information in this type casting.
• The following are various possible implicit type casting.
Diagram:
byte --)~Short~.
~ mt --)~ long --)~ float -~) double
char--- '
Example 1:
int x='a';
System.out.println(x);/ /97
Note: Compiler converts char to int type automatically by implicit type casting.
Example 2:
double d=10;
System.out.println(d);/ /10.0
Note: Compiler converts int to double type automatically by implicit type casting.
Explicit type casting:
• Programmer is responsible for this type casting.
• Whenever we are assigning bigger data type value to the smaller data type variable then
explicit type casting is required.
• Also known as Narrowing or down casting.
• There may be a chance of lose of information in this type casting.
• The following are various possible conversions where explicit type casting is required.
Diagram:

byte--)~short.........__ '"
8 16 ~int -~) long --)~ float _~) double
char~ 32 64 32
16
Example 1:

E:\scjp>javacOperatorsDemo.java
int x=130j OperatorsDemo.java:6: possible loss of precision
byte b=xj -____;;>~ found : int
required: byte
byte b=xj

106
Example 2:
int x=130;
byte b=(byte)x;
System.out.println(b);/ /-126
Analysis:

x(130)= 0000000010000010 2 130

byte b =(b7yt)x= 1 ~~~~~~~ 2 65 -- 0 1\


11 2 32 --1
---
1111110 2 16 -- 0
signbit 2 8 -- 0
o +ve
1----ve 2 4 --0

0*20+1*21+1*22+1*23+1*24+1*25+1*26 2 2 --0
0*1+1*2+1*4+1*8+1*16+1*32+1*64 1
/
0+2+4+8+16+32+64
-126
• Whenever we are assigning bigger data type value to the smaller data type variable by
explicit type casting the most significant bit(MSB)wili be lost.
Example:
int x=lS0;
short s=(short)x;
System.out.println(s);/ /150
byte b=(byte)x;
System.out.println(b);/ /-106
• Whenever we are assigning floating point data types to the integer data type by explicit
type casting the digits after the decimal point will be loosed.
Example:

float x=150.1234fj double d=130.456j


int i=(int)xj int i=(int)dj
System.out.println(i)j/ /150 System.out.println(i)j/ /130

Assignment operators:
• They are three types of assignment operators.
Simple assignment:
Example: int x=10;
Chained assignment:
Example:
int a,b,c,d;
a=b=c=d=20;

107
System .out. pri ntl n(a+" --- +b»
II II " +c+ II--- II +d);/ /20--- 20---20---20
• We can't perform chained assignment directly at the time of declaration.
Example 1:
cannot find symbol
int a=b=c=d=20j ~ variable b
variable c
variable d

Example 2:
int a,b,c,d;
a=b=c=d=30;
Compound assignment:
• Sometimes we can mix assignment operator with some other operator to form
compound assignment operator.
• The following is the list of all possible compound assignment operators in java.
Example 1:
+=

&= »=
*=
1= »>=
/= 1\=«=
%=
• In the case of compound assignment operator the required type casting will be
performed automatically by the compiler similar to increment and decrement
operators.
Example 2:
E:\scjp>javac OperatorsDemo.java
byte b=10j
CE OperatorsDemo.java:6: possible loss of precision
b=b+lj--=·...__-___;"~I
found : int
svstern.out.printlntb): required: byte
beb+I:

Example 3:
byte b=10j
int a.b.c.d:
byte b=10j / /b+=lj a=b=c=d=20j
b++j b=(byte)(b+1)j a+=b-=c*=d/=2j
System.out.println(b)j/ /11 System.out.println(b)j/ /11 System.out.println(a+"--"+b+" "+c+" __-"+d)j

//-160---180---200---10

Conditional operator:
• The only ternary operator which is available in java is conditional operator.

108
Example 1:
int x=(10)20)?30:40;
System.out.println(x);/ /40
• We can perform nesting of conditional operator also.
Example 2:
int a=10,b=20;
T T
byte c1=(10)20)?30:40;
~~
int X=(10~>20)?40:50)i int x=(10)20)?30:((100<20)?40:50)i byte c2=(10<20)?30:40j
.
System.out.pnntln(x);
//40
"-.f./ System.out.println(x)i/ /50 System.out.println(c1)i/ /40
System.out.println(c2)j/ /30
Example 5:

int a=10,b=20i E:\scjp>javac OperatorsDemo.java


byte Cl=(a>b)?30:40;} ~ OperatorsDemo.java:6: possible loss of precision
byte c2=(a<b)?30:40; found : int
System.out.println(cl)i required: byte
System.out.println(c2)i byte cl=(a>b)?30:40i

Example 6:
final int a=10,b=20;
byte cl=(a>b)?30:40;
byte c2=(a<b)?30:40;
System.out.println(cl);/ /40
System.out.println(c2);/ /30
new operator:
• We can use "new" operator to create an object.
• There is no "delete" operator in java because destruction of objects is the responsibility
of garbage collector.
[] operator:
• We can use this operator to declare and construct arrays.
Java operator precedence:
Unary operators:
[], x++, X--,

new, <type>.
Arithmetic operators:

Shift operators:

109
Compression operators:
<J <=J>J>=J instanceof.
Equality operators:
==J!=
Bitwise operators:
&/'JI.
Short circuit operators:
&&JII·
Conditional operator:
(7:)
Assignment operators:
+=J-=J *=JI=J%='
Evaluation order of java operands:
• There is no precedence for operands before applying any operator all operands will be
evaluated from left to right.
Example:
class OperatorsDemo

public static void main(String[] args)


{
System.out.printl n( m l(l)+m 1(2)*m 1(3)/m 1(4)* m 1(5)+m 1(6));

public static int m1(int i)


{
System.out.printl n(i);
return i;

output: Analysis:
1 1+2*3/4*5+6
2 1+6/4*5+6
3 1+1*5+6
4 1+5+6
5 12
6
12

110
Example 1:
int x=10; int x=10; int x=10;
x=++x; x=x+1; int y=x++;
System.out.println(x);/ /11 System.out.println(x);/ /11 System.out.println(y);/ /10
System.out.println(x);/ /11
Example 2:
int i=l;
i+=++i + i++ + ++i + i++;
System.out.println(i);/ /13Analysis:
i=i+ ++i + i++ + ++i + i++;
i=1+2+2+4+4;
i=13;

111
Flow Control
• Flow control describes the order in which all the statements will be executed at run
time.
Diagram:
Flow control

1.selection statements 2.iterative statements 3.transfer statements


1.if_else 1.whileO 1.break
2.switch 2.do-whileO 2.continue
3.forO 3.return
4.forEachO (l.S) 4. try-catch-finally
S.assert{1.4)

Selection statements:
1. if-else:
Syntax:
'I ---:;)';'boolean

if(b}
{
{{action if b is true
}else{
{{action if b is false
}
• The argument to the if statement should be Boolean if we are providing any other type
we will get "compile time error".
EXAMPLE 1:
public class Examplelf{
public static void main(String args[]H
int x=O;
if(x)
{
System.out.println("hello");
}else{
System.out.printl n(" hili);
}}}
OUTPUT:
Compile time error:
D:\Java>javac Examplelf.java
Examplelf.java:4: incompatible types
found : int
required: boolean
if(x)
EXAMPLE 2:
public class Examplelf{

112
public static void main(String args[]H
int x=10;
if(x=20)
{
System.out.println("hello");
}else{
System.out.printl n(" hili);
}}}
OUTPUT:
Compile time error
D:\Java>javac Examplelf.java
Examplelf.java:4: incompatible types
found : int
required: boolean
if(x=20)
EXAMPLE 3:
public class Examplelf{
public static void main(String args[]H
int x=10;
if(x==20)
{
System.out.println("hello");
}else{
System.out.println("hi");
}}}
OUTPUT:
Hi
EXAMPLE 4:
public class Examplelf{
public static void main(String args[]H
boolean b=false;
if(b=true)
{
System.out.println("hello");
}else{
System.out.println("hi");
}}}
OUTPUT:
Hello
EXAMPLE 5:
public class Examplelf{
public static void main(String args[]H
boolean b=false;
if(b==true)

113
System.out.println("hello");
}else{
System.out.printl n(" hi");
}}}
OUTPUT:
Hi
• Both else and curly braces are optional.
• Without curly braces we can take only one statement under it but it should not be
declarative statement.
EXAMPLE 6:
public class Examplelf{
public static void main(String args[]){
if(true)
System.out.println("hello");
}}
OUTPUT:
Hello
EXAMPLE 7:
public class Examplelf{
public static void main(String args[]){
if(true);
}}
OUTPUT:
No output
EXAMPLE 8:
public class Examplelf{
public static void main(String args[]){
if(true)
int x=10;
}}
OUTPUT:
Compile time error
D:\Java>javac Examplelf.java
Examplelf.java:4: '.class' expected
int x=10;
Examplelf.java:4: not a statement
int x=10;
EXAMPLE 9:
public class Examplelf{
public static void main(String args[]){
if(true){
int x=10;
}}}

114
OUTPUT:
D:\Java>javac Examplelf.java
D:\Java>java Examplelf
EXAMPLE 10:
public class Examplelf{
public static void main(String args[]){
if(true)
System.out.println("hello"); dependent statement on if
System.out.println("hi"); this is independent statement on if
}
}
OUTPUT:
Hello
Hi
• Semicolon is a valid java statement which is call empty statement and it won't produce
any output.
• If several options are available then it is not recommended to use if-else we should go
for switch statement.
Switch:
Syntax:
switch(x)
{
case 1:
action1
case 2:
action2

default:
default action

• Curly braces are mandatory.


• Both case and default are optional.
• Every statement inside switch must be under some case (or) default. Independent
statements are not allowed.
EXAMPLE 1:
public class ExampleSwitch{
public static void main(String args[]H
switch(x)
{
System.out.println("hello");
}}}

115
OUTPUT:
Compile time error.
D:\Java>javac ExampleSwitch.java
ExampleSwitch.java:5: case, default, or 'l' expected
System.out.println("hello");
• Until 1.4 version the allow types for the switch argument are byte, short, char, int but
from 1.5 version on wards the corresponding wrapper classes (Byte, Short, Character,
Integer) and "enum" types are allowed.
DIAGRAM:

byte Byte

switch(x)
short Short
{
} + I Stringl
int Integer 1.7v

char Character
l.4v +
IE!numl
1.5v
• Every case label should be "compile time constant" otherwise we will get compile time
error.
EXAMPLE 2:
public class ExampleSwitch{
public static void main(String args[]H
int x=10;
int y=20;
switch(x)
{
case 10:
System.out.printl n(110");
case y:
Svstern.out.printlntZn"):
}}}
OUTPUT:
Compile time error
D:\Java>javac ExampleSwitch.java
ExampleSwitch.java:9: constant expression required
case y:
• If we declare y as final we won't get any compile time error.
EXAMPLE 3:
public class ExampleSwitch{
public static void main(String args[]H
int x=10;

116
final int y=20;
switch(x)
{
case 10:
System.out.printl n(" lO");
case y:
System.out.println("20");
}}}
OUTPUT:
10
20
• Switch argument and case label can be expressions also, but case should be constant
expression.
EXAMPLE 4:
public class ExampleSwitch{
public static void main(String args[]H
int x=10;
switch(x+l)
{
case 10:
case 10+20:
case 10+20+30:
}}}
OUTPUT:
No output.
• Every case label should be within the range of switch argument type.
EXAMPLE 5:
public class ExampleSwitch{
public static void main(String args[]H
byte b=10;
switchfb)
{
case 10:
System.out.printl n(" lO");
case 100:
System.out.println(" 100");
case 1000:
System.out.println("lOOO");
}}}
OUTPUT:
Compile time error
D:\Java>javac ExampleSwitch.java
ExampleSwitch.java:l0: possible loss of precision
found : int

117
required: byte
case 1000:
• Duplicate case labels are not allowed.
EXAMPLE 6:
public class ExampleSwitch{
public static void main(String args[]H
int x=10;
switch(x)
{
case 97:
System.out.println("97");
case 99:
System.out.println("99");
case 'a':
System.out.println(" 100");
}}}
OUTPUT:
Compile time error.
D:\Java>javac ExampleSwitch.java
ExampleSwitch.java:10: duplicate case label
case 'a':
CASE SUMMARY:
DIAGRAM:
-, 1.should be compile time constant.
/

-,
/ 2.Expression also allowed but should be
compile time constant expression.
case label
"-
/ 3.value should be with in the range of
switch argument type.
<,
/ 4.duplicate case label are not allowed.

FALL-THROUGH INSIDE THE SWITCH:


• Within the switch statement if any case is matched from that case onwards all
statements will be executed until end of the switch (or) break. This is call "fall-through"
inside the switch.
EXAMPLE 7:
public class ExampleSwitch{
public static void main(String args[]H
int x=O;
switch(x)
{
case 0:

118
System.out.println("O");
case 1:
System.out.printl n(" 1");
break;
case 2:
System.out.println("2");
default:
System .out. pri ntl n(" defa uIt");
}}}
OUTPUT:
X=O x=1 x=3
o 1 default
1 default
DEFAULT CASE:
• Within the switch we can take the default anywhere, but at most once it is convention
to take default as last case.
EXAMPLE 8:
public class ExampleSwitch{
public static void main(String args[]H
int x=O;
switch(x)
{
default:
System. out. pri ntl n(" defa uIt");
case 0:
System.out.println("O");
break;
case 1:
System.out.printl n(" 1");
case 2:
System.out.println("2");
}}}
OUTPUT:
X=o x=1 x=3
o 1 default

2 o

ITERATIVE STATEMENTS:
While loop: if we don't know the no of iterations in advance then best loop is while loop:
EXAMPLE 1:
while(rs.next())
{
}

119
EXAMPLE 2:
while(e.hasMoreeIEmentsO)
{

EXAMPLE 3:
while(itr.hasNextO)
{

• The argument to the while statement should be Boolean type. If we are using any other
type we will get compile time error.
EXAMPLE 1:
public class ExampleWhile{
public static void main(String args[]H
while(l)
{
System.out.println("hello");
}}}
OUTPUT:
Compile time error.
D:\Java>javac ExampleWhile.java
ExampleWhile.java:3: incompatible types
found : int
required: boolean
while(l)
• Curly braces are optional and without curly braces we can take only one statement
which should not be declarative statement.
EXAMPLE 2:
public class ExampleWhile{
public static void main(String args[]H
while(true)
System.out.println("hello");
}}
OUTPUT:
Hello (infinite times).

120
EXAMPLE 3:
public class ExampleWhile{
public static void main(String args[]H
while(true);
}}
OUTPUT:
No output.
EXAMPLE 4:
public class ExampleWhile{
public static void main(String args[]H
while(true)
int x=10;
}}
OUTPUT:
Compile time error.
D:\Java>javac ExampleWhile.java
ExampleWhile.java:4: '.class' expected
int x=10;
ExampleWhile.java:4: not a statement
int x=10;
EXAMPLE 5:
public class ExampleWhile{
public static void main(String args[]H
while(true)
{
int x=10;
}}}
OUTPUT:
No output.
Unreachable statement in while:
EXAMPLE 6:
public class ExampleWhile{
public static void main(String args[]H
while(true)
{
System.out.println("hello");
}
System.out.printl n(" hi");

121
}}
OUTPUT:
Compile time error.
D:\Java>javac ExampleWhile.java
ExampleWhile.java:7: unreachable statement
System.out.printl n(" hi");
EXAMPLE 7:
public class ExampleWhile{
public static void main(String args[]H
while(false)
{
System.out.println("hello");
}
System.out.println("hi");
}}
OUTPUT:
D:\Java>javac ExampleWhile.java
ExampleWhile.java:4: unreachable statement

EXAMPLE 8:
public class ExampleWhile{
public static void main(String args[]H
int a=10,b=20;
while(a<b)
{
System.out.println("hello");
}
System.out.printl n(" hili);
}}
OUTPUT:
Hello (infinite times).
EXAMPLE 9:
public class ExampleWhile{
public static void main(String args[]H
final int a=10,b=20;
while(a<b)
{
System.out.println("hello");

122
System.out.printl n(" hili);
}}
OUTPUT:
Compile time error.
D:\Java>javac ExampleWhile.java
ExampleWhile.java:8: unreachable statement
System.out.printl n(" hili);
EXAMPLE 10:
public class ExampleWhile{
public static void main(String args[]H
final int a=10;
while(a<20)
{
System.out.println("hello");
}
System.out.println("hi");
}}
OUTPUT:
D:\Java>javac ExampleWhile.java
ExampleWhile.java:8: unreachable statement
System.out.println("hi");
Note:
• Every final variable will be replaced with the corresponding value by compiler.
• If any operation involves only constants then compiler is responsible to perform that
operation.
• If any operation involves at least one variable compiler won't perform that operation. At
runtime jvm is responsible to perform that operation.
EXAMPLE 11:
public class ExampleWhile{
public static void main(String args[]H
int a=10;
while(a<20)
{
System.out.println("hello");
}
System.out.printl n(" hili);
}}

123
OUTPUT:
Hello (infinite times).
Do-while:
• If we want to execute loop body at least once then we should go for do-while.
Syntax:
do
{

}while(b); --~)semicolon is the mandatory.

• Curly braces are optional.


• Without curly braces we can take only one statement between do and while and it
should not be declarative statement.
Example 1:
public class ExampleDoWhile{
public static void main(String args[]H
do
System.out.println("hello");
while(true);
}}
Output:
Hello (infinite times).
Example 2:
public class ExampleDoWhile{
public static void main(String args[]H
do;
while(true);
}}
Output:
Compile successful.
Example 3:
public class ExampleDoWhile{
public static void main(String args[]H
do
int x=10;
while(true);
}}

124
Output:
D:\Java>javac ExampleDoWhile.java
ExampleDoWhile.java:4: '.class' expected
int x=10;
ExampleDoWhile.java:4: not a statement
int x=10;
ExampleDoWhile.java:4: ')' expected
int x=10;
Example 4:
public class ExampleDoWhile{
public static void main(String args[]H
do

int x=10;
}while(true);
}}
Output:
Compile successful.
Example 5:
public class ExampleDoWhile{
public static void main(String args[]H
do while(true)
System.out.println("hello");
while(true);
}}
Output:
Hello (infinite times).
Rearrange the above example:
public class ExampleDoWhile{
public static void main(String args[]H
do
while(true)
System.out.println("hello");
while(true);
}}
Output:
Hello (infinite times).

125
Example 6:
public class ExampleDoWhile{
public static void main(String args[]H
do
while(true);
}}
Output:
Compile time error.
D:\Java>javac ExampleDoWhile.java
ExampleDoWhile.java:4: while expected
while(true);
ExampleDoWhile.java:5: illegal start of expression

Unreachable statement in do while:


Example 7:
public class ExampleDoWhile{
public static void main(String args[]H
do

System.out.println("hello");

while(true);
System.out.println("hi");
}}
Output:
Compile time error.
D:\Java>javac ExampleDoWhile.java
ExampleDoWhile.java:8: unreachable statement
System.out.println("hi");
Example 8:
public class ExampleDoWhile{
public static void main(String args[]H
do

System.out.println("hello");
}
while(false);
System.out.printl n(" hili);

126
}}
Output:
Hello
Hi
Example 9:
public class ExampleDoWhile{
public static void main(String args[]H
int a=10,b=20;
do

System.out.println("hello");
}
while(a<b);
System.out.println("hi");
}}
Output:
Hello (infinite times).
Example 10:
public class ExampleDoWhile{
public static void main(String args[]H
int a=10,b=20;
do

System.out.println("hello");
}
while(a>b);
System.out.println("hi");
}}
Output:
Hello
Hi
Example 11:
public class ExampleDoWhile{
public static void main(String args[]H
final int a=10,b=20;
do

System.out.println("hello");

127
while(a<b);
System.out.println("hi");
}}
Output:
Compile time error.
D:\Java>javac ExampleDoWhile.java
ExampleDoWhile.java:9: unreachable statement
System.out.println("hi");
Example 12:
public class ExampleDoWhile{
public static void main(String args[]H
final int a=10,b=20;
do

System.out.println("hello");
}
while(a>b);
System.out.printl n(" hi");
}}
Output:
D:\Java>javac ExampleDoWhile.java
D:\Java>java ExampleDoWhile
Hello
Hi
For Loop:
• This is the most commonly used loop and best suitable if we know the no of iterations in
advance.
Syntax:

f or (.. Q)
'1' . di . 21 ® ®..
100ti izationsection.con mona expresstonnncrernent
/@(?))
decrement

:OdY®~
®~@~------

1) Initilizationsection:
• This section will be executed only once.
• Here usually we can declare loop variables and we will perform initialization.

128
• We can declare multiple variables but should be of the same type and we can't declare
different type of variables.
Example:
1) Int i=O,j=O;valid
2) Int i=O,Boolean b=true; invalid
3) Int i=O,int j=O; invalid
• In initialization section we can take any valid java statement including "s.o.p" also.
Example 1:
public class ExampleFor{
public static void main(String args[]H
int i=O;
for(System.out.println("hello u r sleeping");i<3;i++H
System.out.println("no boss, u only sleeping");
}}}
Output:
D:\Java>javac ExampleFor.java
D:\Java>java ExampleFor
Hello u r sleeping
No boss, u only sleeping
No boss, u only sleeping
No boss, u only sleeping
2) Conditional check:
• We can take any java expression but should be of the type Boolean.
• Conditional expression is optional and if we are not taking any expression compiler will
place true.
3) Increment and decrement section:
• Here we can take any java statement including s.o.p also.
Example:
public class ExampleFor{
public static void main(String args[]H
int i=O;
for(System.out.println("hello");i<3;System.out.println("hi")H
i++;
}}}
Output:
D:\Java>javac ExampleFor.java
D:\Java>java ExampleFor
Hello

129
Hi
Hi
Hi
• AI13 parts of for loop are independent of each other and all optional.
Example:
public class ExampleFor{
public static void main(String args[]H
for(;;H
System.out.println("hello");
}}}
Output:
Hello (infinite times).
• Curly braces are optional and without curly braces we can take exactly one statement
and it should not be declarative statement.
Unreachable statement in for loop:
Example 1:
public class ExampleFor{
public static void main(String args[]H
for(int i=O;true;i++H
System.out.println("hello");
}
System.out.printl n(" hili);
}}
Output:
Compile time error.
D:\Java>javac ExampleFor.java
ExampleFor.java:6: unreachable statement
System.out.println("hi");
Example 2:
public class ExampleFor{
public static void main(String args[]H
for(int i=O;false;i++H
System.out.println("hello");
}
System.out.println("hi");
}}
Output:
Compile time error.

130
D:\Java>javac ExampleFor.java
ExampleFor.java:3: unreachable statement
for(int i=O;false;i++){
Example 3:
public class ExampleFor{
public static void main(String args[]){
for(int i=O;;i++){
System.out.println("hello");
}
System.out.pri ntln (" hi");
}}
Output:
Compile time error.
D:\Java>javac ExampleFor.java
ExampleFor.java:6: unreachable statement
System.out.println("hi");
Example 4:
public class ExampleFor{
public static void main(String args[]){
int a=10,b=20;
for(int i=O;a<b;i++){
System.out.println("hello");
}
System.out.printl n(" hili);
}}
Output:
Hello (infinite times).
Example 5:
public class ExampleFor{
public static void main(String args[]){
final int a=10,b=20;
for(int i=O;a<b;i++){
System.out.println("hello");
}
System.out.println("hi");
}}
Output:
D:\Java>javac ExampleFor.java

131
ExampleFor.java:7: unreachable statement
System.out.printl n(" hili);
For each:
• For each Introduced in 1.5version.
• Best suitable to retrieve the elements of arrays and collections.
Example 1: Write code to print the elements of single dimensional array by normal for loop and
enhanced for loop.
Example:

Iint[] a={lO,20,30,40,50}; I

normal for loop-,l! \nhanced for loop


public class ExampleFor public classExampleFor
{ {
public static void main(String args[]}{ public static void main(String
int[] a={lO,20,30,40,50}; args[]){
for(int i=O;i<a.length;i++}{ int[] a={lO,20,30,40,50};
System.out.println(a[i); for(int x:a){
}}} System.out.println(x);
}}}

Output:
D:\Java>javac ExampleFor.java
D:\Java>java ExampleFor
10
20
30
40
50
Example 2: Write code to print the elements of 2 dimensional arrays by using normal for loop and
enhanced for loop.

I int[] [] a={{lO,20,30},{40,50}}; I

normal for loop


public class ExampleFor{
public static void main(String args[]}{
I \ enhanced for loop
public class ExampleFor{
public static void main(String args[]}{
int[][) a={{lO,20,30},{40,50}}; int[][) a={{lO,20,30},{40,50}};
for(int[) x:a}{ for(int i=O;i<a.length;i++}{
for(int y:x}{ for(int j=O;j<a[i).length;j++){
System.out.println(y); System.out.println(a[i] [j);
}}}} nn
Example 3: Write equivalent code by For Each loop for the following for loop.
public class ExampleFor{
public static void main(String args[]){

132
for(int i=O;i<lO;i++)

System.out.println("hello");
}}}
Output:
D:\Java>javac ExampleForl.java
D:\Java>java ExampleForl
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
• We can't write equivalent for each loop.
• For each loop is the more convenient loop to retrieve the elements of arrays and collections, but
its main limitation is it is not a general purpose loop.
Transfer statements:
Break statement:
• We can use break statement in the following cases.
1) Inside switch to stop fall-through.
2) Inside loops to break the loop based on some condition.
3) Inside label blocks to break block execution based on some condition.
Example 1:
class Test{
public static void main(String args[]H
int x=10;
11:
{
System.out.println("hello");
if(x==10)
break 11;
System.out.println("hi");
}
System.out.println("end");
}}

133
Output:
D:\Java>javac Test.java
D:\Java>java Test
Hello
End
• These are the only places where we can use break statement. If we are using anywhere
else we will get compile time error.
Example:
class Test{
public static void main(String args[]H
int x=10;
if(x==10)
break;
System.out.println("hello");
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: break outside switch or loop
break;
Continue statement:
• We can use continue statement to skip current iteration and continue for the next
iteration.
Exarnole:

class Test{
public static void main(String args[]){
int x=2;
for(int i=0;i<10;i++){
if(i%~==00 0%2=0
continue: 2/0=infinity
System.out.println(i);
}}}
Output:
D:\Java>javacTest.java
D:\Java>javaTest
1
3
5
7
9

134
• We can use continue only inside loops if we are using anywhere else we will get compile
time error saying "continue outside of loop".
Example:
class Test

public static void main(String args[]H


int x=10;
if(x==10);
continue;
System.out.println("hello");
}
}
Output:
Compile time error.
D:\Enum>javac Test.java
Test.java:6: continue outside of loop
continue;
labeled break and continue statements:
• In the nested loops to break (or) continue a particular loop we should go for labeled
break and continue statements.
Syntax:
11:
for(;;){

12:
for(;;){
...............
...............
13:
for(;;){

break 11;
break 12;

.~!.7.~.~.~.~:
..
................
( }

}
Example:
class Test

135
public static void main(String args[]){
11:
for(int i=0;i<3;i++)
{
for(int j=0;j<3 ;j++)
{
if(i==j)
break;
System.out.println(i+" "+j);
}}}}
Break:
1 0
2 0
2 1
Break 11:
No output.
Continue:
0 1
0 2
1 0
1 2
2 0
2 1
Continue 11:
1 0
2 0
2 1
Do-while vs continue (The most dangerous combination):
class Test

public static void main(String args[)}{


int x=O;
do
{
++x; X
System.out. rintln(x);
if(++x<S)
continue·
++x;
System.out.println(x);
hile +x<10);

136
Output:
1
4
6
8
10
• Compiler won't check unreachability in the case of if-else it will check only in loops.
Example 1:
class Test

public static void main(String args[]H


while(true)
{
System.out.println("hello");
}
System.out.printl n(" hili);
}

Output:
Compile time error.
D:\Enum>javac Test.java
Test.java:8: unreachable statement
System.out.printl n(" hili);
Example 2:
class Test

public static void main(String args[]H


if(true)
{
System.out.pri ntln (" hello ");
}
else

System.out.printl n(" hili);


}}}
Output:
Hello

137
Exception Handling
1. Introduction
2. Runtime stack mechanism
3. Default exception handling in java
4. Exception hierarchy
5. Customized exception handling by try catch
6. Control flow in try catch
7. Methods to print exception information
8. Try with multiple catch blocks
9. Finally
10. Difference between final, finally, finalize
11. Control flow in try catch finally
12. Control flow in nested try catch finally
13. Various possible combinations of try catch finally
14. throw keyword
15. throws keyword
16. Exception handling keywords summary
17. Various possible compile time errors in exception handling
18. Customized exceptions
19. Top-10 exceptions
Exception: An unwanted unexpected event that disturbs normal flow of the program is called
exception.
Example:
SleepingException
TyrePunchuredException
FileNotFoundException .....etc
• It is highly recommended to handle exceptions. The main objective of exception
handling is graceful (normal) termination of the program.
What is the meaning of exception handling?
• Exception handling doesn't mean repairing an exception. We have to define alternative
way to continue rest of the program normally this way of "defining alternative is nothing
but exception handling".
Example: Suppose our programming requirement is to read data from London file at runtime if
London file is not available our program should not be terminated abnormally. We have to
provide a local file to continue rest of the program normally. This way of defining alternative is
nothing but exception handling.

138
Example:
try
{
read data from london file

catch(FileNotFoundException e)
{
use local file and continue rest of the program normally
}
}

Runtime stack mechanism: For every thread JVM will create a separate stack all method calls
performed by the thread will be stored in that stack. Each entry in the stack is called "one
activation record" (or) "stack frame". After completing every method call JVM removes the
corresponding entry from the stack. After completing all method calls JVM destroys the empty
stack and terminates the program normally.
Example:
class Test

public static void main(String[] args){


doStuff();
}
public static void doStuff(){
doMoreStuff();
}
public static void doMoreStuff(){
System.out.println("Hello");
}}
Output:
Hello

U
Diagram:

UW e::>
main ;
e::>
doStuff()j
main()j
¢
doMorestuff()j
~oStuff()j
main()j
e::> oStuff()j
main()j
e::>
mainf]:

I destroyed by jvml(
e::>

139
Default exception handling in java:
1) If an exception raised inside any method then the method is responsible to create
Exception object with the following information.
1) Name of the exception.
2) Description of the exception.
3) Location of the exception.
2) After creating that Exception object the method handovers that object to the JVM.
3) JVM checks whether the method contains any exception handling code or not. If
method won't contain any handling code then JVM terminates that method abnormally
and removes corresponding entry form the stack.
4) JVM identifies the caller method and checks whether the caller method contain any
handling code or not. If the caller method also does not contain handling code then JVM
terminates that caller also abnormally and the removes corresponding entry from the
stack.
S) This process will be continued until main() method and if the main() method also
doesn't contain any exception handling code then JVM terminates main() method and
removes corresponding entry from the stack.
6) Then JVM handovers the responsibility of exception handling to the default exception
handler.
7) Default exception handler just print exception information to the console in the
following formats and terminates the program abnormally.
Name of exception: description
Location of exception (stack trace)
Example:
class Test

public static void main(String[] args){


doStuff();
}
public static void doStuff(){
doMoreStuff();
}
public static void doMoreStuff(){
System.out.println(10jO);
}}
Output:
Runtime error
Exception in thread "main" java.lang.ArithmeticException: j by zero

140
at Test.doMoreStuff(Test.java:l0)
at Test.doStuff(Test.java:7)
at Test.main(Test.java:4)
Diagram:

doMorestuffOi
I

doStuffOi
rnainf]:
Exception hierarchy:
Object

rhr~wable
Throwable acts as a root for exception hierarchy.
Throwable class contains the following two child classes.

Throwable

I
J:
Exception
\1,
Error
Exception: Most of the cases exceptions are caused by our program and these are recoverable.
Error: Most of the cases errors are not caused by our program these are due to lack of system
resources and these are non recoverable.
Checked Vs Unchecked Exceptions:
• The exceptions which are checked by the compiler for smooth execution of the program
at runtime are called checked exceptions.
1) HallTicketMissingException
2) PenNotWorkingException
3) FileNotFoundException
• The exceptions which are not checked by the compiler are called unchecked exceptions.
1) BombBlaustException
2) ArithmeticException
3) NullPointerException
Note: RuntimeException and its child classes, Error and its child classes are unchecked and all
the remaining are considered as checked exceptions.
Note: Whether exception is checked or unchecked compulsory it should occur at runtime only
there is no chance of occurring any exception at compile time.

141
Partially checked Vs fully checked:
• A checked exception is said to be fully checked if and only if all its child classes are also
checked.
Example:
1) IOException
2) Interrupted Exception
• A checked exception is said to be partially checked if and only if some of its child classes
are unchecked.
Example: Exception
• The only partially checked exceptions available in java are:
1. Throwable.
2. Exception.
Which of the following are checked?
1. RuntimeException-----unchecked
2. Error-----unchecked
3. IOException-----fully checked
4. Exception-----partially checked
5. InterruptedException-----fully checked
6. Throwable------partially checked
Diagram:
Object
1)
Throwable
I
I 1
Aj~
Exception Error

It----------r-J/------r-J/-----,l········
RuntimeException 10ExceptionSQLException ServletException . . ~AssertlonError
. ~ VlrtualMachm rror
ArlthmetlcExceptlon EOFException ~-
1---NuIiPointerException FileNotFoundExcept~on VerifyError
---1 ndex0 utOfBoundE·
5 xcepnon
InterruptedlOExceptlon
1-

l-ArraYlndexOutOfBoundSException OutOfMemoryError StackOverflowError


L__StringlndexOutOfBoundSException
1----lllegaIArgumentExceptlon
'---NumberFormatException
1---ClassCastException
I----lllegaIStateException

142
Customized exception handling by try catch:
• It is highly recommended to handle exceptions.
• In our program the code which may cause an exception is called risky code we have to
place risky code inside try block and the corresponding handling code inside catch block.
Example:
try
{
risky code
}
catch(Exception e)
{
handling code
}

Without try catch With try catch


class Test class Test{
{ public static void main(String[] args){
public static void main(String[] args){ Svstem.out.printlru'tstaternent l"};
System.out.println("statementl"); try{
System.out.println(10jO); System.out.println(10jO);
System .out. pri ntl n(" statement3"); }
} catch(ArithmeticException e){
} System.out.println(10/2);
Abnormal termination. }
Svstern.out.printlnt'tstaternent.S"):
}}
Output:
statementl
5
statement3
Normal termination.
Control flow in try catch:
Case 1: There is no exception.
1, 2, 3, 5 normal termination.
Case 2: if an exception raised at statement 2 and corresponding catch block matched 1, 4, 5
normal termination.
Case 3: if an exception raised at statement 2 but the corresponding catch block not matched 1
followed by abnormal termination.
Case 4: if an exception raised at statement 4 or statement 5 then it's always abnormal
termination of the program.

143
1. Within the try block if anywhere an exception raised then rest of the try block won't
be executed even though we handled that exception. Hence we have to place/take
only risk code inside try and length of the try block should be as less as possible.
2. If any statement which raises an exception and it is not part of any try block then it is
always abnormal termination of the program.
3. There may be a chance of raising an exception inside catch and finally blocks also in
addition to try block.
Various methods to print exception information:
• Throwable class defines the following methods to print exception information to the
console.
printStackTraceO: This method prints exception information in the following format.
Name of the exception: description of exception
Stack trace
toStringO: This method prints exception information in the following format.
I Name of the exception: description of exception
getMessageO: This method returns only description of the exception.
I Description.
Example:
class Test

public static void main(String[] args) java.lang.ArithmeticException: / by zero


try at Test.main(Test.java:6)
{
System.out.println(lO/O);
}
catch(ArithmeticException
{
e.printStackTraceO;
System.out.println(e);
System.out.println(e.getMessageO)·
}}}

Note: Default exception handler internally uses printStackTrace() method to print exception
information to the console.
Try with multiple catch blocks: The way of handling an exception is varied from exception to
exception hence for every exception raise a separate catch block is required that is try with
multiple catch blocks is possible and recommended to use.
Example:

144
catch(FileNotFoundException e)
catch(Exception e) {
{ use local file
default handler
} catch(ArithmeticException e)
{
• This approach is not recommended
perform these Arithmetic operations
because for any type of Exception
}
we are using the same catch block.
catch(SQLException e)
{
don't use oracle db, use mysql db
}
catch(Exception e)
{
default handler
}

• This approach is highly recommended


because for any exception raise we are
defining a separate catch block.
• If try with multiple catch blocks presents then order of catch blocks is very important it
should be from child to parent by mistake if we are taking from parent to child then we
will get Compile time error saying "exception xxx has already been caught".
Example:
class Test class Test

public static void main(String[] args) public static void main(String[] args)
{ {
try try
{ {
System.out.println(lOjO); System.out.println(lOjO);
} }
catch(Exception e) catch(ArithmeticException e)
{ {
e.printStackTraceO; e.printStackTraceO;
} }
catch (Arith meticException e) catch(Exception e)
{ {
e.printStackTraceO; e.printStackTraceO;
}}} }}}

145
Output: Output:
Compile time error. Compile successfully.
Test.java:13: exception
java.lang.ArithmeticException has already been
caught
catch (ArithmeticException e)
Finally block:
~ It is never recommended to take clean up code inside try block because there is no
guarantee for the execution of every statement inside a try.
~ It is never recommended to place clean up code inside catch block because if there is no
exception then catch block won't be executed.
~ We require some place to maintain clean up code which should be executed always
irrespective of whether exception raised or not raised and whether handled or not
handled such type of place is nothing but finally block.
~ Hence the main objective of finally block is to maintain cleanup code.
Example:
try
{
risky code
}
catch(x e)
{
handling code
}
finally
{
cleanup code
}
• The specialty of finally block is it will be executed always irrespective of whether the
exception raised or not raised and whether handled or not handled.
Example 1:
class Test

public static void main(String[] args)


{
try

System.out.println("try block executed");


}
catch (Arith meticException e)

146
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
}}}
Output:
Try block executed
Finally block executed
Example 2:
class Test

public static void main(String[] args)


{
try
{
System.out.println("try block executed");
System.out.println(lOjO);
}
catch (Arith meticException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
}}}
Output:
Try block executed
Catch block executed
Finally block executed
Example 3:
class Test

public static void main(String[] args)


{
try

147
System.out.println("try block executed");
System.out.println(lOjO);
}
catch(NullPointerException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
}}}
Output:
Try block executed
Finally block executed
Exception in thread "main" java.lang.ArithmeticException: j by zero
at Test.main(Test.java:8)
Return Vs Finally:
);:- Even though return present in try or catch blocks first finally will be executed and after
that only return statement will be considered that is finally block dominates return
statement.
Example:
class Test

public static void main(String[] args)


{
try
{
System.out.println("try block executed");
return;

catch(ArithmeticException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");

148
}}}
Output:
Try block executed
Finally block executed
);- If return statement present try catch and finally blocks then finally block return
statement will be considered.
Example:
class Test

public static void main(String[] args)

System.out.printl n(methodOneO);
}
public static int methodonefj]
try
{
System.out.println(lOjO);
return 777;

catch (Arith meticException e)

return 888;

finally{
return 999;
}}}
Output:
999
• There is only one situation where the finally block won't be executed is whenever we
are using System.exit(O) method.
Example:
class Test

public static void main(String[] args)


{
try
{
System.out.println("try");

149
System.exit(O);
}
catch (Arith meticException e)
{
System.out.println("catch block executed ");
}
finally
{
System.out.println("finally block executed");
}}}
Output:
Try
Difference between final, finally, and finalize:
Final:
• Final is the modifier applicable for class, methods and variables.
• If a class declared as the final then child class creation is not possible.
• If a method declared as the final then overriding of that method is not possible.
• If a variable declared as the final then reassignment is not possible.
Finally:
• It is the block always associated with try catch to maintain clean up code which should
be executed always irrespective of whether exception raised or not raised and whether
handled or not handled.
Finalize:
• It is a method which should be called by garbage collector always just before destroying
an object to perform cleanup activities.
Note:
• To maintain clean up code faunally block is recommended over finalizeO method
because we can't expert exact behavior of GC.
Control flow in try catch finally:
Example:
class Test

public static void main(String[] args){


try{
System.out.println("statementl");
System.out.println("statement2");
System.out.println("statement3");
}

150
catch (Exception e){
Svstem.out.printlntvstatementa"]:
}
finally
{
Svstem.out.printlnl'tstaternentfi"):
}
Svstem.out.printlnt'tstatemente"]:
}
}
Case 1: If there is no exception. 1, 2, 3, 5, 6 normal termination.
Case 2: if an exception raised at statement 2 and corresponding catch block matched. 1,4,5,6
normal terminations.
Case 3: if an exception raised at statement 2 and corresponding catch block is not matched. 1,5
abnormal termination.
Case 4: if an exception raised at statement 4 then it's always abnormal termination but before
the finally block will be executed.
Case 5: if an exception raised at statement 5 or statement 6 its always abnormal termination.
Control flow in nested try catch finally:
Example:
class Test

public static void main(String[] args){


try{
System.out.println("statementl");
Svstem.out.printlnt'tstaternent Z"]:
Svstem.out.printlnf'tstaternenfS"]:
try{
Svstern.out.printlnt'tstatementa"]:
System .out. pri ntl n( "stateme nt5");
Svstem.out.printlnt'Istaternentfi"):

catch(ArithmeticException e){
Svstern.out.printlnt'tstatement?"):
}
finally
{
Svstem.out.printlru'tstaternentd"):

151
}
System.out.println("statement9");
}
catch(Exception e)
{
System.out.println("statementlO");
}
finally
{
System.out.println("statementll");

System.out.println("statementl2");
}
}
Case 1: if there is no exception. 1, 2, 3, 4, 5, 6, 8,9, 11, 12 normal termination.
Case 2: if an exception raised at statement 2 and corresponding catch block matched
1,10,11,12 normal terminations.
Case 3: if an exception raised at statement 2 and corresponding catch block is not matched 1,
11 abnormal termination.
Case 4: if an exception raised at statement 5 and corresponding inner catch has matched 1, 2,
3,4, 7, 8, 9, 11, 12 normal termination.
Case 5: if an exception raised at statement 5 and inner catch has not matched but outer catch
block has matched. 1,2, 3, 4, 8, 10, 11, 12 normal termination.
Case 6: if an exception raised at statement 5 and both inner and outer catch blocks are not
matched. 1, 2, 3, 4, 8, 11 abnormal termination.
Case 7: if an exception raised at statement 7 and the corresponding catch block matched 1, 2,
3,.,.,.,8, 10, 11, 12 normal termination.
Case 8: if an exception raised at statement 7 and the corresponding catch block not matched 1,
2,3,.,.,.,8,11 abnormal terminations.
Case 9: if an exception raised at statement 8 and the corresponding catch block has matched 1,
2,3,.,.,.,., 10, 11,12 normal termination.
Case 10: if an exception raised at statement 8 and the corresponding catch block not matched
1, 2, 3,.,.,.,., 11 abnormal terminations.
Case 11: if an exception raised at statement 9 and corresponding catch block matched 1, 2,
3,.,.,.,.,8,10,11,12 normal termination.
Case 12: if an exception raised at statement 9 and corresponding catch block not matched 1, 2,
3,.,.,.,.,8, 11 abnormal termination.

152
Case 13: if an exception raised at statement 10 is always abnormal termination but before that
finally block 11 will be executed.
Case 14: if an exception raised at statement 11 or 12 is always abnormal termination.
Note: if we are not entering into the try block then the finally block won't be executed. Once
we entered into the try block without executing finally block we can't come out.
Example:
class Test

public static void main(String[] args){


try{
System.out.println(10jO);
}
catch (Arith meticException e)

System.out.println(10jO);
}
finally{
String s=null;
System. out. pri ntl n(s.1ength 0);
}}}
Note: Default exception handler can handle only one exception at a time and that is the most
recently raised exception.
Various possible combinations of try catch finally:
Example 1:
class Test1{
public static void main(String[] args){
try
{}
catch(ArithmeticException e)
{}
}}
Output:
Compile and running successfully.
Example 2:
class Test1{
public static void main(String[] args){
try
{}

153
catch (Arith meticException e)
{}
catch(NullPointerException e)
{}
}
}
Output:
Compile and running successfully.
Example 3:
class Testl{
public static void main(String[] args){
try
{}
catch (Arith meticException e)
{}
catch (Arith meticException e)
{}
}
}
Output:
Compile time error.
Test1.java:7: exception java.lang.ArithmeticException has already been caught
catch (ArithmeticException e)
Example 4:
class Testl{
public static void main(String[] args){
try
{}
}
}
Output:
Compile time error
Testl.java:3: 'try' without 'catch' or 'finally'
try
Example 5:
class Testl{
public static void main(String[] args){
catch(Exception e)

154
{}
}
}
Output:
Compile time error.
Testl.java:3: 'catch' without 'try'
catch(Exception e)
Example 6:
class Testl{
public static void main(String[] args){
try
{}
System.out.println("hello");
catch (Exception e)
{}
}
}
Output:
Compile time error.
Testl.java:3: 'try' without 'catch' or 'finally'
Try
Example 7:
class Testl{
public static void main(String[] args){
try
{}
catch (Exception e)
{}
finally
{}
}

Output:
Compile and running successfully.
Example 8:
class Testl{
public static void main(String[] args){
try

155
{}
finally
{}
}
}
Output:
Compile and running successfully.
Example 9:
class Testl{
public static void main(String[] args){
try
{}
finally
{}
finally
{}
}
}
Output:
Compile time error.
Test1.java:7: 'finally' without 'try'
Finally
Example 10:
class Testl{
public static void main(String[] args){
try
{}
catch(Exception e)
{}
System.out.println("hello");
finally
{}
}
}
Output:
Compile time error.
Testl.java:8: 'finally' without 'try'
Finally

156
Example 11:
class Testl{
public static void main(String[] args){
try
{}
finally
{}
catch(Exception e)
{}
}

Output:
Compile time error.
Testl.java:7: 'catch' without 'try'
catch(Exception e)
Example 12:
class Testl{
public static void main(String[] args){
finally
{}

Output:
Testl.java:3: 'finally' without 'try'
Finally
Example 13:
class Testl{
public static void main(String[] args){
try
{ try{}
catch(Exception e){}

catch(Exception e)
{}
}
}
Output:
Compile and running successfully.

157
Example 14:
class Testl{
public static void main(String[] args){
try
{}
catch(Exception e)
{
try{}
finally{}
}

Output:
Compile and running successfully.
Example 15:
class Testl{
public static void main(String[] args){
try
{}
catch(Exception e)

try{}
catch(Exception e){}
}
finally{
finally{}
}

Output:
Compile time error.
Testl.java:ll: 'finally' without 'try'
finally{}
Example 16:
class Testl{
public static void main(String[] args){
finally{}
try{ }

158
catch (Exception e){}
}
}
Output:
Compile time error.
Testl.java:3: 'finally' without 'try'
finally{}
Example 17:
class Testl{
public static void main(String[] args){
try{ }
catch(Exception e){}
finally
{
try{}
catch(Exception e){}
finally{}
}
}
}
Output:
Compile and running successfully.
Throw statement: Sometime we can create exception object explicitly and we can hand over to
the JVM manually by using throw keyword.
Example:
throw
\.1/
To handover our creatmg Arithmeticjxception
created exception object explicitly.
object to the jvm
manually.
• The result of following 2 programs is exactly same.
class Test class Test
{
public static void main(String[] args){ public static void main(String[] args){
System.out.println(lOjO); throw new ArithmeticException("j by zero");
}} }}
• In this case creation of
• In this case we are creating exception
Arith meticException object and

159
handover to the jvm will be performed object explicitly and handover to the
automatically by the mainO method. JVM manually.
Note: In general we can use throw keyword for customized exceptions but not for predefined
exceptions.
Case 1: throw e;
• If e refers null then we will get NullPointerException.
Example:
class Test3 class Test
{
static ArithmeticException e=new static ArithmeticException e;
ArithmeticException(); public static void main(String[] args){
public static void main(String[] args){ throwe;
throwe; }
} }
} Output:
Output: Exception in thread "main"
Runtime exception: Exception in thread java.lang.NuIIPointerException
"main" java.lang.ArithmeticException at Test3.main(Test3.java:5)
Case 2: After throw statement we can't take any statement directly otherwise we will get
compile time error saying unreachable statement.
Example:
class Test3 class Test3
{
public static void main(String[] args){ public static void main(String[] args){
System.out.println(lOjO); throw new ArithmeticException("j by zero");
System.out.println("hello"); System.out.println("hello");
} }
} }
Output: Output:
Runtime error: Exception in thread "main" Compile time error.
java.lang.ArithmeticException: / by zero Test3.java:5: unreachable statement
at Test3.main(Test3.java:4) System.out.println("hello");
Case 3: We can use throw keyword only for Throwable types otherwise we will get compile
time error saying incomputable types.
Example:
class Test3 class Test3 extends RuntimeException
{
public static void main(String[] args){ public static void main(String[] args){
throw new Testst): throw new Test30;
} }
}Output: }
Compile time error. Output:

160
Test3.java:4: incompatible types Runtime error: Exception in thread "main"
found : Test3 Test3
required: java.lang.Throwable at Test3.main(Test3.java:4)
throw new Test3();
Throws statement: in our program if there is any chance of raising checked exception
compulsory we should handle either by try catch or by throws keyword otherwise the code
won't compile.
Example:
class Test3

public static void main(String[] args){


Thread.sleep(SOOO);
}
}
• Unreported exception java.lang.lnterruptedException; must be caught or declared to be
thrown. We can handle this compile time error by using the following 2 ways.
Example'
By using try catch By using throws keyword
class Test3 • We can use throws keyword to
delicate the responsibility of
public static void main(String[] args){ exception handling to the caller
try{ method. Then caller method is
Thread.sleep(SOOO); responsible to handle that
} exception.
catch(lnterruptedException e){} class Test3
} {
} public static void main(String[]
Output: args)throws InterruptedException{
Compile and running successfully Thread.sleep(SOOO);
}
}
Output:
Compile and running successfully
• Hence the main objective of "throws" keyword is to delicate the responsibility of
exception handling to the caller method.
• "throws" keyword required only checked exceptions. Usage of throws for unchecked
exception there is no use.
• "throws" keyword required only to convenes complier. Usage of throws keyword
doesn't prevent abnormal termination of the program.

161
Example:
class Test

public static void main(String[] args)throws InterruptedException{


duStufft):
}
public static void dostuff'(lthrows InterruptedException{
dolvloteStufff}:
}
public static void doMoreStuffOthrows InterruptedException{
Thread.sleep(SOOO);
}
}
Output:
Compile and running successfully.
• In the above program if we are removing at least one throws keyword then the program
won't compile.
Case 1: we can use throws keyword only for Throwable types otherwise we will get compile
time error saying incompatible types.
Example:
class Test3{ class Test3 extends RuntimeException{
public static void main(String[] args)throws public static void main(String[] args)throws
Test3 Test3
{} {}
} }
Output: Output:
Compile time error Compile and running successfully.
Test3.java:2: incompatible types
found : Test3
required: java.lang.Throwable
public static void main(String[] args)throws
Test3
Case 2:
Example:
class Test3{ class Test3{
public static void main(String[] args){ public static void main(String[] args){
throw new ExceptionO; throw new Errort):
} }
} }
Output: Output:

162
Compile time error. Runtime error
Test3.java:3: unreported exception Exception in thread "main" java. lang. Error
java.lang.Exception; must be caught or at Test3.main(Test3.java:3)
declared to be thrown
Case 3:
• In our program if there is no chance of rising an exception then we can't right catch
block for that exception otherwise we will get compile time error saying exception XXX
is never thrown in body of corresponding try statement. But this rule is applicable only
for fully checked exception.
Examole'
classTest classTest classTest
{ { {
publicstatic void main(String[)args){ publicstaticvoid main(String[)args){ publicstaticvoid main(String[]args){
try{ try{ try{
System.out.println("hello")i System.out.println("hello")i System.out.println("hello");
} } }
catch(Exceptione) catch(ArithmetlcExceptione) catch(java.io.IOException
e)
{} output: {} output: {} output:
} hello } hello } compiletime error
~}__ ~p.a~rt~ia~l~ch~e~ck~e~d ~ul}~~~~ ~~}~f~Lull~v'c~hecl:~ked~ ~

classTest classTest
{ {
public static void main(String[] args){ public static void main(String[] args){
try{ try{
System.out.println("hello"); System.out.println("hello");
} }
catch(lnterruptedException e) catch(Error e)
{} output: {} output:
} compile time error } compile successfully
~}~F~uuullllv~~chlle~cke~d ~~}~u~n~c~h~ec~k~e~d ~

Exception handling keywords summary:


1) try: To maintain risky code.
2) catch: To maintain handling code.
3) finally: To maintain cleanup code.
4) throw: To handover our created exception object to the JVM manually.
5) throws: To delegate responsibility of exception handling to the caller method.
Various possible compile time errors in exception handling:
1) Exception XXX has already been caught.
2) Unreported exception XXX must be caught or declared to be thrown.
3) Exception XXX is never thrown in body of corresponding try statement.
4) Try without catch or finally.
5) Catch without try.
6) Finally without try.

163
7) Incompatible types.
• Found:test
• Requried:java.lang.Throwable;
8) Unreachable statement.
Customized Exceptions (User defined Exceptions):
• Sometimes we can create our own exception to meet our programming requirements.
Such type of exceptions are called customized exceptions (user defined exceptions).
Example:
1) InSufficientFundsException
2) TooYoungException
3) TooOldException
Program:
class TooYoungException extends RuntimeException

TooYoungException(String s)
{
super(s);
}
}
class TooOldException extends RuntimeException

TooOldException(String s)
{
super(s);
}
}
class Customized Exception Demo

public static void main(String[] args){


int age=lnteger.parselnt(args[O]);
if(age>60)
{
throw new TooYoungException("please wait some more time .... u will get best match");

else if(age<18)
{
throw new TooOldException("u r age already crossed .... no chance of getting married");

164
else

System.out.println("you will get match details soon bye-mail");


}}}
Output:
1) E:\scjp>java Custom ized Exception Demo 61
Exception in thread "main" TooYoungException: please wait some more time .... u will get
best match
at Custom ized Exception Demo. m ain(Custom ized Exception Demo .java :21)
2) E:\scjp>java CustomizedExceptionDemo 27
You will get match details soon bye-mail
3) E:\scjp>java CustomizedExceptionDemo 9
Exception in thread "main" TooOldException: u r age already crossed ....no chance of getting
married
at Customized ExceptionDemo.ma in(Customized Exception Demo.java :25)
Note: It is highly recommended to maintain our customized exceptions as unchecked by
extending RuntimeException.
• We can catch any Throwable type including Errors also.
Example:
try

{} valid
catch(Error e)
{}

Top-10 Exceptions:
• Exceptions are divided into two types. They are:
1) JVM Exceptions:
2) Programatic exceptions:
JVM Exceptions:
• The exceptions which are raised automatically by the jvm whenever a particular event
occurs.
Example:
1) ArraylndexOutOfBoundsException(AIOOBE)
2) NuliPointerException (NPE).
Programatic Exceptions:
• The exceptions which are raised explicitly by the programmer (or) by the API developer
are called programatic exceptions.
Example:
1) IIlegaIArgumentException(IAE).

165
1) Arrayl ndexOutOfBoundsException:
• It is the child class of RuntimeException and hence it is unchecked. Raised automatically
by the JVM whenever we are trying to access array element with out of range index.
Example:
class Test{
public static void main(String[] args){
int[] x=new int[lO];
System.out.println(x[O]);/ /valid
System.out.println(x[lOO] );/ / AIOOBE
System.out.println(x[-lOO]);/ / AIOOBE
}
}
2) NuliPointerException:
• It is the child class of RuntimeException and hence it is unchecked. Raised automatically
by the JVM, whenever we are trying to call any method on null.
Example:
class Test{
public static void main(String[] args){
String s=null;
System.out.println(s.length());~R.E: NullPointerException
}
}
3) StackOverFlowError:
• It is the child class of Error and hence it is unchecked. Whenever we are trying to invoke
recursive method call JVM will raise StackOverFloeError automatically.
Example:
class Test

public static void methodOne()


{
methodTwot):
}
public static void methodTwo()
{
methodonet):
}
public static void main(String[] args)
{

166
methodOne();
}
}
Output:
Run time error: StackOverFloeError
4) NoClassDefFound:
• It is the child class of Error and hence it is unchecked. JVM will raise this error
automatically whenever it is unable to find required .class file.
Example: java Test
• If Test.class is not available. Then we will get NoClassDefFound error.
5) ClassCastException:
• It is the child class of RuntimeException and hence it is unchecked. Raised automatically
by the JVM whenever we are trying to typecast parent object to child type.
Example:
class Test class Test class Test
{ {
public static void main(String[] args) public static void main(String[] args) public static void main(String[] args)
{ { {
String s=new String("bhaskar")j Object o=new ObjectOj Object o=new String("bhaskar")j
Object o=(Object)sj String s=(String)oj String s=(String)oj
} output: } output: } output:
} valid } Runtime exceDtion:ClassCastExceD ion} ~~WU v::Iliri ~

6) ExceptionlnlnitializerError:
• It is the child class of Error and it is unchecked. Raised automatically by the JVM, if any
exception occurs while performing static variable initialization and static block
execution.
Example 1:
class Test{
static int i=10/0;

Output:
Runtime exception:
• Exception in thread "main" java.lang.ExceptionlnlnitializerError
Example 2:
class Test{
static {
String s=null;
System .out. pri ntl n(s.1ength ());
}}

167
Output:
Runtime exception: Exception in thread "main" java.lang.ExceptionlnlnitializerError
7) IlIegalArgumentException:
• It is the child class of RuntimeException and hence it is unchecked. Raised explicitly by
the programmer (or) by the API developer to indicate that a method has been invoked
with inappropriate argument.
Example:
class Test{
public static void main(String[] args){
Thread t=new Thread();
t.setPriority(lO);~valid
t.setPriority(lOO);~invalid
}}
Output:
Runtime exception
• Exception in thread "main" java.lang.lllegaIArgumentException.
8) NumberFormatException:
• It is the child class of IllegalArgumentException and hence is unchecked. Raised explicitly
by the programmer or by the API developer to indicate that we are attempting to
convert string to the number. But the string is not properly formatted.
Example:
class Test{
public static void main(String[] args){
int i=lnteger.parselnt("lO");
int j=lnteger.parselnt("ten");
}}
Output:
Runtime Exception
• Exception in thread "main" java.lang.NumberFormatException: For input string: "ten"
9) IlIegalStateException:
• It is the child class of RuntimeException and hence it is unchecked. Raised explicitly by
the programmer or by the API developer to indicate that a method has been invoked at
inappropriate time.
Example:
• Once session expires we can't call any method on the session object otherwise we will
get IllegalStateException
HttpSession session=req.getSessionO;
System .out. pri ntl n(session .get Id ());

168
session.invalidatef):
System.out.println(session.getld());~illgalstateException
10) AssertionError:
• It is the child class of Error and hence it is unchecked. Raised explicitly by the
programmer or by API developer to indicate that Assert statement fails.
Example:
assert(false);
Exception/Error Raised by
1) AIOOBE
2) NPE(NuIIPointerException)
3) StackOverFlowError Raised automatically by JVM(JVM Exceptions)
?
4) NoClassDefFoundError
5) CCE(ClassCastException)
6) Exception In InitializerError
7) IAE(lIlegaIArgumentException))
8) NFE(NumberFormatException) Raised explicitly either by programmer or by
9) ISE(lllegaIStateException) API developer (Programatic Exceptions).
10) AE(AssertionError)

169
OOPS
1) Data Hiding
2) Abstraction
3) Encapsulation
4) Tightly Encapsulated Class
5) IS-A Relationship
6) HAS-A Relationship
7) Method Signature
8) Overloading
9) Overriding
10) Method Hiding
11) Static Control Flow
12) Instance Control Flow
13) Constructors
14) Coupling
15) Cohesion
16) Object Type Casting
Data Hiding:
• Our internal data should not go out directly that is outside person can't access our
internal data directly.
• By using private modifier we can implement data hiding.
Example:
class Account

private double balance;


...................... ,
...................... ,

• The main advantage of data hiding is security.


Note: recommended modifier for data members is private.
Abstraction:
• Hide internal implementation and just highlight the set of services, is called abstraction.
• By using abstract classes and interfaces we can implement abstraction.
Example:
• By using ATM GUI screen bank people are highlighting the set of services what they are
offering without highlighting internal implementation.
• The main advantages of Abstraction are:

170
1) We can achieve security as we are not highlighting our internal implementation.
2) Enhancement will become very easy because without effecting end user we can able to
perform any type of changes in our internal system.
3) It provides more flexibility to the end user to use system very easily.
4) It improves maintainability of the application.
Encapsulation:
• It is the process of Encapsulating data and corresponding methods into a single module.
• If any java class follows data hiding and abstraction such type of class is said to be
encapsulated class.
Encapsulation=Datahiding+Abstraction
Example:

class Account
welcome to VBR Bank {
private double balance:
"> public double getBalanceO
I getBalance
I {
!!validate user
return balance:
}
_...::rpublic void setBalance(double balance)
L---- {
I setBalance
~ !!validate user
this.balanceebalance:
}
GUI
}

• In encapsulated class we have to maintain getter and setter methods for every data
member.
• The main advantages of encapsulation are:
1) We can achieve security.
2) Enhancement will become very easy.
3) It improves maintainability of the application.
4) It provides flexibility to the user to use system very easily.
• The main disadvantage of encapsulation is it increases length of the code and slows
down execution.
Tightly encapsulated class:
• A class is said to be tightly encapsulated if and only if every variable of that class
declared as private whether the variable has getter and setter methods are not and
whether these methods declared as public or not not required to check.
Example:
class Account

171
private double balance;
public double getBalanceO
{
return balance;

Which of the following classes are tightly encapsulated?


class A
{
private int x=10j (valid)
}
class B extends A
{
int y=20j(invalid)
}
class C extends A
{
private int z=30j (valid)
}

Which of the following classes are tightly encapsulated?


class A

int x=10;

class B extends A

private int y=20;

class C extends B

private int z=30;

Note: if the parent class is not tightly encapsulated then no child class is tightly encapsulated.
IS-A Relationship(inheritance):
1) Also known as inheritance.
2) By using extends keywords we can implement IS-A relationship.
3) The main advantage of IS-A relationship is reusability.
Example:
class Parent

public void methodOne()

172
{}

class Child extends Parent

public void methodTwo()


{}

classTest
{
public static void main(String[] args)
{
Parent p=new ParentOi C.E:cannot find symbol
p.methodOneOi symbol : method methodTwoO
p.methodTwoOi-------;;:~ location: class Parent
Child cenaw ChildOi
c.methodOneOi
c.methodTwoOi
Parent pl=new ChildO'
pt.methcdonel): C.E:incompatible types
p1.methodTwoOi found : Parent
Child cl=new Parentl]: required: Child
}

Conclusion:
1) Whatever the parent has by default available to the child but whatever the child has by
default not available to the parent. Hence on the child reference we can call both parent
and child class methods. But on the parent reference we can call only methods available
in the parent class and we can't call child specific methods.
2) Parent class reference can be used to hold child class object but by using that reference
we can call only methods available in parent class and child specific methods we can't
call.
3) Child class reference cannot be used to hold parent class object.
Example:
• The common methods which are required for housing loan, vehicle loan, personal loan
and education loan we can define into a separate class in parent class loan. So that
automatically these methods are available to every child loan class.
Example:
class Loan

/ /common methods which are required for any type of loan.

class HousingLoan extends Loan

173
/ /Housing loan specific methods.

class EducationLoan extends Loan

/ /Education Loan specific methods.

• For all java classes the most commonly required functionality is define inside object
class hence object class acts as a root for all java classes.
• For all java exceptions and errors the most common required functionality defines
inside Throwable class hence Throwable class acts as a root for exception hierarchy.
Diagram:
Object

N"r·'
-:
Throwable
strln

I I I I I
»:
Exception Error
I
Byte short Integer Long Float Double

Multiple inheritance:
• Having more than one Parent class at the same level is called multiple inheritance.
Example:
Parentl Parent2

Child

• Any class can extends only one class at a time and can't extends more than one class
simultaneously hence java won't provide support for multiple inheritance.
Example:

class AO
class BO (invalid)
class C extends A,B
o
• But an interface can extends any no. Of interfaces at a time hence java provides support
for multiple inheritance through interfaces.

174
Example:

interface AO
interface BO
interface C extends A,BO

• If our class doesn't extends any other class then only our class is the direct child class of
object.
Example:
class AU Object

t
®
• If our class extends any other class then our class is not direct child class of object.
Example 1:
class BO Object
class A extends BO
t
®
l' Multilevel inheritance

®.
(valid)
Example 2:
Object B

\/
(invalid)
Why java won't provide support for multiple inheritance?
• There may be a chance of raising ambiguity problems.
Example:
Parent1~ methodOneO Parent2~ methodOneO

\ c.methodonel):
Why ambiguity problem won't be there in interfaces?
"> Ambiguity problem.

• Interfaces having dummy declarations and they won't have implementations hence no
ambiguity problem.
Example:

175
interface interl interface inter2
{ {
public void methodonet): public void methodOneOi
} }

linterface inter3 extends interl,inter2U J


I
class Test implements inter3
{
public void methodOneO
{
System.out.println("This is methodOneO")i
}
}

Cyclic inheritance:
• Cyclic inheritance is not allowed in java.
Example 1:

class A extends BO Wnvalid)


class B extends AU fC.E:cyclic inheritance involving A

Example 2:

class A extends AU C.E > cyclic inheritance involving A


HAS-A relationship:
1) HAS-A relationship is also known as composition (or) aggregation.
2) There is no specific keyword to implement hAS-A relationship but mostly we can use
new operator.
3) The main advantage of HAS-A relationship is reusability.
Example:
class Engine

/ /engine specific functionality

class Car

Engine e=new EngineO;


//. ;
//. ;
//. ;

176
• Class Car HAS-A engine reference.
• HAS-A relationship increases dependency between the components and creates
maintains problems.
Composition vs Aggregation:
Composition:
• Without existing container object if there is no chance of existing contained objects then
the relationship between container object and contained object is called composition
which is a strong association.
Example:
• University consists of several departments whenever university object destroys
automatically all the department objects will be destroyed that is without existing
university object there is no chance of existing dependent object hence these are
strongly associated and this relationship is called composition.
Example:

o
departmentl
0
department2

o
department3

University

Aggregation:
• Without existing container object if there is a chance of existing contained objects such
type of relationship is called aggregation. In aggregation objects have weak association.
Example:
• Within a department there may be a chance of several professors will work whenever
we are closing department still there may be a chance of existing professor object
without existing department object the relationship between department and professor
is called aggregation where the objects having weak association.
Example:

--~--@---Contained object
---t--@
--+--@

Department

177
Method signature: In java method signature consists of name of the method followed by
argument types.
Example:

• In java return type is not part of the method signature.


• Compiler will use method signature while resolving method calls.
• Within the same class we can't take 2 methods with the same signature otherwise we
will get compile time error.
Example:
public void methodOneO
{}
public int methodOneO
{
return 10;

Output:
Compile time error
methodOneO is already defined in Test
Overloading:
• Two methods are said to be overload if and only if both having the same name but
different argument types.
• In 'C' language we can't take 2 methods with the same name and different types. If
there is a change in argument type compulsory we should go for new method name.
Example:
abs()---for int type
labs() for longtype
fabs() for float type

etc
• Lack of overloading in "C' increases complexity of the programming.
• But in java we can take multiple methods with the same name and different argument
types.

178
Example:
abs(int)
abs(long)
abs(float)

• Having the same name and different argument types is called method overloading.
• All these methods are considered as overloaded methods.
• Having overloading concept in java reduces complexity of the programming.
Example:
class Test

public void methodOneO


{
System.out.println("no-arg method");

public void methodOne(int i)


{
System.out.println("int-arg method"); overloaded methods

public void methodOne(double d)


{
System.out.println("double-arg method");

public static void main(String[] args)


{
Test t=new TestO;
t.methodOneO;/ /no-arg method
t.methodOne(lO);/ /int-arg method
t.methodOne(lO.5);/ /double-arg method

• In overloading compiler is responsible to perform method resolution(decision) based on


the reference type. Hence overloading is also considered as compile time
polymorphism(or) static Oearly biding.
Case 1: Automatic promotion in overloading.
• In overloading if compiler is unable to find the method with exact match we won't get
any compile time error immediately.

179
• 1st compiler promotes the argument to the next level and checks whether the matched
method is available or not if it is available then that method will be considered if it is not
available then compiler promotes the argument once again to the next level. This
process will be continued until all possible promotions still if the matched method is not
available then we will get compile time error. This process is called automatic promotion
in overloading.
• The following are various possible automatic promotions in overloading.
Diagram:
byte~short~

~ int~long~float~double
char........-- .
Example:
class Test

public void methodOne(int i)


{
System.out.println("int-arg method ");

public void methodOne(float f) overloaded methods


{
System.out.println("float-arg method");

public static void main(String[] args)


{
Test t=new Test();
/ /t.methodOne(,a');/ /int-arg method
/ /t.methodOne(101);/ /float-arg method
t.methodOne(10.5);/ /C.E:cannot find symbol

Case 2:
class Test

public void methodOne(String s)


{
System.out.println("String version");

public void methodOne(Object 0) Both methods are said to

180
be overloaded methods.

System.out.println("Object version ");

public static void main(String[] args)


{
Test t=new Test();
t.methodonetbhaskar'tk/ /String version
t.methodOne(new Object());/ /Object version
t.methodOne(null);/ /String version

• In overloading Child will always get high priority then Parent.


Case 3:
class Test

public void methodOne(String s)

System.out.println("String version");

public void methodOne(StringBuffer s)


{
System.out.println("Stri ngBuffer version ");

public static void main(String[] args)


{
Test t=new Test();
t.methodOne(ldurga");/ /String version
t. methodOne( new StringBuffer(lbhaskar"));/ /StringBuffer version

Output:
Object

A
String String Buffer

181
Case 4:
class Test

public void methodOne(int i,float f)


{
System.out.println("int-float method");

public void methodOne(float f,int i)


{
System.out.println("float-int method");

public static void main(String[] args)


{
Test t=new Test();
t.methodOne(lO,lO.5f);/ /int-float method
t.methodOne(lO.5f,lO);/ /float-int method
t.methodOne(lO,lO);//C.E:reference to methodOne is ambiguous, both method
methodOne(int,float) in Test and method methodOne(float,int) in Test match
t.methodOne(lO.5f,lO.5f);/ /C.E:cannot find symbol

Case 5:
class Test

public void methodOne(int i)


{
System.out.println("general method");

public void methodOne(int ...i)


{
System.out.println("var-arg method");

public static void main(String[] args)


{
Test t=new Test();
t.methodOne();/ /var-arg method
t.methodOne(lO,20);/ /var-arg method
t.methodOne(lO);/ /general method

182
• In general var-arg method will get less priority that is if no other method matched then
only var-arg method will get chance for execution it is almost same as default case
inside switch.
Case 6:
class Animal{}
class Monkey extends Animal{}
class Test

public void methodOne(Animal a)


{
System.out.println("Animal version");

public void methodOne(Monkey m)


{
System.out.println("Monkey version");

public static void main(String[] args)


{
Test t=new Test();
Animal a=new Animal();
t.methodOne(a);/ / Animal version
Monkey m=new Monkey();
t.methodOne(m);/ /Monkey version
Animal al=new Monkey();
t.methodOne(al);/ / Animal version

• In overloading method resolution is always based on reference type and runtime object
won't play any role in overloading.
Overriding:
• Whatever the Parent has by default available to the Child through inheritance, if the
Child is not satisfied with Parent class method implementation then Child is allow to
redefine that Parent class method in Child class in its own way this process is called
overriding.
• The Parent class method which is overridden is called overridden method.
• The Child class method which is overriding is called overriding method.

183
Example 1:
class Parent

public void property()


{
System.out.println("cash+land+gold");

public void marry()


{
System.out.println("subbalakshmi"); overridden method

class Child extends Parent overriding

public void marry()


{
System.out.println("Trisha/nayanatara/anushka"); overriding method

class Test

public static void main(String[] args)


{
Parent p=new Parent();
p.marry();/ /subbalakshmi(parent method)
Child c=new Child();
c.marry();/ /Trisha/nayanatara/anushka( chi Id method)
Parent pl=new Child();
pl.marry();/ /Trisha/nayanatara/anushka( child method)

• In overriding method resolution is always takes care by JVM based on runtime object
hence overriding is also considered as runtime polymorphism or dynamic polymorphism
or late binding.
• The process of overriding method resolution is also known as dynamic method dispatch.
Note: In overriding runtime object will play the role and reference type is dummy.

184
Rules for overriding:
• In overriding method names and arguments must be same. That is method signature
must be same.
• Until 1.4 version the return types must be same but from 1.5 version onwards co-variant
return types are allowed.
• According to this Child class method return type need not be same as Parent class
method return type its Child types also allowed.
Example:
class Parent

public Object methodOneO


{
return null;

class Child extends Parent

public String methodOneO


{
return null;

• It is valid in illS' but invalid in "1.4".


Diagram:
Parent method: Object Number String double

i i
return type

Child method : String Integer Object int


x x
return type
V
• Co-variant return type concept is applicable only for object types but not for primitives.
• Private methods are not visible in the Child classes hence overriding concept is not
applicable for private methods. Based on own requirement we can declare the same
Parent class private method in child class also. It is valid but not overriding.

185
Example:
class Parent
{
private void methodOneO
{}
it is valid but not overriding.

private void methodOneO


{}
}

• Parent class final methods we can't override in the Child class.


Example:
class Parent

public final void methodOne()


{}

class Child extends Parent

public void methodOne()


{}

Output:
Compile time error.
Child.java:8: methodOne() in Child cannot override methodOne() in Parent; overridden method
is final
• Parent class non final methods we can override as final in child class. We can override
native methods in the child classes.
• We should override Parent class abstract methods in Child classes to provide
implementation.
Example:
abstract class Parent

public abstract void methodOne();

class Child extends Parent

public void methodOne()


{}

186
nonabstract

• We can override Parent class non abstract method as abstract to stop availability of
Parent class method implementation to the Child classes.
Example:
class Parent

public void methodOneO


{}

abstract class Child extends Parent

public abstract void methodonef):

• Synchronized, strictfp, modifiers won't keep any restrictions on overriding.


Diagram:
final

1 1 li li SYTf
nonfinal native abstract ed strictfp

li
nonfinal final nonnative nonabstract nonSynchronized nonstrictfp
x V V V V V
• While overriding we can't reduce the scope of access modifier.
Example:
class Parent

public void methodOneO


{}

class Child extends Parent

protected void methodOneO


{}

187
Output:
Compile time error
methodOneO in Child cannot override methodOneO in Parent; attempting to assign weaker
access privileges; was public
Diagram:

pr liC prorcted <default> private

public protected/public <defL,>! protected/ publ ic I


overn idlrng concept
V V V is not applicable
x
Checked Vs Un-checked Exceptions:
• The exceptions which are checked by the compiler for smooth execution of the program
at runtime are called checked exceptions.
• The exceptions which are not checked by the compiler are called un-checked
exceptions.
• RuntimeException and its child classes, Error and its child classes are unchecked except
these the remaining are checked exceptions.
Diagram:
Object
'{}
Throwable

Exception Error

11-----...-r-..-J/-------,lmm ~j~
RuntimeException
.
ArlthmeticException
t----NuIiPointerException
t----lndexOutOfBoundsException
IOExceptionSQLException ServletException .
~
EOFException
FileNotFoundExceptlon
InterruptedlOException
A:- . ~AssertlonError
VlrtualMachln rror

VerifyE~ror

~ArraYlndexOutOfBoundsException OutOfMemoryError StackOverflowError


L_StringlndexOutOfBoundsExc.eption
t---lllegalArgumentException
L_ NumberFormatException
r-----ClassCastException
,__--lllegaIStateException

Rule: While overriding if the child class method throws any checked exception compulsory
the parent class method should throw the same checked exception or its parent otherwise
we will get compile time error"

188
• But there are no restrictions for un-checked exceptions.
Example:
class Parent

public void methodOneO


{}

class Child extends Parent

public void methodOneOthrows Exception


{}

Output:
Compile time error
methodOneO in Child cannot override methodOneO in Parent; overridden method does not
throw java. lang. Exception
Examples:

@ Parent: public void methodOneOthrows ExceptiOn}


Child: public void methodOneO valid

® Parent: public void methodOneO }"mvallid


Child: public void methodOneOthrows Exception
® Parent: public void methodOneOthrows ExceptiOn}
Child: public void methodOneOthrows Exception valid

@ Parent: public void methodOneOthrows IOException }


Child
I : pu bliIC VOl
id met h0 d One ()t h rows Exception
" invalid

@ Parent: pu~lic v~id methodOneOthrows IOExcept~on " " } valid


Child: public VOid methodOneOthrows EOFExceptlon,FlleNotFoundExceptlon
@ Parent: public void methodOneOthrows IOException }invalid
Child: public void methodOneOthrows EOFException,lnterruptedException

(Z) Parent: public void methodOneOthrows IOException } valid


Child: public void methodOneOthrows EOFException,ArithmeticException

® Parent: public void methodOneO


Child: public void methodOneOthrows } valid
ArithmeticException,NuIIPointerException,ClassCastException,RuntimeException
Overriding with respect to static methods:
Case 1:
• We can't override a static method as non static.

189
Example:
class Parent

public static void methodOne()/ /here static methodOneO method is a class level
{}

class Child extends Parent

public void methodOne()/ /here methodOneO method is a object level hence we can't
override methodOneO method
{}

Case 2:
• Similarly we can't override a non static method as static.
Case 3:
class Parent

public static void methodOne()


{}

class Child extends Parent

public static void methodOne()


{}

• It is valid. It seems to be overriding concept is applicable for static methods but it is not
overriding it is met1hod hiding.
METHOD HIDING
• All rules of method hiding are exactly same as overriding except the following
differences.
Overriding Method hiding
1. Both Parent and Child class methods should 1. Both Parent and Child class methods should
be non static. be static.
2. Method resolution is always takes care by 2. Method resolution is always takes care by
JVM based on runtime object. compiler based on reference type.
3. Overriding is also considered as runtime 3. Method hiding is also considered as compile
polymorphism (or) dynamic polymorphism time polymorphism (or) static polymorphism
(or) late binding. (or) early biding.

190
Example:
class Parent

public static void methodOne()


{
System.out.println("parent class");

class Child extends Parent

public static void methodOne()


{
System.out.println("child class");

class Test

public static void main(String[] args)


{
Parent p=new Parent();
p.methodOne();/ /parent class
Child c=new Child();
c.methodOne();/ /child class
Parent pl=new Child();
pl.methodOne();/ /parent class
}

Note: If both Parent and Child class methods are non static then it will become overriding and
method resolution is based on runtime object. In this case the output is
Parent class
Child class
Child class
Overriding with respect to Var arg methods:
• A var arg method should be overridden with var-arg method only. If we are trying to
override with normal method then it will become overloading but not overriding.
Example:
class Parent

191
public void methodOne(int ... i)
{
System.out.println("parent class");

class Child extends Parent overloading but not overriding.

public void methodOne(int i)


{
System.out.println("child class");

class Test

public static void main(String[] args)


{
Parent p=new Parent();
p.methodOne(lO);/ /parent class
Child c=new Child();
c.methodOne(lO);/ /child class
Parent pl=new Child();
p1.methodOne(lO);/ /parent class
}

• In the above program if we replace child class method with var arg then it will become
overriding. In this case the output is
Parent class
Child class
Child class
Overriding with respect to variables:
• Overriding concept is not applicable for variables.
• Variable resolution is always takes care by compiler based on reference type.
Example:
class Parent

int x=888;

class Child extends Parent

192
int x=999;

class Test

public static void main(String[] args)

Parent p=new Parentt):


System.out.println(p.x);/ /888
Child c=new Childt):
System.out.println(c.x);/ /999
Parent p1=new Childt):
System.out.println(pl.x);/ /888
}

Note: In the above program Parent and Child class variables, whether both are static or non
static whether one is static and the other one is non static there is no change in the answer.
Differences between overloading and overriding?
Property Overloading Overriding
1) Method names 1) Must be same. 1) Must be same.
2) Argument type 2) Must be different(at 2) Must be same including
least order) order.
3) Method signature 3) Must be different. 3) Must be same.
4) Return types 4) No restrictions. 4) Must be same until 1.4v
but from 1.5v onwards we
can take co-variant return
types also.
5) private, static, final 5) Can be overloaded. 5) Can not be overridden.
methods
6) Access modifiers 6) No restrictions. 6) Weakering/reducing is not
allowed.
7) Throws clause 7) No restrictions. 7) If child class method
throws any checked
exception compulsory
parent class method
should throw the same
checked exceptions or its
parent but no restrictions
for un-checked exceptions.
8) Method resolution 8) Is always takes care 8) Is always takes care by
by compiler based JVM based on runtime

193
on referenced type. object.

9) Also known as 9) Compile time 9) Runtime polymorphism


polymorphism (or) (or) dynamic (or) late
static( or)early binding.
binding.
Note:
1) In overloading we have to check only method names (must be same) and arguments
(must be different) the remaining things like return type extra not required to check.
2) But In overriding we should compulsory check everything like method names,
arguments, return types, throws keyword, modifiers etc.
>- Consider the method in parent class
Parent: public void methodOne(int i)throws IOException
• In the child class which of the following methods we can take.
1) public void methodOne(int i)/ /valid(overriding)
2) private void methodOneOthrows Exception/ /valid(overloading)
3) public native void methodOne(int i);//valid(overriding)
4) public static void methodOne(double d)/ /valid(overloading)
5) public static void methodOne(int i)
Compile time error
1) methodOne(int) in Child cannot override methodOne(int) in Parent; overriding method
is static
6) public static abstract void methodOne(float f)
Compile time error
1) illegal combination of modifiers: abstract and static
2) Child is not abstract and does not override abstract method methodOne(float) in Child
Polymorphism: Same name with different forms is the concept of polymorphism.
Example 1: We can use same absO method for int type, long type, float type etc.
Example:
1) abs(int)
2) abs(long)
3) abs(float)
Example 2: We can use the same List reference to hold ArrayList object, LinkedList object,
Vector object, or Stack object.
Example:
1) List I=new Arravtistt):
2) List I=new Linkedl.istl):
3) List I=new Vectort):
4) List I=new Stackf):

194
Diagram:

Compiletime/static/earlybinding

/\
overloading methodhiding overriding

Diagram:

Reusability

1) Inheritance talks about reusability.


2) Polymorphism talks about flexibility.
3) Encapsulation talks about security.
Beautiful definition of polymorphism:
• A boy starts love with the word friendship, but girl ends love with the same word
friendship, word is the same but with different attitudes. This concept is nothing but
polymorphism.
Constructors
• Object creation is not enough compulsory we should perform initialization then only the
object is in a position to provide the response properly.
• Whenever we are creating an object some piece of the code will be executed
automatically to perform initialization of an object this piece of the code is nothing but
constru ctor.
• Hence the main objective of constructor is to perform initialization of an object.
Example:
class Student

String name;
int rollno;
Student(String name,int roll no)
{
this.name=name; Constructor

195
this.rollno=rollno;

public static void main(String[] args)


{
Student sl=new Studentf'Ivijavabhaskar't.JO'l}:
Student s2=new Student(lbhaskar",102);

Diagram:

Constructor Vs instance block:


• Both instance block and constructor will be executed automatically for every object
st
creation but instance block 1 followed by constructor.
• The main objective of constructor is to perform initialization of an object.
• Other than initialization if we want to perform any activity for every object creation we
have to define that activity inside instance block.
• Both concepts having different purposes hence replacing one concept with another
concept is not possible.
• Constructor can take arguments but instance block can't take any arguments hence we
can't replace constructor concept with instance block.
• Similarly we can't replace instance block purpose with constructor.
Demo program to track no of objects created for a class:
class Test

static int count=O;

count++; } instance block

Test()
{}
Test(int i)
{}
public static void main(String[] args)
{
Test t1=new Test();
Test t2=new Test(10);

196
Test t3=new TestO;
System.out.println(count);/ /3

Rules to write constructors:


1) Name of the constructor and name of the class must be same.
2) Return type concept is not applicable for constructor even void also by mistake if we are
declaring the return type for the constructor we won't get any compile time error and
runtime error compiler simply treats it as a method.
Example:
class Test

void TestO it is not a constructor and it is a method


{}

3) It is legal (but stupid) to have a method whose name is exactly same as class name.
4) The only applicable modifiers for the constructors are public, default, private,
protected.
5) If we are using any other modifier we will get compile time error.
Example:
class Test

static Testf)
{}

Output:
Modifier static not allowed here
Default constructor:
• For every class in java including abstract classes also constructor concept is applicable.
• If we are not writing at least one constructor then compiler will generate default
constru ctor.
• If we are writing at least one constructor then compiler won't generate any default
constructor. Hence every class contains either compiler generated constructor (or)
programmer written constructor but not both simultaneously.
Prototype of default constructor:
1) It is always no argument constructor.
2) The access modifier of the default constructor is same as class modifier. (This rule is
applicable only for public and default).

197
3) Default constructor contains only one line. supert): it is a no argument call to super class
constru ctor.
Programmers code Compiler generated code
class Test class Test
{} {
Test()
{
super();
}
}
public class Test public class Test
{} {
public Test()
{
super();
}
}
class Test class Test
{ {
void Test(){} Test()
} {
super();
}
void Test()
{}
}
class Test class Test
{ {
Test(int i) Test(int i)
{} {
} super();
}
}
class Test class Test
{ {
Test() Test()
{ {
super(); super();
} }
} }
class Test class Test
{ {
Test(int i) Test(int i)

198
{
this(); this();
} }
Test() Test()
{} {
super();
}
}
superO vs thisO:
• The 1st line inside every constructor should be either super() or this() if we are not
writing anything compiler will always generate super().
Case 1: We have to take super() (or) this() only in the 1st line of constructor. If we are taking
anywhere else we will get compile time error.
Example:
class Test

Test()
{
System .out. pri ntl n(" constructor");
super();

Output:
Compile time error.
Call to super must be first statement in constructor
Case 2: We can use either super() (or) this() but not both simultaneously.
Example:
class Test

Test()
{
super();
this();

Output:
Compile time error.
Call to this must be first statement in constructor

199
Case 3: We can use superO (or) thisO only inside constructor. If we are using anywhere else we
will get compile time error.
Example:
class Test

public void methodOneO


{
superf):

Output:
Compile time error.
Call to super must be first statement in constructor
• That is we can call a constructor directly from another constructor only.
Diagram:
~---l.we should use only in 1st line
-+---2. only one but not both
.....__7'-----3. only inside constructor
1....- calling another constructor of same class.
1....- calling super class constructor.

Example·
suoertj.thist) super, this
1. These are constructors calls. 1. These are keywords which can be used to
call parent class and current class instance
members.
2. We should use only inside constructors. 2. We can use anywhere except static area.
Example:
class Test

public static void main(String[] args)


{
System .out. pri ntl n(super. hashCode());

Output:
Compile time error.
Non-static variable super cannot be referenced from a static context.

200
Overloaded constructors:
• A class can contain more than one constructor and all these constructors having the
same name but different arguments and hence these constructors are considered as
overloaded constructors.
Example:
class Test

Test(double d)
{
this(lO);
System.out.println("double-argument constructor");

Test(int i)
{
thist):
System.out.println("int-argument constructor");

TestO
{
System.out.println("no-argument constructor");

public static void main(String[] args)


{
Test U=new Test(lO.5);/ /no-argument constructor/int-argument
constructor/double-argument constructor
Test t2=new Test(lO);/ /no-argument constructor/int-argument constructor
Test t3=new TestO;//no-argument constructor

• "Inheritance concept is not applicable for constructors and hence overriding concept
also not applicable to the constructors. But constructors can be overloaded".
• We can take constructor in any java class including abstract class also but we can't take
constructor inside inheritance.

201
Example:

class Test abstract class Test interface Testl


{ {
Test() Test() Testl()
{} {} {}
} }
valid valid invalid
We can't create object for abstract class but abstract class can contain constructor what is the
need?
• Abstract class constructor will be executed to perform initialization of child class object.
Which of the following statement is true?
1) Whenever we are creating child class object then automatically parent class object will
be created.(false)
2) Whenever we are creating child class object then parent class constructor will be
executed. (true)
Example:
abstract class Parent

Parent()
{
System.out.println(this.hashCode());/ /11394033/ /here this means child class
object

class Child extends Parent

Child()
{
System.out.println(this.hashCode());/ /11394033

class Test

public static void main(String[] args)


{
Child c=new Child();
System.out.println(c.hashCode());/ /11394033

202
Case 1: recursive method call is always runtime exception where as recursive constructor
invocation is a compile time error.
Note:
Recursive functions:
• A function is called using two methods (types).
1) Nested call
2) Recursive call
Nested call:
• Calling a function inside another function is called nested call.
• In nested call there is a calling function which calls another function(called function).
Example:
public static void methodOneO
{
methodTwo();

public static void methodTwoO


{
methodOne();

Recursive call:
• Calling a function within same function is called recursive call.
• In recursive call called and calling function is same.
Example:
public void methodOne()

methodOne();

203
Example:
class Test
class Test
{ {
public static void methodOne(}
Test(int i)
{
{
methodTwo();
this();
}
}
public static void methodTwo()
Test()
{ {
methodOne();
this(lO);
} }
public static void main(String[] args)
public static void main(String[] args)
{
{
methodOne();
System.out.println("hello");
System.out.println("hello");
}
}
C.E:recursive constructor invocation
} R.E:StackOverflowError
Note: Compiler is responsible for the following checkings.
1) Compiler will check whether the programmer wrote any constructor or not. If he didn't
write at least one constructor then compiler will generate default constructor.
2) If the programmer wrote any constructor then compiler will check whether he wrote
st
super() or this() in the 1 line or not. If his not writing any of these compiler will always
write (generate) super().
3) Compiler will check is there any chance of recursive constructor invocation. If there is a
possibility then compiler will raise compile time error.
Case 2:
class Parent class Parent
class Parent {
{} ParentO Parent(int i)
class Child extends Parent {} {}
{} } } E:\scjp>javac Child.java
valid
class Child extends Parent class Child extends Parent Child.java:l0: cannot find symbol
{} { symbol : constructor ParentO
ChildO location: class Parent
{ superl):
super!);
}
} output:
compile time error

• If the Parent class contains any argument constructors while writing Child classes we
should takes special care with respect to constructors.
• Whenever we are writing any argument constructor it is highly recommended to write
no argument constructor also.
Case 3:
class Parent

204
Parent()throws java.io.IOException
{}

class Child extends Parent


{}
Output:
Compile time error
• Unreported exception java.io.IOException in default constructor.
Example:
class Parent

Parent()throws java.io.IOException
{}

class Child extends Parent

Child()throws Exception
{
super();

• If Parent class constructor throws some checked exception compulsory Child class
constructor should throw the same checked exception (or) its Parent.
Singleton classes:
• For any java class if we are allow to crate only one object such type of class is said to be
singleton class.
Example:
1) Runtime class
2) ActionServlet
3) ServiceLocator
Runtime r1=Runtime.getRuntime();/ /getRuntimeO method is a factory method

Runtime r2=Runtime.getRuntimeO;

Runtime r3=Runtime.getRuntimeO;

205
System.out.println(r1==r2);/ /true
System.out.println(r1==r3);/ /true
Diagram:

rl-=i:)
r2
r3

• If the requirement is same then instead of creating a separate object for every person
we will create only one object and we can share that object for every required person
we can achieve this by using singleton classes. That is the main advantages of singleton
classes are Performance will be improved and memory utilization will be improved.
Creation of our own singleton classes:
• We can create our own singleton classes for this we have to use private constructor and
factory method.
Example:
class Test

private static Test t=null;


private Test()
{}
public static Test getTest()/ /getTest() method is a factory method
{
if(t==null)
{
t=new Test();

return t;

class Client

public static void main(String[] args)


{
System.out.println(Test.getTest().hashCode() );//1671711
System.out.printl n(Test.getTest().hashCode() );//1671711
System.out.println(Test.getTest().hashCode() );//1671711
System.out.printl n(Test.getTest().hashCode() );//1671711

206
Diagram:

t1=t:)
t2
t3

Note:
• We can create any xxxton classes like(double ton,trible ton ....etc)
Example:
class Test

private static Test t1=null;


private static Test t2=null;
private TestO
{}
public static Test getTestO/ /getTestO method is a factory method
{
if(t1==null)
{
t1=new Test();
return t1;

else if(t2==null)
{
t2=new Test();
return t2;

else

if(Math.random()<O.5 )
return t1;
else
return t2;

class Client

public static void main(String[] args)


{

207
System.out.println(Test.getTestO.hashCode() );//1671711
System.out.println(Test.getTestO.hashCode());/ /11394033
System.out.println(Test.getTestO.hashCode());/ /11394033
System.out.printl n(Test.getTestO.hashCodeO );//1671711

Which of the following is true?


1) The name of the constructor and name of the class need not be same.(false)
2) We can declare return type for the constructor but it should be void. (false)
3) We can use any modifier for the constructor. (false)
4) Compiler will always generate default constructor. (false)
5) The modifier of the default constructor is always default. (false)
st
6) The 1 line inside every constructor should be super always. (false)
7) The 1st line inside every constructor should be either super or this and if we are not
writing anything compiler will always place thisO.(false)
8) Overloading concept is not applicable for constructor. (false)
9) Inheritance and overriding concepts are applicable for constructors. (false)
10) Concrete class can contain constructor but abstract class cannot. (false)
11) Interface can contain constructor. (false)
12) Recursive constructor call is always runtime exception. (false)
13) If Parent class constructor throws some un-checked exception compulsory Child class
constructor should throw the same un-checked exception or it's Parent. (false)
14) Without using private constructor we can create singleton class. (false)
15) None of the above.(true)
Factory method:
• By using class name if we are calling a method and that method returns the same class
object such type of method is called factory method.
Example:
Runtime r=Runtime.getRuntimeO;/ /getRuntime is a factory method.
Date Format df= Date Form at.getl nsta nce();
• If object creation required under some constraints then we can implement by using
factory method.

208
Static control flow:
Example:

class Base
{
®static int@------<v
®static
{
ImethodOne()i --e
!system.out.println("first static block")i!t----@
}
® public static void main(String[] args)
{
!methodOne()i! @
Fc!
s~y~st;::e::m~.
o::u~t:=:.
p:::rti n7r,-;:,
n:;ti':1( m::a:::i:-n i:1-I--@
-:m::e:;ti:':ho::d 4711;'\.)
}
@ public static void methodOne()
{
system.out.println(j)i---@,@
}
@ static
{
System.out.println("second static block")i--@
}
® static int @------@
}

Analysis:
i=O[RIWO]
j=O[RIWO]
i=10[R&W]
j=20[R&W]
l.identification of static members from top to bottom[1 to 6]
2.execution of static variable assignments and static blocks from top to bottom [7 to 12]
3.execution of main method[13 to 15]
Output:
E:\scjp>javac Base.java
E:\scjp>java Base
o
First static block
Second static block
20
Main method

209
Read indirectly write only state (or) RIWO:
• If a variable is in RIWO state then we can't perform read operation directly otherwise
we will get compile time error saying illegal forward reference.
Example:

class Test class Test class Test


{ { {
static int i=lOi static static
static { {
{ System.out.println(i); methodonet):
System.out.println(i)i/ /10 } }
System.exit(O)i static int i=lOi public static void methodOneO
} } {
} output: System.out.println(i)i
compile time error:
}
illegal forward reference static int i=lOi
} output:
Runtime exception:
o
NoSuchMethodError: main

210
Example:
class Base

{<Ylstaticint(9 @
® static
{
ImethodOne(); ~@
System.out.println("base static block"); @
}
® public static void main(String[] args)
{
methodOneOi
System.out.println("base main");
}
@Publicstaticvoid methodOneO
{
System.out.printlnO)j --@
}
@static int8---®
}
class Derived extends Base
{
@Istatic int@ @
<V static
{
ImethodTwoOj t--@
System.out.println("derived first static block");--@
}
@ public static void main(String[] args)

{ ImethodTwo();1 @
System.out.println("derived main"); __ @
}
® public static void methodTwo()
{
System.out.println(y); --@,@
}
@static
{
System.out.println("derived second static block");--@
}
@staticint~
}

211
Analysis:
i=O[RIWO]
j=O[RIWO]
x=O[RIWO]
y=O[RIWO]
i=10[R&w]
j=20[R&w]
x=100[R&w]
y=200[R&w]

Output:
E:\scjp>java Derived
o
Base static block
o
Derived first static block
Derived second static block
200
Derived main
• Whenever we are executing Child class the following sequence of events will be performed
automatically.
1) Identification of static members from Parent to Child. [1 to 11]
2) Execution of static variable assignments and static blocks from Parent to Child.[12 to 22]
3) Execution of Child class mainO method.[23 to 25].
Static block:
• Static blocks will be executed at the time of class loading hence if we want to perform
any activity at the time of class loading we have to define that activity inside static block.
• With in a class we can take any no. Of static blocks and all these static blocks will be
executed from top to bottom.
Example:
• The native libraries should be loaded at the time of class loading hence we have to
define that activity inside static block.
Example:
class Test

static

System.loadLibrary("native library path");

212
• Every JDBC driver class internally contains a static block to register the driver with
DriverManager hence programmer is not responsible to define this explicitly.
Example:
class Driver

static

Register this driver with DriverManager

Without using mainO method is it possible to print some statements to the console?
Ans: Yes, by using static block.
Example:
class Google

static

System.out.println("hello i can print");


System.exit(O);

Output:
Hello i can print
Without using mainO method and static block is it possible to print some statements to the
console?
Example 1:
class Test

static int i=methodOneO;


public static int methodOneO
{
System.out.println("hello i can print");
System.exit(O);
return 10;

Output:
Hello i can print

213
Example 2:
class Test

static Test t=new Testt):


TestO
{
System.out.println("hello i can print");
System.exit(O);

Output:
Hello i can print
Example 3:
class Test

static Test t=new Testf):


{
System.out.println("hello i can print");
System.exit(O);
}

Output:
Hello i can print
Without using System.out.printlnO statement is it possible to print some statement to the
console?
Example:
class Test

public static void main(String[] args)


{
System.err.println("hello");

214
Instance control flow:

class Parent
f
@~@
@){
methodOneO; @
}
@ParentO
{
System.out.println("Parent class constructor");

public static void main(String[] args) @


{
IParent p=new ParentO; I ®
ISystem.out.println("main method");1 @
}
® public void methodOneO
{
ISystem.out.printlnU);1 @
}
0{
Isystem.out.println("second instance bIOCkll);i@
}
®lint<D~v @
}

Analysis:
i=O[RIWOj
j=O[RIWOj
i=10[R&Wj
j=20[R&Wj
Output:

215
• Whenever we are creating an object the following sequence of events will be performed
automatically.
1) Identification of instance members from top to bottom(3 to 8).
2) Execution of instance variable assignments and instance blocks from top to bottom(9 to
14).
3) Execution of constructor.
Note: static control flow is one time activity and it will be executed at the time of class loading.
• But instance control flow is not one time activity for every object creation it will be
executed.
Instance control flow in Parent and Child relationship:
Example:
class Parent

int x=10;

methodonef):
System.out.println("Parent first instance block");

ParentO
{
System.out.println("parent class constructor");

public static void main(String[] args)


{
Parent p=new Parenti):
System.out.println("parent class main method");

public void methodOneO


{
System.out.println(y);

int y=20;

class Child extends Parent

int i=100;

rnethod'Twof):

216
System.out.println("Child first instance block");

ChildO
{
System.out.println("Child class constructor");

public static void main(String[] args)


{
Child c=new Chtldf):
System.out.println("Child class main method");

public void methodTwoO


{
System.out.println(j);
}
{
System.out.println("Child second instance block");

int j=200;

Output:
E:\scjp>javac Child.java
E:\scjp>java Child
o
Parent first instance block
Parent class constructor
o
Child first instance block
Child second instance block
Child class constructor
Child class main method
• Whenever we are creating child class object the following sequence of events will be
executed automatically.
1) Identification of instance members from Parent to Child.
2) Execution of instance variable assignments and instance block only in Parent class.
3) Execution of Parent class constructor.
4) Execution of instance variable assignments and instance blocks in Child class.
5) Execution of Child class constructor.

217
Note: Object creation is the most costly operation in java and hence if there is no specific
requirement never recommended to crate objects.
Example 1:
public class Initilization

private static String methodOne(String msg)

System.out.println(msg);

return msg;

public Initilization()

m=methodOne("l");

m=methodOne("2");

String m=methodOne("3");

public static void main(String[] args)

Object obj=new Initilization();

Analysis:
1
~
-t
m=methodOne() [RIWO]

218
Output:
2
3
1
Example 2:
public class Initilization

private static String methodOne(String msg)

System.out.println(msg);
return msg;

static String m=methodOne("l");


{
m=methodOne("2");

static

m=methodOne("3");

public static void main(String[] args)


{
Object obj=new Initilization();

Output:
1
3
2
• We can't access instance variables directly from static area because at the time of
execution of static area JVM may not identify those members.

219
Example:
class Test
{
int i=10;
public static void main(String[] args)
{
System.out.printl(i);
}
} output:
compile time error
non-static variable i cannot be referenced from a static context
• But from the instance area we can access instance members directly.
• Static members we can access from anywhere directly because these are identified
already at the time of class loading only.
Type casting:
• Parent class reference can be used to hold Child class object but by using that reference
we can't call Child specific methods.
Example:
Object o=new String("bhaskar");//valid
System.out.printl n(o. hashCode());/ Iva lid
System.out.println(o.length());/ /C.E:cannot find svrnbol.svrnbol : method Iengthtj.location:
class java.lang.Object
• Similarly we can use interface reference to hold implemented class object.
Example:
Runnable r=new Thread();
Type casting syntax:

name of class/interface name of reference


reference variable/object
variable
Compile time checking:
Rule 1: The type of lid" and "c" must have some relationship [either Child to Parent (or) Parent
to Child (or) same type] otherwise we will get compile time error saying inconvertible types.
Example 1:

Object o=new String("bhaskar"); (valid)


StringBuffer sb=(StringBuffer)o;

220
Example 2:

String s=new String("bhaskar")j


(inval id)
StringBuffer sb=(StringBuffer)sj
output:
compile time error
E:\scjp>javac Test.java
Test.java:6: inconvertible types
found : java.lang.String
required: java.lang.StringBuffer
StringBuffer sb=(StringBuffer)sj
Rule 2: "C' must be either same (or) derived type of "A" otherwise we will get compile time
error saying incompatible types.
Found:C
Required: A
Example 1:

Object o=new String("bhaskar");


StringBuffer sb=(StringBuffer)o; (valid)

Example 2:

Object o=new String("bhaskar"); (. id]


. B u ff er sb =(Strmg
Strmg • ) 0; invalid

output:
compile time error
E:\scjp>javac Test.java
Test.java:6: incompatible types
found : java.lang.String
required: java.lang.StringBuffer
StringBuffer sb=(String)o;

Runtime checking:
• The underlying object type of "d" must be either same (or) derived type of "C"
otherwise we will get runtime exception saying ClassCastException.
Example:

Object o=new String("bhaskar")j


StringBuffer sb=(StringBuffer)o;

Runtime Exception:ClassCastException

221
Diagram:
Object

Derived2 Derived3 Derived4


Basel b=new Derived2();/ /valid
Object o=(Basel)b;/ /valid
Object ol=(Base2)o;//invalid
Object o2=(Base2)b;//invalid
Base2 bl=(Basel)(new Derivedl());/ /invalid
Base2 b2=(Base2)(new Derived3());/ /valid
Base2 b2=(Base2)(new Derivedl());/ /invalid
• Through Type Casting just we are converting the type of object but not object itself that
is we are performing type casting but not object casting.
Example:

String s=new String("bhaskar")j


Object o=(Object)sj Strings-~y
equivalent code System.out.println(s==o )j/ /true Objecto-~~ .__--
Object o=new String("bhaskar")j

222
Example 1:

class Parent
{
public void methodOne()
Parent -____;">~ {
System.out.println(" A"]:
}
}

class Child extends Parent


Child "> {
public void methodOneO
{
System.out.println(IB")j
}
public void methodTwo()
{
Parent p=new ParentOj
svstem.out.prlntlntvc"):
}
/ ((Parent)c).methodTwo();
public static void main(String[] args) output:
compile time error.
{ Child c=new Child(); /( Child.java:25: cannot find symbol
c.methodOne()i/ /B symbol : method methodT woO
c.methodTwoO;/ /C location: class Parent
HParent)c).methodOneO;/ /B ((Parent)c).metho dTwoOi
}
}

Example 2:

A ---iPublic void methodOneO


{
System.out.println(" Ali);
}

public void methodOneO


B------i {
System.out.println("B");
}

public void methodOneO


{
C------1 System.out.println("C");
}

• It is overriding and method resolution is based on runtime object.

223
C c=new C();
c.methodOne();/ /c
((B)c).methodOne();/ /c
((A)((B )c)).methodOne();/ /c
Example 3:

A ------I public static void methodOneO


{
System.out.println(" A"]:
}

public static void methodOneO


B-----i {
System.out.println("B")j
}

public static void methodOneO


{
(-----I
System.out.println("(")j
}

• It is method hiding and method resolution is based on reference type.


C c=new C();
c.methodOne();/ /C
((B)c).methodOne();! /B
((A)((B)c)).methodOne();/ /A
Example 4:
A ---- int x=777j

i
B---- int x=888j

t
(---- int x=999j
C c=new C();
System.out.println(c.x);/ /999
System.out.println(((B)c).x);/ /888
System.out.println( ((A)((B )c)) .x);! /777
• Variable resolution is always based on reference type only.
• If we are changing variable as static then also we will get the same output.
Coupling:
• The degree of dependency between the components is called coupling.

224
Example:
class A

static int i=B.j;

class B extends A

static int j=C.methodOneO;

class C extends B

public static int methodOneO


{
return D.k;

class D extends C

static int k=10;


public static void main(String[] args)

D d=new DO;

• The above components are said to be tightly coupled to each other because the
dependency between the components is more.
• Tightly coupling is not a good programming practice because it has several serious
disadvantages.
1) Without effecting remaining components we can't modify any component hence
enhancement(development) will become difficult.
2) It reduces maintainability of the application.
3) It doesn't promote reusability of the code.
• It is always recommended to maintain loosely coupling between the components.
Cohesion:
• For every component we have to maintain a clear well defined functionality such type of
component is said to be follow high cohesion.

225
Diagram:

login page
validation inbox.jsp compose.jsp
inbox
Compose
login.jsp
Forward

validate servlet error.jsp


low cohesion high cohesion
TotalServlet.java

• High cohesion is always good programming practice because it has several advantages.
1) Without effecting remaining components we can modify any component hence
enhancement will become very easy.
2) It improves maintainability of the application.
3) It promotes reusability of the application.
Note: It is highly recommended to follow loosely coupling and high cohesion.

226
Multi Threading
Agenda
1) Introduction.
2) The ways to define instantiate and start a new Thread.
3) Getting and setting name of a Thread.
4) Thread priorities.
5) The methods to prevent(stop) Thread execution.
1. vieldf)
2. joinO
3. sleepf)
6) Synchronization.
7) Inter Thread communication.
8) Deadlock
9) Daemon Threads.
Multitasking: Executing several tasks simultaneously is the concept of multitasking. There are
two types of multitasking's.
1) Process based multitasking.
2) Thread based multitasking.
Diagram:

A
Processbased multitasking Thread based Multithreading

Process based multitasking: Executing several tasks simultaneously where each task is a
separate independent process such type of multitasking is called process based multitasking.
Example:
• While typing a java program in the editor we can able to listen mp3 audio songs at the
same time we can download a file from the net all these tasks are independent of each
other and executing simultaneously and hence it is Process based multitasking.
• This type of multitasking is best suitable at "os level".
Thread based multitasking: Executing several tasks simultaneously where each task is a
separate independent part of the same program, is called Thread based multitasking. And each
independent part is called a "Thread".
• This type of multitasking is best suitable for "programatic level".
• When compared with "C++", developing multithreading examples is very easy in java
because java provides in built support for multithreading through a rich API (Thread,
Runnable, ThreadGroup, ThreadLocal. ...etc).

227
• In multithreading on 10% of the work the programmer is required to do and 90% of the
work will be down by java API.
• The main important application areas of multithreading are:
1) To implement multimedia graphics.
2) To develop animations.
3) To develop video games etc.
• Whether it is process based or Thread based the main objective of multitasking is to
improve performance of the system by reducing response time.
The ways to define instantiate and start a new Thread:
What is singleton? Give example?
• We can define a Thread in the following 2 ways.
1. By extending Thread class.
2. By implementing Runnable interface.
Defining a Thread by extending "Thread class":
Example:
class MyTh read extends Thread
{
public void runO
{
defining
a for(int i=O;i<10;i++)
Thread. {

Job of a Thread.
}
}

class ThreadDemo

public static void main(String[] args)


{
MyThread t=new MyThread();/ /Instantiation of a Thread
t.start();/ /starting of a Thread
..
for(int i=0;i<5;i++)
{
System.out.println("main thread");

228
Case 1: Thread Scheduler:
• If multiple Threads are waiting to execute then which Thread will execute 1st is decided
by "Thread Scheduler" which is part of JVM.
• Which algorithm or behavior followed by Thread Scheduler we can't expect exactly it is
the JVM vendor dependent hence in multithreading examples we can't expect exact
execution order and exact output.
• The following are various possible outputs for the above program.
pl p2 p3
main thread main thread main thread
main thread main thread main thread
main thread main thread main thread
main thread main thread main thread
main thread main thread main thread
child thread child thread child thread
child thread child thread child thread -------------.-----------
child thread child thread child thread
child thread child thread child thread
child thread child thread child thread
child thread child thread child thread
child thread child thread' child thread
child thread child thread child thread
child thread child thread child thread
child thread child thread child thread
Case 2: Difference between t.startt) and t.runO methods.
• In the case of t.startl] a new Thread will be created which is responsible for the
execution of runO method. But in the case of t.runO no new Thread will be created and
runO method will be executed just like a normal method by the main Thread. In the
above program if we are replacing t.startO with t.runO the following is the output.
Output:
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
main thread

229
main thread
main thread
main thread
main thread
• Entire output produced by only main Thread.
Case 3: importance of Thread class startO method.
• For every Thread the required mandatory activities like registering the Thread with
Thread Scheduler will takes care by Thread class startf) method and programmer is
responsible just to define the job of the Thread inside runO method. That is startf)
method acts as best assistant to the programmer.
Example:
startf)
{
1. Register Thread with Thread Scheduler
2. All other mandatory low level activities.
3. Invoke or calling runO method.

• We can conclude that without executing Thread class startl] method there is no chance
of starting a new Thread in java.
Case 4: If we are not overriding runO method:
• If we are not overriding runO method then Thread class runO method will be executed
which has empty implementation and hence we won't get any output.
Example:
class MyThread extends Thread
{}
class ThreadDemo

public static void main(String[] args)


{
MyTh read t=new MyThreadO;
t.startf):

• It is highly recommended to override runO method. Otherwise don't go for


multithreading concept.

230
Case 5: Overriding of runO method.
• We can overload run() method but Thread class start() method always invokes no
argument run() method the other overload run() methods we have to call explicitly then
only it will be executed just like normal method.
Example:
class MyTh read extends Thread

public void run()


{
System.out.println("no arg method");

public void run(int i)


{
System.out.println("int arg method");

class ThreadDemo

public static void main(String[] args)


{
MyTh read t=new MyThread();
t.start();

Output:
No arg method
Case 6: overriding of startO method:
• If we override start() method then our start() method will be executed just like a normal
method call and no new Thread will be started.
Example:
class MyTh read extends Thread

public void start()


{
System.out.println("start method");

public void run()


{

231
System.out.println("run method");

class ThreadDemo

public static void main(String[] args)


{
MyTh read t=new MyThread();
t.start();
System.out.println("main method");

Output:
start method
main method
• Entire output produced by only main Thread.
Case 7:
Example 1:

class ThreadDemo
class MyTh read extends Thread
{ {
public void startO ~- ~ public static void main(String[] args)
{ {
MyThread t=new MyThreadO;
System.out.println("start method"]:
} t.startl]:
System.out.println("main method");
public void runO
{ }
}
System.out.println("run method"]:
output:
}
} main thread
start method
main method

232
Example 2:

class MyThread extends Thread class ThreadDemo


{ {
public void startO-E------- public static void main(String[] args)
{ {
super .startl]: MyTh read t=new MyThreadOi
-____;:')~system.out.println("start method"]: t.startt]:
} System.out.println("main method"]:
public void runO }
{ }
System.out.println("run method"]:
}
}
Output:

child main
run method start method
main method
Case 8: life cycle of the Thread:

ifTS
allocates CPU

• Once we created a Thread object then the Thread is said to be in new state or born
state.
• Once we call start() method then the Thread will be entered into Ready or Runnable
state.
• If Thread Scheduler allocates CPU then the Thread will be entered into running state.
• Once run() method completes then the Thread will entered into dead state.
Case 9:
• After starting a Thread we are not allowed to restart the same Thread once again
otherwise we will get runtime exception saying "1IIegaIThreadStateException".
Example:
MyTh read t=new MyThread();
t.start();/ /valid
11111111

t.start();/ /we will get R.E saying: IllegalThreadStateException

233
Defining a Thread by implementing Runnable interface:
• We can define a Thread even by implementing Runnable interface also. Runnable
interface present in java.lang.pkg and contains only one method run().
Diagram:

2nd Approach

Example:

class MyRunnable implements Runnable


{
public void runO
{
defining a
for(int i=Oji<lOji++)
Thread
{
System.out.println("child Thread"]:

job of a Thread
}
}
class ThreadDemo

public static void main(String[] args)


{
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);/ /here r is a Target Runnable
t.start();

for(int i=O;i<10;i++)
{
System.out.println("main thread");

234
Output:
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
• We can't expect exact output but there are several possible outputs.
Case study:
MyRunnable r=new MyRunnable();
Thread t1=new Thread();
Thread t2=new Thread(r);
Case 1: tl.startO:
• A new Thread will be created which is responsible for the execution of Thread class
run()method.
Output:
main thread
main thread
main thread
main thread
main thread
Case 2: tl.runO:
• No new Thread will be created but Thread class run() method will be executed just like
a normal method call.

235
Output:
main thread
main thread
main thread
main thread
main thread
Case 3: t2.startO:
• New Thread will be created which is responsible for the execution of MyRunnable run()
method.
Output:
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread
Case 4: t2.runO:
• No new Thread will be created and MyRunnable run() method will be executed just like
a normal method call.
Output:
child Thread
child Thread
child Thread
child Thread
child Thread
main thread
main thread
main thread
main thread
main thread
Case 5: r.startO:
• We will get compile time error saying start()method is not available in MyRunnable
class.

236
Output:
Compile time error
E:\SCJP>javac ThreadDemo.java
ThreadDemo.java:18: cannot find symbol
Symbol: method startf)
Location: class MyRunnable
Case 6: r.runO:
• No new Thread will be created and MyRunnable class runO method will be executed just
like a normal method call.
Output:
child Thread
child Thread
child Thread
child Thread
child Thread
main thread
main thread
main thread
main thread
main thread
Best approach to define a Thread:
• Among the 2 ways of defining a Thread, implements Runnable approach is always
recommended.
• In the 1st approach our class should always extends Thread class there is no chance of
extending any other class hence we are missing the benefits of inheritance.
• But in the 2nd approach while implementing Runnable interface we can extend some
other class also. Hence implements Runnable mechanism is recommended to define a
Thread.
Thread class constructors:
1) Thread t=new Threadt):
2) Thread t=new Thread(Runnable r);
3) Thread t=new Thread(String name);
4) Thread t=new Thread(Runnable r,String name);
5) Thread t=new Thread(ThreadGroup g,String name);
6) Thread t=new Thread(ThreadGroup g,Runnable r);
7) Thread t=new Thread(ThreadGroup g,Runnable r,String name);
8) Thread t=new Thread(ThreadGroup g,Runnable r,String name,long stackSize);

237
Durga's approach to define a Thread(not recommended to use):
class ThreadDemo
{
class MyTh read extends Thread public static void main(String[] args)
{ {
public void runO MyTh read t=new MyThreadO;
{ Thread tl=new Thread(t);
System.out.println("run method"); tl.startO;
} System.out.println(" main method");
} }
}
Diagram:
Runnable

l'
Thread

t
MyThread

Output:
main method
run method
Getting and setting name of a Thread:
• Every Thread in java has some name it may be provided explicitly by the programmer or
automatically generated by JVM.
• Thread class defines the following methods to get and set name of a Thread.
Methods:
1) public final String getNameO
2) public final void setName(String name)
Example:
class MyTh read extends Thread
{}
class ThreadDemo

public static void main(String[] args)


{
System.out.println(Thread.currentThreadO.getNameO);//main
MyThread t=new MyThreadO;
System.out.println(t.getName());/ /Thread-O
Thread.currentThread().setName("Bhaskar Thread");
System.out.println(Thread.currentThreadO.getName());/ /Bhaskar Thread

238
Note: We can get current executing Thread object reference by using Thread.currentThread()
method.
Thread Priorities
• Every Thread in java has some priority it may be default priority generated by JVM (or)
explicitly provided by the programmer.
• The valid range of Thread priorities is 1 to 10[but not 0 to 10] where 1 is the least
priority and 10 is highest priority.
• Thread class defines the following constants to represent some standard priorities.
1) Thread. MIN_PRIORITY----------1
2) Thread. MAX_PRIORITY----------10
3) Thread. NORM_PRIORITY--------S
• There are no constants like Thread.LOW_PRIORITY, Thread.HIGH_PRIORITY
• Thread scheduler uses these priorities while allocating CPU.
• The Thread which is having highest priority will get chance for 1st execution.
• If 2 Threads having the same priority then we can't expect exact execution order it
depends on Thread scheduler whose behavior is vendor dependent.
• We can get and set the priority of a Thread by using the following methods.
1) public final int getPriorityO
2) public final void setPriority(int newPriority);/ /the allowed values are 1 to 10
• The allowed values are 1 to 10 otherwise we will get runtime exception saying
"lllegaIArgumentException".
Default priority:
• The default priority only for the main Thread is 5. But for all the remaining Threads the
default priority will be inheriting from parent to child. That is whatever the priority
parent has by default the same priority will be for the child also.
Example 1:
class MyTh read extends Thread
{}
class ThreadPriorityDemo

public static void main(String[] args)


{
System .out. pri ntl n(Thread. currentTh read () .getPriority());/ /5
Thread.currentThread().setPriority(9);
MyTh read t=new MyThread();
System.out.println(t.getPriority() );//9

239
Example 2:
class MyTh read extends Thread

public void runO


{
for(int i=0;i<10;i++)
{
System.out.println("child thread");

class ThreadPriorityDemo

public static void main(String[] args)


{
MyThread t=new MyThreadO;
/ /t.setPriority( 10); 1
t.startt):
for(int i=0;i<10;i++)
{
System.out.println("main thread");

• If we are commenting line 1 then both main and child Threads will have the same
priority and hence we can't expect exact execution order.
• If we are not commenting line 1 then child Thread has the priority 10 and main Thread
has the priority 5 hence child Thread will get chance for execution and after completing
child Thread main Thread will get the chance in this the output is:
Output:
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread

240
child thread
child thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
• Some operating systems(like windowsXP) may not provide proper support for Thread
priorities. We have to install separate bats provided by vendor to provide support for
priorities.
The Methods to Prevent a Thread from Execution:
• We can prevent(stop) a Thread execution by using the following methods.
1) yieldO;
2) [oint):
3) sleept):
yieldO:
• vieldt) method causes lito pause current executing Thread for giving the chance of
remaining waiting Threads of same priority".
• If all waiting Threads have the low priority or if there is no waiting Threads then the
same Thread will be continued its execution.
• If several waiting Threads with same priority available then we can't expect exact which
Thread will get chance for execution.
• The Thread which is yielded when it get chance once again for execution is depends on
mercy of the Thread scheduler.
• public static native void yieldO;
Diagram:

241
Example:
class MyTh read extends Thread

public void runO


{
for(int i=O;i<5;i++)
{
Thread.vieldt):
System.out.println("child thread");

class ThreadYieldDemo

public static void main(String[] args)


{
MyTh read t=new MyThreadO;
t.startt):
for(int i=O;i<5;i++)
{
System.out.println("main thread");

Output:
main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread
• In the above example the chance of completing main Thread 1st is high because child
Thread always calling vieldf) method.

242
JoinO:
• If a Thread wants to wait until completing some other Thread then we should go for
joinO method.
Example:
• If a Thread t1 executes t2.joinO then t1 should go for waiting state until completing t2.
Diagram:

tl

1) public final void joinflthrows InterruptedException


2) public final void join(long ms) throws Interrupted Exception
3) public final void join(long ms,int ns) throws Interrupted Exception
Diagram:

1) If t2 completes (or)

2) If time expires (or) 1)t2.joinOi


3) If waiting got interrupted

t2.join(1000,100)i

• Every joinO method throws InterruptedException, which is checked exception hence


compulsory we should handle either by try catch or by throws keyword.
Example:
class MyTh read extends Thread

public void runO


{
for(int i=O;i<5;i++)
{
System.out.println("Seethe Thread");
try

243
Thread.sleep(2000);

catch (Interrupted Exception e){}

class ThreadJoinDemo

public static void main(String[] args)throws InterruptedException

MyTh read t=new MyThreadO;


t.startf):
/ /t.joinf): 1
for(int i=O;i<5;i++)
{
System.out.println("Rama Thread");

• If we are commenting line 1 then both Threads will be executed simultaneously and we
can't expect exact execution order.
• If we are not commenting line 1 then main Thread will wait until completing child
Thread in this the output is seethe Thread 5 times followed by Rama Thread 5 times.
SleepO method:
• If a Thread don't want to perform any operation for a particular amount of time then we
should go for sleept) method.
1) public static native void sleep(long ms) throws Interrupted Exception
2) public static void sleep(long ms,int ns)throws Interrupted Exception

244
Diagram:

l)Thread.sleep(lOOO)i
2)lf sleeping Thread got interrupted
2)Thread.sleep(lOOO,lOO)i

Example:
class ThreadJoinDemo

public static void main(String[] args)throws Interrupted Exception

Svstern.out.printlnffvl"):
Thread.sleep(3000);
System.out.println(" E");
Thread.sleep(3000);
Svstem.out.printlntG''}:
Thread.sleep(3000);
Svstem.out.printlnl'A"):

Output:
M
E
G
A
Interrupting a Thread:
• We can interrupt a sleeping or waiting Thread by using interruptO(break off) method of
Thread class.
Example:
class MyTh read extends Thread

public void runO


{
try

245
for(int i=O;i<5;i++)
{
System.out.println("i am lazy Thread :"+i);
Thread.sleep(2000);

catch (InterruptedException e)
{
System.out.println("i got interrupted");

class ThreadlnterruptDemo

public static void main(String[] args)


{
MyTh read t=new MyThreadO;
t.startf):
//t.interruptO; ----..l
System.out.println("end of main thread");

• If we are commenting line 1 then main Thread won't interrupt child Thread and hence
child Thread will be continued until its completion.
• If we are not commenting line 1 then main Thread interrupts child Thread and hence
child Thread won't continued until its completion in this case the output is:
End of main thread
I am lazy Thread: 0
I got interrupted
Note:
• Whenever we are calling interrupti] method we may not see the effect immediately, if
the target Thread is in sleeping or waiting state it will be interrupted immediately.
• If the target Thread is not in sleeping or waiting state then interrupt call will wait until
target Thread will enter into sleeping or waiting state. Once target Thread entered into
sleeping or waiting state it will effect immediately.
• In its lifetime if the target Thread never entered into sleeping or waiting state then there
is no impact of interrupt call simply interrupt call will be wasted.

246
Example:
class MyTh read extends Thread

public void runO


{
for(int i=O;i<5;i++)
{
System.out.println("iamlazy thread");

try

Thread.sleep(3000);

catch (Interrupted Exception e)


{
System.out.println("i got interrupted");

class ThreadlnterruptDemol

public static void main(String[] args)


{
MyTh read t=new MyThreadO;
t.startf):
t.interrupt();
System.out.println("end of main thread");

• In the above program interrupt() method call invoked by main Thread will wait until
child Thread entered into sleeping state.
• Once child Thread entered into sleeping state then it will be interrupted immediately.
Compression of yield, join and sleept) method?
property YieldO JoinO Sleept]
1) Purpose? To pause current If a Thread wants If a Thread don't
executing Thread to wait until want to perform
for giving the completing some any operation for
chance of other Thread then a particular
remaining waiting we should go for amount of time

247
Threads of same join. then we should
priority. go for sleept]
method.
2) Is it static? yes no yes
3) Is it final? no yes no
4) Is it overloaded? No yes yes
5) Is it throws no yes yes
6) Interrupted Exception ?
7) Is it native method? yes no sleep(long ms)
sleep(long rns.int
ns)

Synchronization
• Synchronized is the keyword applicable for methods and blocks but not for classes and
variables.
• If a method or block declared as the synchronized then at a time only one Thread is allow
to execute that method or block on the given object.
• The main advantage of synchronized keyword is we can resolve date inconsistency
problems.
• But the main disadvantage of synchronized keyword is it increases waiting time of the
Thread and effects performance of the system.
• Hence if there is no specific requirement then never recommended to use synchronized
keyword.
• Internally synchronization concept is implemented by using lock concept.
• Every object in java has a unique lock. Whenever we are using synchronized keyword then
only lock concept will come into the picture.
• If a Thread wants to execute any synchronized method on the given object 1st it has to get
the lock of that object. Once a Thread got the lock of that object then it's allow to execute
any synchronized method on that object. If the synchronized method execution completes
then automatically Thread releases lock.
• While a Thread executing any synchronized method the remaining Threads are not allowed
execute any synchronized method on that object simultaneously. But remaining Threads
are allowed to execute any non-synchronized method simultaneously. [lock concept is
implemented based on object but not based on method].
Example:
class Display
{
public synchronized void wish(String name)

248
for(int i=O;i<5;i++)
{
System.out.print("good morning:");
try

Thread.sleep(lOOO);

catch (Interrupted Exception e)


{}
System.out.println(name);

class MyTh read extends Thread

Display d;
String name;
MyThread(Display d,String name)
{
this.d=d:
this.name=name;

public void runO


{
d.wish(name);

class Synchronized Demo

public static void main(String[] args)


{
Display dl=new Displavl]:
MyThread tl=new MyThread(dl,ldhoni");
MyThread t2=new MyThread(dl,lyuvaraj");
t l.startf):
t2.startO;

249
• If we are not declaring wish() method as synchronized then both Threads will be
executed simultaneously and we will get irregular output.
Output:
good morning:good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
dhoni
• If we declare wish()method as synchronized then the Threads will be executed one by
one that is until completing the 1st Thread the 2nd Thread will wait in this case we will
get regular output which is nothing but
Output:
good morning:dhoni
good morning:dhoni
good morning:dhoni
good morning:dhoni
good morning:dhoni
good morning:yuvaraj
good morning:yuvaraj
good morning:yuvaraj
good morning:yuvaraj
good morning:yuvaraj
Case study:
Case 1:
Display d1=new Display();
Display d2=new Display();
MyThread tl=new MyThread(d1,"dhoni");
MyThread t2=new MyThread(d2,"yuvaraj");
tl.start();
t2.start();

250
Diagram:

-r=:
~ .wish("dhoni");

-c:
~ .wish("yuvaraj");

• Even though we declared wish() method as synchronized but we will get irregular
output in this case, because both Threads are operating on different objects.
Class level lock:
• Every class in java has a unique lock. If a Thread wants to execute a static synchronized
method then it required class level lock.
• Once a Thread got class level lock then it is allow to execute any static synchronized
method of that class.
• While a Thread executing any static synchronized method the remaining Threads are
not allow to execute any static synchronized method of that class simultaneously.
• But remaining Threads are allowed to execute normal synchronized methods, normal
static methods, and normal instance methods simultaneously.
• Class level lock and object lock both are different and there is no relationship between
these two.
Synchronized block:
• If very few lines of the code required synchronization then it's never recommended to
declare entire method as synchronized we have to enclose those few lines of the code
with in synchronized block.
• The main advantage of synchronized block over synchronized method is it reduces
waiting time of Thread and improves performance of the system.
Example 1: To get lock of current object we can declare synchronized block as follows.
Synchronized(this){}
Example 2: To get the lock of a particular object 'b' we have to declare a synchronized block as
follows.
Synchronized(b ){}
Example 3: To get class level lock we have to declare synchronized block as follows.
Synchronized(Display.class){}
• As the argument to the synchronized block we can pass either object reference or
".class file" and we can't pass primitive values as argument [because lock concept is
dependent only for objects and classes but not for primitives].

251
Example:
Int x=b;
Synchronized(x){}
Output:
Compile time error.
Unexpected type.
Found: int
Required: reference
Questions:
1) Explain about synchronized keyword and its advantages and disadvantages?
2) What is object lock and when a Thread required?
3) What is class level lock and when a Thread required?
4) What is the difference between object lock and class level lock?
5) While a Thread executing a synchronized method on the given object is the remaining
Threads are allowed to execute other synchronized methods simultaneously on the
same object?
Ans: No.
G) What is synchronized block and explain its declaration?
7) What is the advantage of synchronized block over synchronized method?
8) Is a Thread can hold more than one lock at a time?
Ans: Yes, up course from different objects.
Example:
class X class Y
{ {
synchronized void methodOneO synchronized void methodTwoO
{ {}
Y y=new YOi }
y.methodTwoOi
}
}
Diagram:
~t1--I(X)'I(Y)

'\:_) .metnodOneO

8·methodTWOO

9) What is synchronized statement?


Ans: The statements which present inside synchronized method and synchronized block are
called synchronized statements. [Interview people created terminology].

252
Inter Thread communication (waitO,notifyO, notifyAIIO):
• Two Threads can communicate with each other by using wattt), notifvt) and notifyAllO
methods.
• The Thread which is excepting updation it has to call waitO method and the Thread
which is performing updation it has to call notlfvt) method. After getting notification the
waiting Thread will get those updations.
Diagram:

t. t.. strnan

.waitOi
.notifyl);
.notifyAIiOi

3
4
5
6
7

• waitt), notifvf) and notifyAllO methods are available in Object class but not in Thread
class because Thread can call these methods on any common object.
• To call wattf), notifvf) and notifyAllO methods compulsory the current Thread should be
owner of that object that is current Thread should has lock of that object that is current
Thread should be in synchronized area. Hence we can call waitt), notifvt) and notifyAllO
methods only from synchronized area otherwise we will get runtime exception saying
IllegalMonitorStateException.
• Once a Thread calls waitO method on the given object 1st it releases the lock of that
object immediately and entered into waiting state.
• Once a Thread calls notlfvt) (or) notifyAllO methods it releases the lock of that object
but may not immediately.
• Except these (waitO,notifyO,notifyAII()) methods there is no other place(method) where
the lock release will be happen.

253
Method Is Thread Releases Lock?
yield() No
join() No
sleep() No
wait() Yes
notify() Yes
notifyAII() Yes
• Once a Thread calls wait(), notify(), notifyAII() methods on any object then it releases
the lock of that particular object but not all locks it has.
1) public final void waitOthrows Interrupted Exception
2) public final native void wait(long ms)throws InterruptedException
3) public final void wait(long ms,int ns)throws InterruptedException
4) public final native void notifvt)
5) public final void notifyAIiO
Diagram:
1)If waiting Thread got notification.
2) If time expires.

obj.waitf]:
if waiting Thread
obj.wait(1000);
got lock.
obj.wait(1000,100);

if TS allocates CPU

Example 1:
class ThreadA

public static void main(String[] args)throws Interrupted Exception

ThreadB b=new ThreadB();


b.start();
synchronized(b)
{
System.out.println("main Thread calling waitO method");//step-l
b.waitf):
System.out.println("main Thread got notification call");//step-4
System.out.println(b.total);

254
class ThreadB extends Thread

int total=O;
public void runO
{
synchronized(this}
{
System.out.println("child thread starts calcuation"};/ /step-2
for(int i=0;i<=100;i++}
{
tot aI=tota I+i;

System.out.println("child thread giving notification call"};//step-3


this.notifvf):

Output:
main Thread calling waitO method
child thread starts calculation
child thread giving notification call
main Thread got notification call
5050
Example 2:
Producer consumer problem:
• Producer(producer Thread} will produce the items to the queue and
consumer(consumer thread} will consume the items from the queue. If the queue is
empty then consumer has to call waitO method on the queue object then it will entered
into waiting state.
• After producing the items producer Thread call notifvf) method on the queue to give
notification so that consumer Thread will get that notification and consume items.
Diagram:

255
Example:
{
class Producer Consumer()
{ {
Producer() synchronized(q)
{ {
synchronized(q) if(q is empty)
{ {
produce items to the queue q.waitOi
q.notifY()i }
else
} continue items;
}

}
Notify vs notifyAIIO:
• We can use notifvf) method to give notification for only one Thread. If multiple
Threads are waiting then only one Thread will get the chance and remaining Threads
has to wait for further notification. But which Thread will be notify(inform) we can't
expect exactly it depends on JVM.
• We can use notifyAllO method to give the notification for all waiting Threads. All
waiting Threads will be notified and will be executed one by one.
Note: On which object we are calling waitt), notifvl] and notifyAllO methods that corresponding
object lock we have to get but not other object locks.
Example:
Stack sl=new StackOi
Stack s2=new StackOi

synchronized(sl) synchronized(sl)
{ {
111111111 111111111

s2.waitO; sl.waitO;
111111111 111111/11

(invalid) (valid)
R.E:lllegaIMonitorStateException

Dead lock:
• If 2 Threads are waiting for each other forever(without end) such type of
situation(infinite waiting) is called dead lock.
• There are no resolution techniques for dead lock but several prevention(avoidance)
techniques are possible.

256
• Synchronized keyword is the cause for deadlock hence whenever we are using
synchronized keyword we have to take special care.
Example:
class A

public synchronized void foo(B b)

System.out.println("Threadl starts execution of foot) method");


try
{
Thread.sleep(2000);

catch (InterruptedException e)
{}
System.out.println("Threadl trying to call b.lastt)"):
b.lastt):

public synchronized void lastt)


{
System.out.println("inside A, this is last()method");

class B

public synchronized void bar(A a)


{
System.out.println("Thread2 starts execution of barf) method");
try
{
Thread.sleep(2000);

catch (Interrupted Exception e)


{}
System.out.println("Thread2 trying to call a.lastO");
a.lastf):
}
public synchronized void lastt)
{

257
System.out.println("inside B, this is last() method");
}

class DeadLock implements Runnable

A a=new A();
B b=new B();
Dead Lock()
{
Thread t=new Thread(this);
t.start();
a.foo(b);//main thread

public void run()


{
b.bar(a);/ /child thread

public static void main(String[] args)


{
new DeadLock();/ /main thread

Output:
Threadl starts execution of foo() method
Thread2 starts execution of bar() method
Thread2 trying to call a.last()
Threadl trying to call b.last()
/ /here cursor always waiting.

Daemon Threads:
• The Threads which are executing in the background are called daemon Threads. The
main objective of daemon Threads is to provide support for non daemon Threads.
Example:
Garbage collector
• We can check whether the Thread is daemon or not by using isDaemon() method.
public final boolean isDaemonO;
• We can change daemon nature of a Thread by using setDaemon () method.
public final void setDaemon(boolean b);

258
• But we can change daemon nature before starting Thread only. That is after starting the
Thread if we are trying to change the daemon nature we will get R.E saying
IllegalThreadStateException.
• Main Thread is always non daemon and we can't change its daemon nature because it's
already started at the beginning only.
• Main Thread is always non daemon and for the remaining Threads daemon nature will
be inheriting from parent to child that is if the parent is daemon child is also daemon
and if the parent is non daemon then child is also non daemon.
• Whenever the last non daemon Thread terminates automatically all daemon Threads
will be terminated.
Example:
class MyTh read extends Thread

public void run()


{
for(int i=O;i<10;i++)
{
System.out.println("lazy thread");
try
{
Thread.sleep(2000);

catch (Interrupted Exception e)


{}

class DaemonThreadDemo

public static void main(String[] args)


{
MyTh read t=new MyThread();
t.setDaemon(true); 1
t.start();
System.out.println("end of main Thread");
}

259
Output:
End of main Thread
Lazy thread
• If we are commenting line 1 then both main and child Threads are non daemon and
hence both will be executed until they completion.
• If we are not commenting line 1 then main Thread is non daemon and child Thread is
daemon and hence whenever main Thread terminates automatically child Thread will be
terminated.
Deadlock vs Starvation:
• A long waiting of a Thread which never ends is called deadlock.
• A long waiting of a Thread which ends at certain point is called starvation.
• A low priority Thread has to wait until completing all high priority Threads.
• This long waiting of Thread which ends at certain point is called starvation.
How to kill a Thread in the middle of the line?
• We can call stop(] method to stop a Thread in the middle then it will be entered into
dead state immediately.
public final void stopt):
• stop(] method has been deprecated and hence not recommended to use.
suspend and resume methods:
• A Thread can suspend another Thread by using suspendl) method then that Thread will
be paused temporarily.
• A Thread can resume a suspended Thread by using resumeO method then suspended
Thread will continue its execution.
1) public final void suspendt]:
2) public final void resumel):
• Both methods are deprecated and not recommended to use.
RACEcondition:
• Executing multiple Threads simultaneously and causing data inconsistency problems
is nothing but Race condition we can resolve race condition by using synchronized
keyword.

260
Life cycle of a Thread:

Thread.yieldOj
If TS allocates CPU

bj.waitOj
bj.wait(long ms);
obj.wait(long ms,int ns]:

resumeO

What is the difference between extends Thread and implements Runnable?


• Extends Thread is useful to override the public void runt) method of Thread class.
• Implements Runnable is useful to implement public void runO method of Runnable
interface.
Extends Thread, implements Runnable which one is advantage?
• If we extend Thread class, there is no scope to extend another class.
Example:
Class MyClass extends Frame,Thread/ /invalid
• If we write implements Runnable still there is a scope to extend one more class.
Example:
1) class MyClass extends Thread implements Runnable
2) class MyClass extends Frame implements Runnable
How can you stop a Thread which is running?
Step 1:
• Declare a boolean type variable and store false in that variable.
boolean stop=false;
Step 2:
• If the variable becomes true return from the runO method.

261
If(stop) return;
Step 3:
• Whenever to stop the Thread store true into the variable.
System.in.readO;/ /press enter
Obj.stop=true;

Questions:
1) What is a Thread?
2) Which Thread by default runs in every java program?
• Ans: By default main Thread runs in every java program.
3) What is the default priority of the Thread?
4) How can you change the priority number of the Thread?
5) Which method is executed by any Thread?
• Ans: A Thread executes only public void run() method.
6) How can you stop a Thread which is running?
7) Explain the two types of multitasking?
8) What is the difference between a process and a Thread?
9) What is Thread scheduler?
10) Explain the synchronization of Threads?
11) What is the difference between synchronized block and synchronized keyword?
12) What is Thread deadlock? How can you resolve deadlock situation?
13) Which methods are used in Thread communication?
14) What is the difference between notifvt) and notifyAIiO methods?
15) What is the difference between sleept) and waitO methods?
16) Explain the life cycle of a Thread?
17) What is daemon Thread?

262
Java.lang Package
1) Object
2) String
3) Stri ngBuffer
4) StringBuilder
5) Wrapper Classes
6) Autoboxing and Autounboxing
• For writing any java program the most commonly required classes and interfaces are
encapsulated in the separate package which is nothing but java.lang package.
• It is not required to import java.lang package in our program because it is available by
default to every java program.
• The following are some of important classes present in java.lang package.
1. Object
2. String
3. StringBuffer
4. StringBuilder
5. All wrapper classes
6. Execption API
7. Thread API....etc
What is your favorite package?
Why java.lang is your favorite package?
• It is not required to import lang package explicitly but the remaining packages we have
to import.
Java.lang.Object class: For any java object whether it is predefine or customized the most
commonly required methods are encapsulated into a separate class which is nothing but object
class.
• As object class acts as a root (or) parent (or) super for all java classes, by default its
methods are available to every java class.
• The following is the list of all methods present in java.lang Object class.
1) public String tostringt):
2) public native int hashcodet):
3) public boolean equals(Object 0);
4) protected native Object clonetjthrows CloneNotSupportedException;
5) public final Class-ci'> getclasst):
6) protected void finalizetjthrows Throwable;
7) public final void waitOthrows Interrupted Exception;
8) public final native void waitOthrows Interrupted Exception;
9) public final void wait(long rns.int ns)throws Interrupted Exception;

263
10) public final native void notifvf):
11) public final native void notifyAIIO;
toStringO method: We can use this method to get string representation of an object.
• Whenever we are try to print any object reference internally tostringf) method will be
executed.
• If our class doesn't contain toStringO method then Object class toStringO method will be
executed.
Example: System.out.println(sl); -+super(sl.toString());
Example 1:
class Student

String name;
int rollno;
Student(String name,int rollno)
{
this.name=name;
this.rollno=rollno;
}
public static void main(String args[]H
Student sl=new Studentf'Ivijavabhaskar't.Iu.l ):
Student s2=new Student(lbhaskar",102);
System.out.printl n(sl);
System .out. pri ntl n(s1.toStri ngO);
System.out.println(s2);
}
}
Output:
Student@3e2SaS
Student@3e2SaS
Student@19821f
• In the above program Object class tostringf) method got executed which is
implemented as follows.
public String tostrtngf) {
return getClassO.getNameO + "@" + Integer.toHexString(hashCode());
}
• To provide our own String representation we have to override tostringf) method in our
class.
• For example whenever we are try to print student reference to print his a name and roll
no we have to override toStringO method as follows.
public String toStringO{
return name+" "+rollno;

264
• In String class, StringBuffer, StringBuilder, wrapper classes and in all collection classes
toString() method is overridden for meaningful string representation. Hence in our
classes also highly recommended to override tostringt) method.
Example 2:
class Test

public String tostrtngf)


{
return "Test";

public static void main(String[] args){


Integer i=new Integer(10);
String s=new String("bhaskar");
Test t=new TestO;
System.out.println(i);
System.out.printl n(s);
System.out.printl n(t);
}}
Output:
10
Bhaskar
Test
hashCodeO method:
• For every object jvm will generate a unique number which is nothing but hashCode.
• hashCode of an object will be used by jvm while saving objects into HashSet, HashMap,
and Hashtable etc.
• If the objects are stored according to hashCode searching will become very efficient
(The most powerful search algorithm is hashing which will work based on hashCode).
• If we didn't override hashCode() method then Object class hashCode() method will be
executed which generates hashCode based on address of the object but it doesn't mean
hashCode represents address of the object.
• Based on our programming requirement we can override hashCodeO method in our
class.
• Overriding hashCodeO method is said to be proper if and only if for every object we
have to generate a unique number.
Example 3:
class Student class Student
{
public int hashCodeO int rollno;
{ public int hashCode()
return 100; {
}} return rollno;
• It is improper way of overriding }}

265
hashCodeO method because for every • It is proper way of overriding
object we are generating same hashcodeO method because for every
hashcode. object we are generating a different
hashcode.
toStringO method vs hashCodeO method:
class Test class Test{
int i;
int i; Test(int i){
Test(int i) this.i=i;
{ }
this.i=i; public int hashCodeO{
} return i;
public static void main(String[] args){ }
Test tl=new Test(lO); public static void main(String[] args){
Test t2=new Test(lOO); Test tl=new Test(lO);
System.out.println(tl); Test t2=new Test(lOO);
System.out.println(t2); System.out.println(tl);
} System.out.println(t2);
} }}
Object==o+toStringO called. Object==o+toStringO called.
Object==o+hashCodeO called. Test==o+hashCodeO called.
• In this case Object class tostringf) • In this case Object class toStringO
method got executed which is internally method got executed which is
calls Object class hashCodeO method. internally calls Test class hashCodeO
method.
Example 4:
class Test

int i;
Test(int i)
{
this.i=i;
}
public int hashcoderl]
return i;

public String tcStringf]


{
return i+"";

public static void main(String[] args){


Test tl=new Test(lO);
Test t2=new Test(lOO);
System.out.printl n(tl);

266
System.out.println(t2);
}
}
Output:
10
100
• In this case Test class toString() method got executed.
Note: if we are giving optrurniuty to Object class toString() method it internally calls hashCode()
method. But if we are overriding toString() method it may not call hashCode() method.
• We can use toString() method while printing object references and we can use
hashCode() method while saving objects into HashSet or Hashtable or HashMap.
egualsO method:
• We can use this method to check equivalence of two objects.
• If our class doesn't contain .equals() method then object class .equalsO method will be
executed which is always meant for reference compression[address compression].
Example 5:
class Student

String name;
int rollno;
Student(String name,int roll no}
{
this.name=name;
this.rollno=rollno;
}
public static void main(String[] args){
Student sl=new Studentf'Ivijavabhaskar't.Iu.l ):
Student s2=new Student(lbhaskar",102};
Student s3=new Studenti'Vijavabhaskar't.In.l ):
Student s4=sl;
System .out. pri ntl n(s1.equals( s2));
System. out. pri ntl n(s1.equals( s3));
System. out. pri ntl n(s1.equals( s4));
}}
Output:
False
False
True
Diagram:

267
• In the above program Object class .equals() method got executed which is always meant
for reference compression that is if two references pointing to the same object then
only .equals(() method returns true.
• In object class .equals() method is implemented as follows which is meant for reference
compression.
public boolean equals(Object obj) {
return (this == obj);
}
• Based on our programming requirement we can override .equals() method for content
compression purpose.
• While overriding .equals() method we have to consider the following things.
1) Meaning of content compression like whether the names are equal (or) roll numbers
(or) both are equal.
2) If we are passing heterogeneous object our .equals() method should return false that is
we have to handle ClassCastException to return false.
3) If we are providing null argument our .equals() method should return false that is we
have to handle NuliPointerException to return false.
• The following is the proper way of overriding .equals() method for content compression
in Student class.
Example 6:
class Student

String name;
int rollno;
Student(String name,int roll no)
{
this.name=name;
this.rollno=rollno;
}
public boolean equals(Object obj)
{
try{
String name1=this.name;
int rollno1=this.rollno;
Student s2=(Student)obj;
String name2=s2.name;
int rollno2=s2.rollno;
if(name1.equals(name2)&&rollno1==rollno2)
{
return true;
}
else return false;
}

268
catch(ClassCastException e)
{
return false;
}
catch(NullPointerException e)
{
return false;
}
}
public static void main(String[] args){
Student sl=new Studentt'vtjavabhaskar'i.j.O'l ):
Student s2=new Studenti'tbhaskar't.Hlz):
Student s3=new Studentf'Ivijavabhaskar't.Iu.l ):
Student s4=sl;
System .out. pri ntl n(s1.equals( s2));
System. out. pri ntl n(s1.equals( s3));
System .out. pri ntl n(s1.equals( s4));
System. out. pri ntl n(s1.equals( "vijaya bh askar"));
System .out. pri ntl n(s1.equals( nu 11"));
11

}
}
Output:
False
True
True
False
False
Simplified version of .egualsO method:
public boolean equals(Object o){
try{
Student s2=(Student)o;
if(name.equals(s2.name)&&rollno==s2.rollno){
return true;}
else return false;
}
catch(ClassCastException e)
{
return false;
}
catch(NullPointerException e)
{
return false;
}}

269
More simplified version of .egualsO method:
public boolean equals(Object 0)
{
if(this==o)
return true;
if(o instanceof Student)
{
Student s2=(Student)0;
if(name.equals(s2.name)&&rollno==s2.rollno)
return true;
else
return false;
}
return false;
}
Example 7:
class Student

String name;
int rollno;
Student(String name,int rollno)
{
this.name=name;
this.rollno=rollno;
}
public boolean equals(Object 0)
{
if(this==o)
return true;
if( 0 instanceof Student)
{
Student s2=(Student)o;
if(name.equals(s2.name)&&rollno==s2.rollno)
return true;
else
return false;
}
return false;
}
public static void main(String[] args){
Student s=new Studentivljavabhaskar't.Ijrl ):
Integer i=new Integer(lO);
System. out. pri ntl n(s.eq uaIs(i));
}

270
Output:
False
• To make .equals() method more efficient we have to place the following code at the top
inside .equals() method.
if(this==o)
.I return true;
Diagram:
Student s1=new Studenttvijavabhaskar't.Iuf]:
Student s4=s1;

• If 2 references pointing to the same object then .equals() method return true directly
without performing any content compression this approach improves performance of
the system.
Relationship between .equalsO method and ==(double equal operator):
1) If r1==r2 is true then rl.equals(r2) is always true that is if two objects are equal by
double equal operator then these objects are always equal by .equals() method also.
2) If r1==r2 is false then we can't conclude anything about rl.equals(r2) it may return true
(or) false.
3) If rl.equals(r2) is true then we can't conclude anything about r1==r2 it may returns true
(or) false.
4) If rl.equals(r2) is false then r1==r2 is always false.
Differences between == (double equal operator) and .equalsO method?
==(double equal operator) .equals() method
1) It is an operator applicable for both 1) It is a method applicable only for
primitives and object references. object references but not for
primitives.
2) In the case of primitives == (double 2) By default .equals() method present in
equal operator) meant for content object class is also meant for reference
compression, but in the case of object compression.
references -- operator meant for
reference compression.
3) We can't override== operator for 3) We can override .equalst) method for
content compression in object content compression.
references.
4) If there is no relationship between 4) If there is no relationship between
argument types then we will get argument types then .equalsO method
compile time error saying incompatible simply returns false and we won't get
types. any compile time error and runtime
error.
5) For any object reference r, 5) For any object reference r,
r==null is always false. r.equals(null) is also returns false.

271
Note: in general we can use == (double equal operator) for reference compression whereas
.equalsO method for content compression.
Contract between .egualsO method and hashCodeO method:
1) If 2 objects are equal by .equalsO method compulsory their hashcodes must be equal
(or) same. That is
If rl.equals(r2) is true then rl.hascodeO==r2.hashcodeO must be true.
2) If 2 objects are not equal by .equalsO method then there are no restrictions on
hashCodeO methods. They may be same (or) may be different. That is
If rl.equals(r2) is false then rl.hashCodeO==r2.hashCodeO may be same (or) may be
different.
3) If hashcodes of 2 objects are equal we can't conclude anything about .equalsO method it
may returns true (or) false. That is
If rl.hashCodeO==r2.hashCodeO is true then rl.equals(r2) method may returns true (or)
false.
4) If hashcodes of 2 objects are not equal then these objects are always not equal by
.equalsO method also. That is
If rl.hashCodeO==r2.hashCodeO is false then r1.equals(r2) is always false.
• To maintain the above contract between .equalsO and hashCodeO methods whenever
we are overriding .equalsO method compulsory we should override hashCodeO method.
Violation leads to no compile time error and runtime error but it is not good
programming practice.
• Consider the following person class.
Program:
class Person

String name;
int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public boolean equals(Object 0)
{
if(this==o)
return true;
if( 0 instanceof Person)
{
Person p2=(Person)0;
if(name.equals(p2.name)&&age==p2.age)
return true;
else
return false;
}

272
return false;
}
public static void main(String[] args){
Person p1=new Persoru'vtjavabhaskar't.Iufl:
Person p2=new Persoru'vijavabhaskar't.Iut]:
Integer i=new Integer(102);
System.out.printl n(pl.equa Is(p2));
System .out. pri ntl n(p 1.eq uaIs(i));
}}
Output:
True
False
Which of the following is appropriate way of overriding hashCodeO method?

x1)public int hashCodeO ~)public int hashCodeO r)PUbliC int hashCodeO


{ { { 4)Any of the above.
return 100i return age+height: return narne.hashcodelj+age:
} } }

• Based on whatever the parameters we override ".equals() method" we should use same
parameters while overriding hashCode() method also.
Note: in all wrapper classes, in string class, in all collection classes .equalsl] method is
overridden for content compression in our classes also it is highly recommended to override
.equals() method.
Which of the following is valid?
1) If hash Codes of 2 objects are not equal then .equals() method always return false.(valid)
Example:
class Test

int i;
Test(int i)
{
this.i=i;

public int hashCodeO


{
return i;

public String toStringO


{
return i+"";

public static void main(String[] args)


{

273
Test tl=new Test(10);
Test t2=new Test(20);
System.out.println(tl.hashCode());/ /10
System.out.println(t2.hashCode());/ /20
System.out.println(tl.hashCode()==t2.hashCode());/ /false
System .out. pri ntl n(tl.equals(t2));/ /fa Ise

2) If 2 objects are equal by == operator then their hash codes must be same.(valid)
Example:
class Test

int i;
Test(int i)
{
this.i=i;

public int hashCode()


{
return i;

public String toString()


{
return i+"";

public static void main(String[] args)

Test tl=new Test(10);


Test t2=tl;
System.out.println(tl.hashCode());/ /10
System.out.println(t2.hashCode());/ /10
System.out.println(tl==t2);/ /true

3) If == operator returns false then their hash codes{may be same (or) may be different)
must be different.{invalid)
Example:
class Test

int i;
Test(int i)

274
this.i=ii

public int hashCodeO


{
return ii

public String toStringO


{
return i+'!":

public static void main(String[] args)


{
Test t1=new Testf l.O):
Test t2=new Testf l.O):
System.out.println(tl.hashCodeO);/ /10
System.out.println(t2.hashCodeO);/ /10
System.out.println(tl==t2)i/ /false

4) If hashcodes of 2 objects are equal then these objects are always equal by == operator
also.(invalid)
Clone 0 method:
• The process of creating exactly duplicate object is called cloning.
• The main objective of cloning is to maintain backup.
• That is if something goes wrong we can recover the situation by using backup copy.
• We can perform cloning by using c1one() method of Object class.
protected native object cloneO throws CloneNotSupportedException;
Example:
class Test implements Cloneable
{
int i=10;
int j=20;
public static void main(String[] args)throws CloneNotSupportedException
{
Test tl=new Test();
Test t2=(Test)tl.c1one();
t2.i=888;
t2.j=999;
System .out. pri ntl n(tl. i+"---------------" +tl.j);
System .out. pri ntl n(t2. i+"---------------" +t2.j);

275
Output:
10--------------- 20
888---------------999
Diagram:

• We can perform cloning only for Cloneable objects.


• An object is said to be Cloneable if and only if the corresponding class implements
Cloneable interface.
• Cloneable interface present in java.lang package and does not contain any methods. It is
a marker interface where the required ability will be provided automatically by the JVM.
Shallow cloning vs deep cloning:
• The process of creating just duplicate reference variable but not duplicate object is
called shallow cloning.
Example:
Test U=new Test();
Test t2=tl;
Diagram:

• The process of creating exactly independent duplicate object is called deep cloning.
Example:
Test U=new Test();
Test t2=(Test)U.clone();
System.out.printl n(U==t2);/ /false
System.out.println(U.hashCode()==t2.hashCode());/ /false
Diagram:

• Cloning by default deep cloning.


getClassO method:
• This method returns runtime class definition of an object.
Example:
class Test implements Cloneable
{
public static void main(String[] args)throws CloneNotSupportedException
{
Object o=new String("bhaskar");

276
System.out.println("Runtime object type of 0 is :"+o.getClassO.getName());

Output:
Runtime object type of 0 is: java. lang. String

String
Case 1:
String s=new String("bhaskar"); StringBuffer sb=new StringBuffer(lbhaskar");
s.concat("software"); sb.append("software");
System.out.println(s );/ /bhaskar System.out.println(sb);
• Once we create a String object we • Once we created a StringBuffer object
can't perform any changes in the we can perform any changes in the
existing object. If we are try to perform existing object. This behavior is called
any changes with those changes a new mutability of the StringBuffer object.
object will be created. This behavior is Diagram:
called immutability of the String object.
Diagram:

s~

it has no reference that's


why it is eligible for Gc.
Case 2:

String sl=new String("bhaskar"); StringBuffer sbl=new StringBuffer(lbhaskar");


String s2=new String("bhaskar"); StringBuffer sb2=new StringBuffer(lbhaskar");
System.out.println(sl==s2);/ /false System .out. pri ntln(sbl==sb2);/ /false
System.out.println(sl.equals(s2) );/ /true System .out. println(sbl.eq uals(sb2));/ /false
• In String class .equalsO method is • In StringBuffer class .equalsO method
overridden for content compression is not overridden for content
hence if the content is same .equalsO compression hence Object class
method returns true even though .equalsO method got executed which is
objects are different. always meant for reference
compression. Hence if objects are
different .equalsO method returns
false even though content is same.
Case 3:

String s=new String("bhaskar"); String s="bhaskar";


• In this case two objects will be created • In this case only one object will be
one is on the heap the other one is created in SCPand s is always referring
SCP(String constant pool) and s is that object.
always pointing to heap object. Diagram:

277
Diagram: Heap SCP
Heap SCP
s~
s~ ~
Note:
1) Object creation in SCP is always optional 1st JVM will check is any object already created
with required content or not. If it is already available then it will reuse existing object
instead of creating new object. If it is not already there then only a new object will be
created. Hence there is no chance of existing 2 objects with same content on SCPthat is
duplicate objects are not allowed in SCPo
2) Garbage collector can't access SCP area hence even though object doesn't have any
reference still that object is not eligible for GC if it is present in SCPo
3) All SCPobjects will be destroyed at the time of JVM shutdown automatically.
Example 1:
String sl=new String("bhaskar");
String s2=new String("bhaskar");
String s3=lbhaskar";
String s4=lbhaskar";
Diagram:
Heap SCP

Sl~

S2~ L...--~s4

Example 2:
String s=new String("bhaskar");
s.concat("software");
s=s.concat("solutions");
s="bhaskarsoft";
Diagram:
Heap SCP

s~

s~

278
• For every String Constant one object will be created in SCPo Because of runtime
operation if an object is required to create compulsory that object should be placed on
the heap but not SCPo
Example 3:
String sl=new String("spring");
sl.concat("fall");
sl=sl+"winter";
String s2=sl.concat(lsummer");
System.out.printl n(sl);
System.out.printl n(s2);
Diagram:
Heap SCP

Sl~
®
~ ~

Sl~ ~
<E3>
total:8(4+4)
eligible for gc=2

Example:
class StringDemo

public static void main(String[] args)

String sl=new String("you cannot change me!");


String s2=new String("you cannot change me!");
System.out.println(sl==s2);/ /false
String S3="you cannot change me!";
System.out.printl n(sl==s3 );/ /false
String S4="you cannot change me!";
System.out.println (53==54);/ /true
String SS="you cannot "+"change me!";
System.out.println(s3==sS);/ /true
String S6="you cannot ";
String s7=s6+"change me!";
System.out.printl n(s3==s7);/ /false

279
final String s8="you cannot ";
String s9=s8+"change me!";
System.out.println(s3==s9);/ /true
System.out.printl n(s6==s8);/ /true
}

Diagram:
Heap SCP

51 >CYou cannot change m!D


'----53
L-------54
52 --_;>Ci~ you cannot change m!!:>
'---------55
'-----------59
57-->~CYOU cannot change m!!:>
~
L...---56
'------58
Importance of String constant pool (SCP):

B
Diagram:
Voter Re istration Form
Name:IBhaskarReddy I
FatherName: photo
DOB: ~============~
Age: .--

Addr;::e~s~s:::;::=====~~~~~~~~~~2
City:.~========:
State:'-- ---'

Veore

• In our program if any String object is required to use repeatedly then it is not
recommended to create multiple object with same content it reduces performance of
the system and effects memory utilization.
• We can create only one copy and we can reuse the same object for every requirement.
This approach improves performance and memory utilization we can achieve this
by"scp".
• In SCP several references pointing to same object the main disadvantage in this
approach is by using one reference if we are performing any change the remaining
references will be impacted. To parent this sun people declared String objects as
immutable.

280
• According to this once we creates a String object we can't perform any changes in the
existing object if we are trying to perform any changes with those changes a new String
object will be created hence immutability is the main disadvantage of scp.
1) What is the main difference between String and StringBuilder?
2) What is the meaning of immutability and mutability?
3) Explain immutability and mutability with an example?
4) What is SCP?
• A specially designed memory area for the String literals.
5) What is the advantage of SCP?
• Instead of creating a separate object for every requirement we can create only one
object and we can reuse same object for every requirement. This approach improves
performance and memory utilization.
6) What is the disadvantage of SCP?
• In SCPas several references pointing to the same object by using one reference if we are
performing any changes the remaining references will be inflected. To prevent this
compulsory String objects should be immutable. That is immutability is the disadvantage
of SCPo
7) Why SCP like concept available only for the String but not for the StringBuffer?
• As String object is the most commonly used object sun people provided a specially
designed memory area like SCPto improve memory utilization and performance.
• But StringBuffer object is not commonly used object hence specially designed memory
area is not at all required.
8) Why String objects are immutable where as StringBuffer objects are mutable?
• In the case of String as several references pointing to the same object, by using one
reference if we are allowed perform the change the remaining references will be
impacted. To prevent this once we created a String object we can't perform any change
in the existing object that is immutability is only due to SCPo
• But in the case of StringBuffer for every requirement we are creating a separate object
by using one reverence if we are performing any change in the object the remaining
references won't be impacted hence immutability concept is not require for the
StringBuffer.
9) Similar to String objects any other objects are immutable in java?
• In addition to String all wrapper objects are immutable in java.
10) Is it possible to create our own mutable class?
Yes.
11) Explain the process of creating our own immutable class with an example?
12) What is the difference between final and immutability?
13) What is interning of String objects?

281
Interning of String objects:
• By using heap object reference, if we want to corresponding SCP object reference we
should go for intern() method.
Example 1:
class StringlnternDemo

public static void main(String[] args)


{
String sl=new String("bhaskar");
String s2=sl.intern();
String s3=lbhaskar";
System.out.printl n(s2==s3 );/ /true

Diagram:

s3

• If the corresponding object is not there in SCP then intern() method itself will create
that object and returns it.
Example 2:
class StringlnternDemo

public static void main(String[] args)


{
String sl=new String("bhaskar");
String s2=sl.concat(lsoftware");
String s3=s2.intern();
String s4=lbhaskarsoftware";
System.out.printl n(s3==s4 );/ /true

282
Diagram 2:
Hea Sc

Sl~
~

S2~ ~
s3,--------I)("

s4

String class constructors:


1) String s=new Stringt]:
• Creates an empty String Object.
2) String s=new String(String literals);
• To create an equivalent String object for the given String literal on the heap.
3) String s=new String(StringBuffer sb);
• Creates an equivalent String object for the given StringBuffer.
4) String s=new String(char[] ch);
Example:
class StringlnternDemo

public static void main(String[] args)


{
char[] ch={'a','b','c'};
String s=new String(ch);
System.out.println( ch);/ /abc
}
}
5) String s=new String(byte[] b);
• For the given byte[] we can create a String.
Example:
class StringlnternDemo

public static void main(String[] args)


{
byte[] b={lOO,lOl,102};
String s=new String(b);
System.out.println(s);/ /def
}

283
Important methods of String class:
1) public char charAt(int index);
• Returns the character locating at specified index.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="bhaskar";
System.out.println(s.charAt(3));/ /s
System.out.println(s.charAt(lOO));//StringlndexOutOfBoundsException
}

2) public String concat(String str);


Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="bhaskar";
s=s.concat("software");
/ /s=s+"software";
/ /s+="software";
System .out.println(s );/ /bhaskarsoftware
}

• The overloaded "+/1 and "+=/1 operators also meant for concatenation purpose only.
3) public boolean equals(Object 0);
• For content compression where case is important.
• It is the overriding version of Object class .equalsO method.
4) public boolean equalslgnoreCase(String s);
• For content compression where case is not important.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="bhaskar";
System. out. pri ntl n(s.eq uaIs("b haska r"));/ /tru e
System.out.println(s.equalslgnoreCase("BHASKAR"));//true
}

284
Note: We can validate username by using equalslgnoreCaseO method where case is not
important and we can validate password by using .equalsO method where case is important.
5) public String substring(int begin);
• Return the substring from begin index to end of the string.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="vijayabhaskar";
System.out.printl n(s.substri ng(6) );/ /bhaskar
}

6) public String substring(int begin, int end);


• Returns the substring from begin index to end-l index.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="vijayabhaskar";
System.out.println(s.substri ng(6) );/ /bhaskar
System.out.println(s.substring(3,7));/ /ayab
}

7) public int Iengthl]:


• Returns the no of characters present in the string.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="vijayabhaskar";
System.out.println(s.length());/ /13
/ /System.out.println(s.length);/ /compile time error
//StringlnternDemo.java:7: cannot find symbol
/ /svrnbol : variable length
/ /Iocation: class java.lang.String
}

Note: length is the variable applicable for arrays where as lengthO method is applicable for
String object.
8) public String replace(char old,char new);
• To replace every old character with a new character.

285
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="ababab";
System .out.println(s.replace('a',' b'));/ /bbbbbb
}

9) public String toLowerCaseO;


• Converts the all characters of the string to lowercase.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="BHASKAR";
System .out.println(s. toLowerCase() );/ /bhaskar
}

10) public String toUpperCaseO;


• Converts the all characters of the string to uppercase.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="bhaskar";
System.out.println(s.toUpperCase());/ /BHASKAR
}

11) public String trimO


• We can use this method to remove blank spaces present at beginning and end of the
string but not blank spaces present at middle of the String.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s=" bha skar ";
System.out.println(s.trim());/ /bha skar
}

12) public int indexOf(char ch);

286
• It returns index of 1st occurrence of the specified character if the specified character is
not available then return -1.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="vijayabhaskarreddy";
System.out.printl n(s.i ndexOf('a ') );//3
System. out. pri ntl n (s.indexOf( 'z')) ;-1
}

13) public int lastlndexOf(Char ch);


• It returns index of last occurrence of the specified character if the specified character is
not available then return -1.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String s="vijayabhaskarreddy";
System.out.println(s.lastlndexOf('a') );//11
System.out.printl n(s.i ndexOf('z'));/ /-1
}

Note:
• Because runtime operation if there is a change in content with those changes a new
object will be created only on the heap but not in SCPo
• If there is no change in content no new object will be created the same object will be
reused.
Example 1:
class StringlnternDemo
{
public static void main(String[] args)
{
String sl="bhaskar";
String s2=s1.toUpperCase();
Stri ng s3=s1.toLowerCase();
System.out.println(s1==s2);/ /false
System.out.println(s1==s3);/ /true
}

287
Diagram:
Hea

53
Example 2:
class StringlnternDemo
{
public static void main(String[] args)
{
String sl="bhaskar";
String s2=s1.toStringO;
System.out.println(sl==s2);/ /true
}

Diagram:

Hea SCP

s2
Creation of our own immutable class:
• We can create our own immutable classes.
• Once we created an object we can't perform any changes in the existing object. If we
are trying to perform any changes with those changes a new object will be created. If
there is no change in the content then existing object will be reused. This behavior is
called immutability.
Example:
class StringlnternDemo
{
public static void main(String[] args)
{
String sl="bhaskar";
String s2=sl.toUpperCaseO;
String s3=s1.toLowerCaseO;
System.out.println(sl==s2);/ /false
System.out.println(sl==s3);/ /true
}

288
Diagram:
Hea

53
Immutable program:
final class Createlmmutable

private int i;
Createlmmutable(int i)
{
this.i=i;

public Createlmmutable modify(int i)


{
if(this.i==i)
return this;
else
return (new Createlmmutable(i));

public static void main(String[] args)


{
Createlmmutable c1=new Createlmmutable(10);
Createlmmutable c2=c1.modify(100);
Createlmmutable c3=c1.modify(10);
System.out.println( c1==c2);/ /false
System.out.println( c1==c3);/ /true
Createlmmutable c4=cl.modify(100);
System.out.println( c2==c4);/ /false
}

Diagram:

::~ cz-B c4-B


Final vs immutability:
• If we declare a variable as final then we can't perform reassignment for that variable. It
doesn't mean in the corresponding object we can't perform any changes. That is
through final keyword we won't get any immutability that is final and immutability
concepts are different.

289
Example:
class Test

public static void main(String[] args)


{
final StringBuffer sb=new StringBuffer(lbhaskar");
sb.append("software");
System.out.println(sb);/ /bhaskarsoftware
sb=new StringBuffer("solutions");//C.E: cannot assign a value to final variable
sb

• In the above example even though "sb" is final we can perform any type of change in
the corresponding object. That is through final keyword we are not getting any
immutability nature.

Stri ngBuffer
• If the content will change frequently then never recommended to go for String object
because for every change a new object will be created internally.
• To handle this type of requirement we should go for StringBuffer concept.
• The main advantage of StringBuffer over String is, all required changes will be
performed in the existing object only instead of creating new object.
Constructors:
1) StringBuffer sb=new StringBufferO;
• Creates an empty StringBuffer object with default initialcapacity "16/1.

• Once StringBuffer object reaches its maximum capacity a new StringBuffer object will be
created with Newcapacity=(currentcapacity+ 1)*2.
Example:
class StringBufferDemo

public static void main(String[] args)


{
StringBuffer sb=new StringBuffer();
System .out.printl n(sb.capacity());/ /16
sb.append("abcdefghijklmnop");
System.out.printl n(sb.capacity());/ /16
sb.append("q");
System .out.printl n(sb.capacity());/ /34
}

290
2) StringBuffer sb=new StringBuffer(int initialcapacity);
• Creates an empty StringBuffer object with the specified initial capacity.
Example:
class StringBufferDemo

public static void main(String[] args)

StringBuffer sb=new StringBuffer(19);


System.out.println(sb.capacityO);/ /19
}

3) StringBuffer sb=new StringBuffer(String s);


• Creates an equivalent StringBuffer object for the given String with
capacity=s.lengthO+16;
Example:
class StringBufferDemo

public static void main(String[] args)


{
StringBuffer sb=new StringBuffer("bhaskar");
System.out.printl n(sb.capacityO);/ /23
}

Important methods of StringBuffer:


1) public int lengtht):
• Return the no of characters present in the StringBuffer.
2) public int capacitvf):
• Returns the total no of characters but a StringBuffer can accommodate(hold).
3) public char charAt(int index);
• It returns the character located at specified index.
Example:
class StringBufferDemo

public static void main(String[] args)

StringBuffer sb=new StringBuffer("vijayabhaskarreddy");


System.out.println(sb.lengthO );//18
System.out.printl n(sb.capacityO);/ /34

291
System.out.printl n(sb.charAt(14));/ / e
}

4) public void setCharAt(int index,char ch);


• To replace the character locating at specified index with the provided character.
Example:
class StringBufferDemo

public static void main(String[] args)


{
StringBuffer sb=new StringBuffer("vijayabhaska rreddy");
sb.setCharAt(6,'A');
System.out.printl n(sb);
}

5) public StringBuffer append(String s);


public StringBuffer append{int i);
public StringBuffer append{long I);
public StringBuffer append{boolean b); All these are overloaded methods.
public StringBuffer append{double d);
public StringBuffer append{float f);
Example:
class StringBufferDemo

public static void main(String[] args)


{
StringBuffer sb=new StringBufferO;
sb.append("PI value is :");
sb.append(3.14);
sb.append(" this is exactly ");
sb.append(true);
System.out.println(sb);//PI value is :3.14 this is exactly true
}

6) public StringBuffer insert(int index,String s);


public StringBuffer insert{int index,int i);
public StringBuffer insert(int index,long I);
public StringBuffer insert{int index,double d); All are overloaded methods

2 2
public StringBuffer insert(int index,boolean b);
public StringBuffer insert(int index,float f);
• To insert at the specified location.
Example:
class StringBufferDemo

public static void main(String[] args)


{
StringBuffer sb=new StringBuffer("vijaya");
sb.insert( 6,"bhaskar");
sb.insert(13, "9");
System .out.printl n(sb);/ /vijayabhaskar9
}

7) public StringBuffer delete(int begin,int end);


• To delete characters from begin index to end n-l index.
8) public StringBuffer deleteCharAt(int index);
• To delete the character locating at specified index.
Example:
class StringBufferDemo

public static void main(String[] args)


{
StringBuffer sb=new StringBuffer("vijayabhaskar");
System.out.println(sb);/ /vijayabhaskar
sb.delete(6,13);
System.out.println(sb);/ /vijaya
sb.deleteCharAt(S);
System.out.println(sb);/ /vijay
}

9) public StringBuffer reverseO;


Example:
class StringBufferDemo

public static void main(String[] args)


{
StringBuffer sb=new StringBuffer("vijayabhaskar");

293
System.out.printl n(sb);/ /vijayabhaskar
System .out.printl n(sb. reverse() );/ /raksahbayajiv
}

10) public void setLength(int length);


• Consider only specified no of characters and remove all the remaining characters.
Example:
class StringBufferDemo

public static void main(String[] args)


{
StringBuffer sb=new StringBuffer("vijayabhaskar");
sb.setLength(6);
System.out.printl n(sb);/ /vijaya
}

11) public void trimToSizeO;


• To deallocate the extra free memory such that capacity and size are equal.
Example:
class StringBufferDemo

public static void main(String[] args)


{
StringBuffer sb=new StringBuffer(lOOO);
System.out.printl n(sb.capacity());/ /1000
sb. append (" bhaska r");
System .out.printl n(sb.capacity());/ /1000
sb.trimToSize();
System.out.printl n(sb.capacity());/ /7
}

12) public void ensureCapacity(int initialcapacity);


• To increase the capacity dynamically based on our requirement.
Example:
class StringBufferDemo

public static void main(String[] args)


{

294
StringBuffer sb=new StringBufferO;
System .out.printl n(sb.capacityO);/ /16
sb.ensureCapacity(1000);
System.out.printl n(sb.capacityO);/ /1000
}

StringBuilder (I.S)
• Every method present in StringBuffer is declared as synchronized hence at a time only
one thread is allowed to operate on the StringBuffer object due to this, waiting time of
the threads will be increased and effects performance of the system.
• To overcome this problem sun people introduced StringBuilder concept in 1.5v.
• StringBuilder is exactly same as StringBuffer except the following differences.
StringBuffer StringBuilder
1) Every method present in StringBuffer is 1) No method present in StringBuilder is
synchronized. synchronized.
2) At a time only one thread is allow to 2) Multiple Threads are allowed to
operate on the StringBuffer object operate simultaneously on the
hence Stri ngBuffer object is Thread StringBuilder object hence
safe. StringBuilder is not Thread safe.
3) It increases waiting time of the Thread 3) Threads are not required to wait and
and hence relatively performance is hence relatively performance is high.
low.
4) Introduced in 1.0 version. 4) Introduced in 1.5 versions.
String vs StringBuffer vs StringBuilder:
• If the content is fixed and won't change frequently then we should go for String.
• If the content will change frequently but Thread safety is required then we should go for
StringBuffer.
• If the content will change frequently and Thread safety is not required then we should
go for StringBuilder.
Method chaining:
• For most of the methods in String, StringBuffer and StringBuilder the return type is same
type only. Hence after applying method on the result we can call another method which
forms method chaining.
Example:
s.ml0·m20·m30· ....·..·..·..·..··
• In method chaining all methods will be evaluated from left to right.
Example:
class StringBufferDemo

295
public static void main(String[] args)
{
StringBuffer sb=new StringBufferO;
sb. append ("vijaya "). insert( 6, bh askarred dy"). delete( 13,17). reverse().a ppend (" sol utions
II

"). insert(22, "a bcdf"). reverset]:


System.out.println(sb);/ /sfdcbanoitulosvijayabhaskary
}

Wrapper classes
• The main objectives of wrapper classes are:
• To wrap primitives into object form so that we can handle primitives also just like
objects.
• To define several utility functions which are required for the primitives.
Constructors:
• All most all wrapper classes define the following 2 constructors one can take
corresponding primitive as argument and the other can take String as argument.
Example:
1) Integer i=new Integer(10);
2) Integer i=new Integer(1/10");
• If the String is not properly formatted then we will get runtime exception saying
"NumberFormatException" .
Example:
class WrapperClassDemo

public static void main(String[] args)throws Exception


{
Integer i=new Integer("ten");
System.out.println(i);/ /NumberFormatException
}

• Float class defines 3 constructors with float, String and double arguments.
1) Float f=new Float (10.Sf);
2) Float f=new Float (1/10.Sf");
3) Float f=new Float(10.S);
4) Float f=new Float (1/10S');

296
• Character class defines only one constructor which can take char primitive as argument
there is no String argument constructor.
Character ch=new Character(/a');/ /valid
Character ch=new Character(lfaJl);/linvalid
• Boolean class defines 2 constructors with boolean primitive and String arguments.
• If we want to pass boolean primitive the only allowed values are true, false where case
should be lower case.
Example:
Boolean b=new Boolean(true);
IIBoolean bl=new Boolean(True);/ ICE
IIBoolean b=new Boolean(False);//C.E
• If we are passing String argument then case is not important and content is not
important. If the content is case insensitive String of true then it is treated as true in all
other cases it is treated as false.
Example 1:
class WrapperClassDemo

public static void main(String[] args)throws Exception

Boolean bl=new Boolean("true");


Boolean b2=new Boolean("True");
Boolean b3=new Boolean("false");
Boolean b4=new Boolean("False");
Boolean bS=new Boolean("bhaskar");
System.out.println(bl);/ /true
System.out.println(b2);/ /true
System.out.printl n(b3);/ /false
System.out.println(b4);/ /false
System.out.println(bS);/ /false
}

Example 2(for exam purpose):


class WrapperClassDemo

public static void main(String[] args)throws Exception


{
Boolean bl=new Boolean("yes");
Boolean b2=new Boolean("no");

297
System.out.printl n(bl);/ /false
System.out.println(b2);/ /false
System.out.printl n(bl.equa Is(b2) );/ /true
System.out.println(bl==b2);/ /false
}

Wrapper class Constructor summery


Byte byte, String
Short short, String
Integer lnt, String
Long long, String
Float float, String, double
Double double, String
Character char,S~g
Boolean boolean, String
Note:
1) In all wrapper classes toString() method is overridden to return its content.
2) In all wrapper classes .equals() method is overridden for content compression.
Utility methods:
1) valueOf() method.
2) XXXValue() method.
3) parseXxx() method.
4) toString() method.
valueOf() method: We can use valueOf() method to create wrapper object for the given
primitive or String this method is alternative to constructor.
Form 1: Every wrapper class except Character class contains a static valueOf() method to create
wrapper object for the given String.
public static wrapper valueOf(String s);
Example:
class WrapperClassDemo
{
public static void main(String[] args)throws Exception
{
Integer i=lnteger.valueOf(110");
Double d=Double.valueOf(110.5");
Boolean b=Boolean.valueOf(lbhaskar");
System.out.println(i);/ /10
System.out.println( d);/ /10.5
System.out.println(b);/ /false
}

298
Form 2: Every integral type wrapper class (Byte, Short, Integer, and Long) contains the following
valueOfO method to convert specified radix string to wrapper object.
public static Integer valueOf(String s, int ~
~base
Note: the allowed radix range is 2-36.
base 2 0 To 1
base 8 0 To 7
base 10----- 0To 9
base 11 0 To 9,a
base 16 0 To 9,a To f
base 36 0 To 9,a to z

Example:
class WrapperClassDemo

public static void main(String[] args)


{
Integer i=lnteger.valueOf("100",2);
System.out.println(i);/ /4
}

Analysis:

1*0+2*0+4*1

0+0+4=4
Form 3: Every wrapper class including Character class defines valueOfO method to convert
primitive to wrapper object.
public static wrapper valueOf(primitive p);
Example:
class WrapperClassDemo

public static void main(String[] args)throws Exception

Integer i=lnteger.valueOf(10);
Double d=Double.valueOf(10.5);
Boolean b=Boolean.valueOf(true);
System.out.println(i);/ /10
System.out.println( d);/ /10.5

299
System.out.println(b);/ /true
}

Diagram:

valueOfO

xxxValueO method: We can use xxxValueO methods to convert wrapper object to primitive.
• Every number type wrapper class (Byte, Short, Integer, Long, Float, Double) contains the
following 6 xxxValueO methods to convert wrapper object to primitives.
1) public byte byteValueO
2) public short shortValueO
3) public int intValueO
4) public long longValueO
5) public float floatValueO
6) pblic double doubleValueO;
Example:
class WrapperClassDemo

public static void main(String[] args)throws Exception


{
Integer i=new Integer(130);
System.out.printl n(i .byteValue());/ / -126
System.out.println(i.shortValue());/ /130
System.out.println(i.i ntValueO);/ /130
System.out.println(i.longValue());/ /130
System.out.printl n(i. floatVal ue() );//130.0
System.out.println(i.doubleValue());/ /130.0
}

charValueO method: Character class contains charValueO method to convert Character object
to char primitive.
public char charvaluet):
Example:
class WrapperClassDemo
{
public static void main(String[] args)
{
Character ch=new Character(,a');
char c=ch.charvaluef]:

300
System.out.println( c);/ /a
}

booleanValueO method: Boolean class contains booleanValueO method to convert Boolean


object to boolean primitive.
public boolean booleanValueO;
Example:
class WrapperClassDemo

public static void main(String[] args)


{
Boolean b=new Boolean("bhaskar");
boolean bl=b.booleanValueO;
System.out.printl n(bl);/ /false
}

Diagram:

xxxValueO metho

• In total there are 38(6*6+1+1) xxxValueO methods are possible.

parseXxxO method: We can use this method to convert String to corresponding primitive.
Form1: Every wrapper class except Character class contains a static parseXxxO method to
convert String to corresponding primitive.
public static primitive parseXxx(String s);
Example:
class WrapperClassDemo

public static void main(String[] args)


{
int i=1nteger.parselnt(" lO");
boolean b=Boolean.parseBoolean("bhaskar");
double d=Double.parseDouble("10.S");
System.out.println(i);/ /10
System.out.println(b);/ /false
System.out.println( d);/ /10.5
}

301
Form 2: integral type wrapper classes(Byte, Short, Integer, Long) contains the following
parseXxxO method to convert specified radix String form to corresponding primitive.
public static primitive parseXxx(String s,int radix);
Example:
class WrapperClassDemo

public static void main(String[] args)


{
int i=1nteger.parselnt(" 100",2);
System.out.println(i);/ /4
}

Diagram:

parseXxxO

toStringO method: We can use tostrtngt) method to convert wrapper object (or) primitive to
String.
Form 1:
public String tostringt):

• Every wrapper class including Character class contains the above tcStringl] method to
convert wrapper object to String.
• It is the overriding version of Object class toStringO method.
• Whenever we are trying to print wrapper object reference internally this toStringO
method only executed.
Example:
class WrapperClassDemo

public static void main(String[] args)

Integer i=lnteger.valueOf("10");
System.out.println(i);/ /10
System .out.printl n(i. toStringO);/ /10
}

Form 2: Every wrapper class contains a static to'Stringf] method to convert primitive to String.
public static String toString(primitive p);

302
Example:
class WrapperClassDemo
{
public static void main(String[] args)
{
String sl=lnteger.toString(10);
String s2=Boolean.toString(true);
System.out.println(sl);/ /10
System.out.printl n(s2);/ /true
}

Form 3:
• Integer and long classes contains the following static toStringO method to convert the
primitive to specified radix String form.
public static String toString(primitive p,int radix);
Example:
class WrapperClassDemo

public static void main(String[] args)


{
String sl=lnteger.toString(7,2);
String s2=lnteger.toString(17,2);
System.out.println(sl);/ /111
System.out.println(s2);/ /10001
}

Form 4: Integer and Long classes contains the following toXxxStringO methods.
public static String toBinaryString(primitive p);
public static String toOctalString(primitive p);
public static String toHexString(primitive p);
Example:
class WrapperClassDemo

public static void main(String[] args)

String sl=lnteger.toBinaryString(7);
Stri ng s2=lnteger. toOcta IString(10);
String s3=lnteger.toHexString(20);
System.out.println(sl);/ /111
System.out.println(s2);/ /12

303
System.out.println(s3);/ /14
}

Diagram:

toStringO

Dancing between String. wrapper object and primitive:


Diagram:

xxxValueO

valueOfO

• String, StringBuffer, StringBuilder and all wrapper classes are final classes.
• The wrapper classes which are not child class of Number of Boolean and Character.
• The wrapper classes which are not direct class of Object of Byte, Short, Integer, Long,
Float, Double.
• Sometimes we can consider Void is also as wrapper class.
• In addition to String all wrapper objects also immutable in java.

Autoboxing and Autounboxing


• Until 1.4 version we can't provide wrapper object in the place of primitive and primitive
in the place of wrapper object all the required conversions should be performed
explicitly by the programmer.
Example 1:
Program 1:
class AutoBoxingAndUnboxingDemo
{
public static void main(String[] args)
{
Boolean b=new Boolean(true)j
E:\scjp>javac -source 1.4 AutoBoxingAndUnboxingDemo.java
if(~) 1.4V ') AutoBoxingAndUnboxingDemo.java:6: incompatible types
{ ound : java.lang.Boolean
svstem.out.printlntvhello"): required: boolean
}}}

304
Program 2:
class AutoBoxingAndUnboxingDemo

public static void main(String[] args)


{
Boolean b=new Boolean(true);
if(b)
{
System.out.println("hello");
}}}
Output:
Hello
Example 2:
Program 1:
import java.util. *i
class AutoBoxingAndUnboxingDemo
{
public static void main(String[] args)
{
ArrayList I=new ArrayListOi E:\scjp>javac -source 1.4 AutoBoxingAndUnboxingDemo.java
l.add(10)i--------~ .....
~AutoBoxingAndunboxingDemo.java:7: cannot find symbol
..,.symbol : method add(int)
}
location: class java.util.ArrayList
}
Program 2:
import java.util. *;
class AutoBoxingAndUnboxingDemo

public static void main(String[] args)


{
ArrayList I=new ArrayList();
Integer i=new Integer(10);
I.add(i);

• But from 1.5 version onwards we can provide primitive value in the place of wrapper
and wrapper object in the place of primitive all required conversions will be performed
automatically by compiler. These automatic conversions are called Autoboxing and
Autounboxing.

305
Autoboxing: Automatic conversion of primitive to wrapper object by compiler is called
Autoboxing.
Example:
Integer i=lO; [compiler converts "int" to "Integer" automatically by Autoboxing]
• After compilation the above line will become.
Integer i=lnteger.valueOf(lO);
• That is internally Autoboxing concept is implemented by using valueOf() method.
Autounboxing: automatic conversion of wrapper object to primitive by compiler is called
Autounboxing.
Example:
Integer i=new Integer(lO);
Int i=l; [compiler converts "Integer" to "int" automatically by Autounboxing]
• After compilation the above line will become.
Int i=l.intValue();
• That is Autounboxing concept is internally implemented by using xxxValue() method.
Diagram:

Example:
import java.util. *;
class AutoBoxingAndUnboxingDemo
{
static Integer 1=10; @Autoboxing.
public static void main(String[] args)
{
int i=li 0Autounboxing
methodOne(i i
}
public static void methodOne(lnteger )
{
int k=li 0 Autounboxing
System.out.println(k};1110
}

Note: From 1.5 version onwards we can use primitives and wrapper objects interchangly the
required conversions will be performed automatically by compiler.
Example 1:
import java.util, *;
class AutoBoxingAndUnboxingDemo

306
static Integer 1=0;
public static void main(String[] args)
{
int i=l;
System.out.println(i);/ /0

Example 2:
import java.uti!. *j

class AutoBoxingAndUnboxingDemo
{
»<.
static Integer Ij null
public static void main(String[] args)
{
int i'4-' >R.E:NuIiPointerException
Systern·out.println(i)j
L...- ~) int i=l.intValue()j

Example 3:
import java.uti!. *;
class AutoBoxingAndUnboxingDemo

public static void main(String[] args)


{
Integer x=10;
Integer y=x;
++x;
System.out.println(x);/ /11
System.out.println(y);/ /10
System.out.println(x==y);/ /false

Diagram:

307
Note: All wrapper objects are immutable that is once we created a wrapper object we can't
perform any changes in the existing object. If we are trying to perform any changes with those
changes a new object will be created.
Example 4:
import java.util. *;
class AutoBoxingAndUnboxingDemo

public static void main(String[] args)


{
Integer x=new Integer(lO);
Integer y=new Integer(lO);
System.out.println(x==y);/ /false

Diagram:

x-----G
v--0
Example 5:
import java.util. *;
class AutoBoxingAndUnboxingDemo

public static void main(String[] args)


{
Integer x=new Integer(lO);
Integer y=lO;
System.out.println(x==y);/ /false

Diagram:

Example 6:
import java.util. *;
class AutoBoxingAndUnboxingDemo

308
public static void main(String[] args)
{
Integer x=new Integer(lO);
Integer y=x;
System.out.println(x==y);/ /true

Diagram:

Example 7:
import java.util. *;
class AutoBoxingAndUnboxingDemo

public static void main(String[] args)


{
Integer x=lO;
Integer y=lO;
System.out.println(x==y);/ /true

Diagram:

Example 8:
import java.util. *;
class AutoBoxingAndUnboxingDemo

public static void main(String[] args)


{
Integer x=lOO;
Integer y=lOO;
System.out.println(x==y);/ /true

Diagram:

~--e 309
Example 9:
import java.util. *;
class AutoBoxingAndUnboxingDemo

public static void main(String[] args)


{
Integer x=1000;
Integer y=1000;
System.out.println(x==y);/ /false

Diagram:

Conclusions:
• To implement the Autoboxing concept in every wrapper class a buffer of objects will be
created at the time of class loading.
• By Autoboxing if an object is required to create 1st JVM will check whether that object is
available in the buffer or not. If it is available then JVM will reuse that buffered object
instead of creating new object. If the object is not available in the buffer then only a
new object will be created. This approach improves performance and memory
uti lization.
• But this buffer concept is available only in the following cases.
Byte Always
Short -128 To 127
Integer -128 To 127
Long -128 To 127
Character o To 127
Boolean Always
• In all the remaining cases compulsory a new object will be created.

310
Examples:

@ Integer x=127j ® Boolean bl=truej


Integer y=127j Boolean b2=truej
Svstem.out.println(x==v);//true System.out.println(bl==b2)jf ftrue
<y Integer x=128j
@ Double dl=lO.Oj
Integer y=128j
Double d2=lO.Oj
System.out.println(x==Y)jf ffalse
System.out.println(dl==d2)jf ffalse

• Internally Autoboxing concept is implemented by using valueOf() method hence the


above rule applicable even for valueOf() method also.
Examples:

@ Integer x=new Integer(lO); ® Integer x=lnteger.valueOf(10)j


Integer y=new Integer(10)j Integer y=lnteger.valueOf(10);
System.out.println(x==y);//false System.out.println(x==y)i//true

G) Integer x=10j
@ Integer x=10j
Integer y=lnteger.valueOf(10)j
Integer y=10j
System.out.println(x==y);//true
System.out.println(x==y);//true
Note: When compared with constructors it is recommended to use valueOf() method to create
wrapper object.

Overloading with respect to widening. Autoboxing and var-arg methods:


Case 1: Widening vs Autoboxing.
Widening: Converting a lower data type into a higher data type is called widening.
Example:
import java.uti!. *;
class AutoBoxingAndUnboxingDemo

public static void methodOne(long I)


{
System.out.println("widening");

public static void methodOne(lnteger i)


{
System.out.println("autoboxing");

public static void main(String[] args)


{
int x=10;
methodOne(x);

311
Output:
Widening
• Widening dominates Autoboxing.
Case 2: Widening vs var-arg method.
Example:
import java.util. *;
class AutoBoxingAndUnboxingDemo

public static void methodOne(long I)


{
System.out.println("widening");
}
public static void methodOne(int ... i)
{
System.out.println("var-arg method");
}
public static void main(String[] args)
{
int x=10;
methodOne(x);
}

Output:
Widening
• Widening dominates var-arg method.
Case 3: Autoboxing vs var-arg method.
Example:
import java.util. *;
class AutoBoxingAndUnboxingDemo

public static void methodOne(lnteger i)


{
System.out.println("Autoboxing");

public static void methodOne(int ... i)


{
System.out.println("var-arg method ");

312
public static void main(String[] args)
{
int x=10;
methodOne(x);
}
}
Output:
Autoboxing
• Autoboxing dominates var-arg method.
• In general var-arg method will get least priority. That is if no other method matched
then only var-arg method will get chance. It is exactly same as "default" case inside a
switch.
1) Widening
2) Autoboxing
3) Var-arg method.
Case 4:
import java.util. *;
class AutoBoxingAndUnboxingDemo

public static void methodOne(Long I)


{
Svstem.out.printlnfLong"}:

public static void main(String[] args)


{
int x=10;
methodOne(x);

Output:
• methodOne(java.lang.Long) in AutoBoxingAndUnb oxingDemo cannot be applied to (int)

313
Diagram:

• Widening followed by Autoboxing is not allowed in java but Autoboxing followed by


widening is allowed.
Case 5:
import java.uti!. *;
class AutoBoxingAndUnboxingDemo

public static void methodOne(Object 0)


{
Svstem.out.printlnt'Dbject"]:
}
public static void main(String[] args)
{
int x=10;
methodOne(x);
}
}
Output:
Object
Diagram:

Which of the following declarations are valid?


1) Longl=10;(valid)
2) Long 1=10;(invalid)(C.E)
3) Long 1=101;(Autoboxing)
4) Number n=10; (valid)
5) Object 0=10.0; (valid)
6) int i=101; (invalid)(C.E)

314
Java.IO Package
Agenda:
1) File
2) FileWriter
3) FileReader
4) BufferedWriter
5) BufferedReader
6) PrintWriter
File:
File f=new File("abc.txt");
st
• This line 1 checks whether abc.txt file is already available (or) not if it is already
available then "f" simply refers that file. If it is not already available then it won't create
any physical file just creates a java File object represents name of the file.
Example:
import java.io. *;
class FileDemo

public static void main(String[] args)throws IOException


{
File f=new File("cricket.txt");
System .out.printl n(f.exists());/ /false
f.createNewFile();
System.out.println(f.exists());/ /true

• A java File object can represent a directory also.


Example:
import java.io. *;
class FileDemo

public static void main(String[] args)throws IOException


{
File f=new File("cricket123");
System.out.println(f.exists());/ /false
f.mkdir();
System.out.println(f.exists());/ /true

315
Note: in UNIX everything is a file, java "file 10" is based on UNIX operating system hence in java
also we can represent both files and directories by File object only.
File class constructors:
1) File f=new File(String name);
• Creates a java File object that represents name of the file or directory.
2) File f=new File(String subdirname,String name);
• Creates a File object that represents name of the file or directory present in specified
sub directory.
3) File f=new File(File subdir,String name);
Requirement: Write code to create a file named with demo.txt in current working directory.
Program:
import java.io. *;
class FileDemo

public static void main(String[] args)throws 10Exception


{
File f=new File("demo.txt");
f.createNewFileO;

Reauirement: Write code to create a directory named with bhaskar123 in current working
directory and create a file named with abc.txt in that directory.
Program:
import java.io. *;
class FileDemo

public static void main(String[] args)throws 10Exception


{
File fl=new File("bhaskar123");
fl.mkdir();
File f2=new File("bhaskar123","abc.txt");
f2.createNewFileO;

Requirement: Write code to create a file named with demo.txt present in c:\xyz folder.

316
Program:
import java.io. *;
class FileDemo

public static void main(String[] args)throws IOException


{
File f=new File("c:\ \bhaskar"/'demo.txt");
f.createNewFileO;

Import methods of file class:


1) boolean existst]:
• Returns true if the physical file or directory available.
2) boolean createNewFileO;
• This method 1st checks whether the physical file is already available or not if it is already
available then this method simply returns false. If this file is not already available then it
will create a new file and returns true
3) boolean mkdirt]:
4) boolean isFileO;
• Returns true if the File object represents a physical file.
5) boolean isDirectoryO;
6) String[] listO;
• It returns the names of all files and subdirectories present in the specified directory.
7) long Iengtht):
• Returns the no of characters present in the file.
8) boolean deleteO;
• To delete a file or directory.
FileWriter:
• By using FileWriter we can write character data to the file.
Constructors:
FileWriter fw=new FileWriter(String name);
FileWriter fw=new FileWriter(File f);
• The above 2 constructors meant for overriding.
• Instead of overriding if we want append operation then we should go for the following 2
constru ctors.
FileWriter fw=new FileWriter(String name,boolean append);
FileWriter fw=new FileWriter(File f,boolean append);

317
• If the specified physical file is not already available then these constructors will create
that file.
Methods:
1) write(int ch);
• To write a single character to the file.
2) write(char[] ch);
• To write an array of characters to the file.
3) write(String s);
• To write a String to the file.
4) flusht):
• To give the guarantee the last character of the data also added to the file.
S) closet):
• To close the stream.
Example:
import java.io. *;
class FileWriterDemo

public static void main(String[] args)throws IOException


{
FileWriter fw=new FileWriter("cricket.txt",true);
fw.write(98);/ /adding a single character
fw.write("haskar\nsoftware solutions");
fw. write("\n ");
char[] ch={'a','b','c'};
fw.write(ch);
fw.write("\n");
fw.flush();
fw.close();

Output:
Bhaskar
Software solutions
ABC
FileReader: By using FileReader we can read character data from the file.
Constructors:
FileReader fr=new FileReader(String name);
FileReader fr=new FileReader (File f);

318
Methods:
1) int readl):
• It attempts to read next character from the file and return its Unicode value. If the next
character is not available then we will get -1.
2) int read(char[] ch);
• It attempts to read enough characters from the file into chart] array and returns the no
of characters copied from the file into chart] array.
3) void closet):
Approach 1:
import java.io. *;
class FileReaderDemo

public static void main(String[] args)throws IOException

FileReader fr=new FileReader("cricket.txt");


int i=fr.read();
while(i !=-1)
{
System.out.print( (char) i);
i=fr.read();

Output:
Bhaskar
Software solutions
ABC
Approach 2:
import java.io. *;
class FileReaderDemo

public static void main(String[] args)throws IOException


{
File f=new File("crickettxt");
FileReader fr=new FileReader(f);
chart] ch=new char[(int)f.length()];
fr.read(ch);
for(char chl:ch)

319
System.out.print( ch 1);

Output:
VBR
Software solutions.
Usage of FileWriter and FileReader is not recommended because:
1) While writing data by FileWriter compulsory we should insert line separator(\n)
manually which is a bigger headache to the programmer.
2) While reading data by FileReader we have to read character by character which is not
convent to the programmer.
3) To overcome these limitations we should go for BufferedWriter and BufferedReader
concepts.
BufferedWriter:
• By using BufferedWriter object we can write character data to the file.
Constructors:
BufferedWriter bw=new BufferedWriter(writer w);
BufferedWriter bw=new BufferedWriter(writer w,int buffersize);
Note:
• BufferedWriter never communicates directly with the file it should communicates via
some writer object.
Which of the following declarations are valid?
1) BufferedWriter bw=new BufferedWriter(lfcricket.txtJl); (invalid)
2) BufferedWriter bw=new BufferedWriter (new File(lfcricket.txtJl));
(invalid)
Jl
3) BufferedWriter bw=new BufferedWriter (new FileWriter(lfcricket.txt )); (valid)
4)BufferedWriter bw=new BufferedWriter(new BufferedWriter(new FileWriter("cricket.txtJl)))i (valid)
I I > Two level buffering

Methods:
1) write(int ch);
2) write(char[] ch);
3) write(String s);
4) flusht):
5) closet):
6) newlineO;
• Inserting a new line character to the file.

320
• When compared with FileWriter which of the following capability(facility) is available as
method in BufferedWriter.
1) Writing data to the file.(x)
2) Closing the writer.(x)
3) Flush the writer.(x)
4) Inserting newline character. ( v)
Example:
import java.io. *;
class BufferedWriterDemo

public static void main(String[] args)throws IOException


{
FileWriter fw=new FileWriter("cricket.txt");
BufferedWriter bw=new BufferedWriter(fw);
bw.write(100);
bw.newLine();
char[] ch={'a','b','c','d'};
bw.write(ch);
bw.newLine();
bw.write("bhaskar");
bw.newLine();
bw.write("software solutions");
bw.flush();
bw.close();
}

Output:
d
abcd
bhaskar
software solutions
BufferedReader:
• This is the most enhanced(better) Reader to read character data from the file.
Constructors:
BufferedReader br=new BufferedReader(Reader r);
BufferedReader br=new BufferedReader(Reader r,int buffersize);

321
Note:
• BufferedReader can not communicate directly with the File it should communicate via
some Reader object. The main advantage of BufferedReader over FileReader is we can
read data line by line instead of character by character.
Methods:
1) int readl]:
2) int read(char[] ch);
3) String readLineO;
• It attempts to read and return next line from the File. if the next line is not available
then this method returns null.
4) void closet):
Example:
import java.io. *;
class BufferedReaderDemo

public static void main(String[] args)throws IOException


{
FileReader fr=new FileReader("cricket.txt");
BufferedReader br=new BufferedReader(fr);
String line=br.readLineO;
while(line !=null)
{
System.out.printl n(1ine);
line=br.read Linef):

br.closef):
}

Note:
• Whenever we are closing BufferedReader automatically underlying FileReader will be
closed it is not required to close explicitly.

x
I
:;~~sS:'l:i br.~I~se()i
~
I fr.cloSe()il
x
• Even this rule is applicable for BufferedWriter also.
PrintWriter:
• This is the most enhanced Writer to write text data to the file.

322
• By using FileWriter and BufferedWriter we can write only character data to the File but
by using PrintWriter we can write any type of data to the File.
Constructors:
PrintWriter pw=new PrintWriter(String name);
PrintWriter pw=new PrintWriter(File f);
PrintWriter pw=new PrintWriter(Writer w);
• PrintWriter can communicate either directly to the File or via some Writer object also.

Methods:
write(int ch);
write (char[] ch);
write(String s);
flush();
close();
print(char ch);
print (int i);
print (double d);
print (boolean b);
print (String s);
println(char ch);
println (int i);
println(double d);
println(boolean b);
println(String s);
Example:
import java.io. *;
class PrintWriterDemo

public static void main(String[] args)throws IOException


{
FileWriter fw=new FileWriter(lcricket.txt");
PrintWriter out=new PrintWriter(fw);
out.write(100);
out.println(100);
out.println(true);
out.println('c');
out. println("bhaska r");
out.flush();

323
out.close();

Output:
d100
true
c
bhaskar
What is the difference between write(100) and print(100)?
• In the case of write(100) the corresponding character "d" will be added to the File but in
the case of print(100) "lOO" value will be added directly to the File.
Note 1:
1) The most enhanced Reader to read character data from the File is BufferedReader.
2) The most enhanced Writer to write character data to the File is PrintWriter.
Note 2:
1) In general we can use Readers and Writers to handle character data. Where as we can
use InputStreams and OutputStreams to handle binary data(like images, audio files,
video files etc).
2) We can use OutputStream to write binary data to the File and we can use InputStream
to read binary data from the File.
Diagram:
Object

r-:
'e.de'(ACj

OutputSr·mw,;te, Buffe,edW';te,P';",w,;t~:putSt"l amReader BufferedReader

FileWriter
FileReader

324
Requirement: Write a program to perform File merge(combine) operation.
Diagram:

.txt

aaa
bbb
ccc
666
777
888
file3.txt
Program:
import java.io. *;
class FileWriterDemol

public static void main(String[] args)throws IOException


{
PrintWriter pw=new PrintWriter(lfile3.txt");
BufferedReader br=new BufferedReader(new FileReader(lfilel.txt"));
String line=br.readLineO;
while(line !=null)

pw.println(line);
line=br.read Linel):

br=new BufferedReader(new FileReader(lfile2.txt")); ~euse


line=br.readLineO; f
while(line !=null)
{
pw.println(line);
line=br.read Linef):

pw.flushj):
br.closet):
pw.closel):
}

Requirement: Write a program to perform file merge operation where merging should be
performed line by line alternatively.

325
Diagram:
aaa 666
bbb 777

.txt

aaa
666
bbb
777
ccc
888
file3.txt

Program:
import java.io. *;
class FileWriterDemol

public static void main(String[] args)throws IOException

PrintWriter pw=new PrintWriter(lfile3.txt");


BufferedReader brl=new BufferedReader(new FileReader(lfilel.txt"));
BufferedReader br2=new BufferedReader(new FileReader(lfile2.txt"));
String linel=brl.readLineO;
String line2=br2.readLineO;
while(linel!=nullllline2!=null)
{
if(linel!=null)
{
pw.println(linel);
Iinel=brl. read Linet):
}
if(line2!=null)
{
pw.println(line2);
line2=br2.readLineO;
}

pw.flusht):
br l.closel):
brz.closet):
pw.closel):
}

326
Requirement: Write a program to delete duplicate numbers from the file.
Diagram:
555
555
666
666
777
777
555 ~ 444
444
333
333
999
777
999 output.txt
input.txt

Program:
import java.io. *;
class FileWriterDemol

public static void main(String[] args)throws IOException


{
BufferedReader brl=new BufferedReader(new FileReader("input.txt"));
PrintWriter out=new PrintWriter("outputtxt");
String target=brl.readLineO;
while(target !=null)
{
boolean available=false;
BufferedReader br2=new BufferedReader(new FileReader("output.txt"));
String line=br2.readLineO;
while(line !=null)
{
if(target.equals(li ne))
{
available=true;
break;

line=br2.readLineO;

if( available==false)
{
out. println(ta rget);
out.flusht):

target=brl. readl.inef):

327
Requirement: write a program to perform file extraction operation.
Diagram:
111
222
333
444
555

output.txt
Program:
import java.io. *;
class FileWriterDemol

public static void main(String[] args)throws IOException


{
BufferedReader brl=new BufferedReader(new FileReader(linput.txt"));
PrintWriter pw=new PrintWriter(loutput.txt");
String line=brl.readLine();
while(line !=null)
{
boolean available=false;
BufferedReader br2=new BufferedReader(new Filefceadert'tdelete.txtj]:
String target=br2.readLine();
while(target !=null)
{
if(line.equa Is(target))

available=true;
break;

target=br2. readLi ne();

if( ava ilable==false)


{

328
pw.println(line);

line=br1.readLineO;

pw.flusht):

329
SERIALIZATION
1. Introduction.
2. Object graph in serialization.
3. customized serialization.
4. Serialization with respect inheritance.
Serialization: The process of saving (or) writing state of an object to a file is called serialization
but strictly speaking it is the process of converting an object from java supported form to either
network supported form (or) file supported form.
• By using FileOutputStream and ObjectOutputStream classes we can achieve serialization
process.
Diagram:

G -c'> -c'> -c'>


ObjectOutputStream
-;';o:;;:'St~ 0
abc.ser
De-Serialization: The process of reading state of an object from a file is called DeSerialization
but strictly speaking it is the process of converting an object from file supported form (or)
network supported form to java supported form.
• By using FilelnputStream and ObjectlnputStream classes we can achieve DeSerialization.
Diagram:

f-::\
~
<"-<"-~
ObjectlnputStream
~ut~ 0
abc.ser

Example 1:
import java.io. *;
class Dog implements Serializable

int i=10;
int j=20;

330
class SerializableDemo

public static void main(String args[])throws Exception{


Dog d1=new DogO;
System.out.pri ntln ("Serialization started");
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos. writeObject( dl);
System.out.printl n("Serialization ended ");
System.out.printl n(" Deserialization started");
FilelnputStream fis=new FilelnputStream("abc.ser");
ObjectlnputStream ois=new ObjectlnputStream(fis);
Dog d2=(Dog)ois.readObjectO;
System.out.println("Deserialization ended");
System.out.println( d2.i+" II +dz.j):
}
}
Output:
Serialization started
Serialization ended
Deserialization started
Deserialization ended
10 20
Diagram:

dl

d2

abc.ser
Note: We can perform Serialization only for Serilizable objects.
• An object is said to be Serilizable if and only if the corresponding class implements
Serializable interface.

331
• Serializable interface present in java.io package and does not contain any methods. It is
marker interface. The required ability will be provided automatically by JVM.
• We can add any no. Of objects to the file and we can read all those objects from the file
but in which order we wrote objects in the same order only the objects will come back.
That is order is important.
Example2:
import java.io. *;
class Dog implements Serializable

int i=lO;
int j=20;

class Cat implements Serializable

int i=30;
int j=40;

class SerializableDemo

public static void main(String args[])throws Exception{


Dog dl=new DogO;
Cat cl=new Catf):
System.out.println("Serialization started");
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos. writeObject( dl);
oos.writeObject(cl);
System.out.println("Serialization ended ");
System.out.printl n(" Deserialization started");
FilelnputStream fis=new FilelnputStream("abc.ser");
ObjectlnputStream ois=new ObjectlnputStream(fis);
Dog d2=(Dog)ois.readObjectO;
Cat c2=(Cat)ois.readObjectO;
System.out.println("Deserialization ended");
System.out.println( d2.i+" II +d2.j);
System.out.println(c2.i+" "+c2.j);
}
}

332
Output:
Serialization started
Serialization ended
Deserialization started
Deserialization ended
10 20
30 40
Transient keyword:
• While performing serialization if we don't want to serialize the value of a particular
variable then we should declare that variable with "transient" keyword.
• At the time of serialization JVM ignores the original value of transient variable and save
default value.
• That is transient means "not to serialize".
Static Vs Transient:
• static variable is not part of object state hence they won't participate in serialization
because of this declaring a static variable as transient these is no use.
Transient Vs Final:
• final variables will be participated into serialization directly by their values. Hence
declaring a final variable as transient there is no use.
Example 3:
import java.io. *;
class Dog implements Serializable

static transient int i=10;


final transient int j=20;

class SerializableDemo

public static void main(String args[])throws Exception{


Dog d1=new DogO;
FileOutputStream fos=new FileOutputStream(labc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
005. writeObject( dl);
FilelnputStream fis=new Hlelnput'Streamf'labc.ser"):
ObjectlnputStream ois=new ObjectlnputStream(fis);
Dog d2=(Dog)ois.readObjectO;
System.out.println( d2.i+" " +dz.j):
}

333
Output:
10 20
Diagram:

i=lO;

dl

d2

abc.ser

Table'
declaration output
int i=10; 10 ................ 20
int j=20;
transient int i=10; 0................ 20
int j=20;
transient int i=10; 0................ 20
transient static int j=20;
transient final int i=10; 10................ 0
transient int j=20;
transient final int i=10; 10 ................ 20
transient static int j=20;
Object graph in serialization:
• Whenever we are serializing an object the set of all objects which are reachable from
that object will be serialized automatically. This group of objects is nothing but object
graph in serialization.
• In object graph every object should be Serializable otherwise we will get runtime
exception saying "NotSerializableException".
Example 4:
import java.io. *;
class Dog implements Serializable

Cat c=new Cat();


}

334
class Cat implements Serializable

Rat r=new RatO;


}
class Rat implements Serializable

int j=20;

class SerializableDemo

public static void main(String args[])throws Exception{


Dog dl=new DogO;
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStrea m oos= new 0 bjectOutputStrea m (fos);
oos. writeObject( dl);
FilelnputStream fis=new FilelnputStream("abc.ser");
ObjectlnputStream ois=new ObjectlnputStream(fis);
Dog d2=(Dog)ois.readObjectO;
System.out.println(d2.c.r.j);
}

Output:
20
Diagram:

object graph

• In the above example whenever we are serializing Dog object automatically Cat and Rat
objects will be serialized because these are part of object graph of Dog object.

335
• Among Dog, Cat, Rat if at least one object is not serializable then we will get runtime
exception saying "NotSerializableException".
Customized serialization:
Example 5:
import java.io. *;
class Account implements Serializable

String userNameeBhaskar'':
transient String pwd="kajal";

class CustomizedSerializeDemo

public static void main(String[] args)throws Exception{


Account a1=new Account();
System.out.println( a1.userName+ " "+a 1.pwd);
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos. writeObject( a1);
FilelnputStream fis=new Hlelnputstreaml'abc.ser"]:
ObjectlnputStream ois=new ObjectlnputStream(fis);
Account a2=(Account)ois.readObject();
System.out.printl n(a2. userName+ " "+a2. pwd);

Output:
Bhaskar kajal
Bhaskar null
Diagram:

at

Se . liz ble

abc.ser

336
• In the above example before serialization Account object can provide proper username
and password. But after Deserialization Account object can provide only username bur
not password. This is due to declaring password as transient. Hence doing default
serialization there may be a chance of loss of information due to transient keyword.
• We can recover this loss of information by using customized serialization.
• We can implements customized serialization by using the following two methods.
1) private void writeObject(OutputStream os) throws Exception.
• This method will be executed automatically by jvm at the time of serialization.
• It is a callback method. Hence at the time of serialization if we want to perform any
extra work we have to define that in this method only.
2) private void readObject(lnputStream is)throws Exception.
• This method will be executed automatically by JVM at the time of Deserialization. Hence
at the time of Deserialization if we want to perform any extra activity we have to define
that in this method only.
Example 6: Demo program for customized serialization to recover loss of information which is
happen due to transient keyword.
import java.io. *;
class Account implements Serializable

String userName="Bhaskar";
transient String pwd="kajal";
private void writeObject(ObjectOutputStream os)throws Exception

os.defaultWriteObject();
String epwd="123"+pwd;
os.writeObject(epwd);
}
private void readObject(ObjectlnputStream is)throws Exception{
is.defa ultReadObject();
String epwd=(String)is.readObject();
pwd=epwd.substring(3);

class CustomizedSerializeDemo

public static void main(String[] args)throws Exception{


Account a1=new Account();
System.out.printl n(a1.userName+" "+a 1.pwd);

337
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos. writeObject( a1);
FilelnputStream fis=new FilelnputStream("abc.ser");
ObjectlnputStream ois=new ObjectlnputStream(fis);
Account a2=(Account)ois.readObjectO;
System.out.printl n(a2. userName+ " II +a2. pwd);

Output:
Bhaskar kajal
Bhaskar kajal
Diagram:

abc.ser
• At the time of Account object serialization JVM will check is there any writeObjectO
method in Account class or not. If it is not available then JVM is responsible to perform
serialization(default serialization). If Account class contains writeObjectO method then
JVM feels very happy and executes that Account class writeObjectO method. The same
rule is applicable for readObjectO method also.

Serialization with respect to inheritance:


Case 1:
• If parent class implements Serializable then automatically every child class by default
implements Serializable. That is Serializable nature is inheriting from parent to child.
Example 7:
import java.io. *;
class Animal implements Serializable

int i=10;

338
class Dog extends Animal

int j=20;

class SerializableWRTlnheritance

public static void main(String[] args)throws Exception{


Dog d1=new Dogf):
System.out.println( d l.i+" II +d l.j);
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos. writeObject( dl);
FilelnputStream fis=new FilelnputStream("abc.ser");
ObjectlnputStream ois=new ObjectlnputStream(fis);
Dog d2=(Dog)ois.readObjectO;
System.out.println( d2.i+" "+d2.j);
}
}
Output:
10 20
10 20
• Even though Dog class does not implements Serializable interface explicitly but we can
Serialize Dog object because its parent class animal already implements Serializable
interface.
Case 2:

• Even though parent class does not implements Serializable we can serialize child object
if child class implements Serializable interface.
• At the time of serialization JVM ignores the values of instance variables which are
coming from non Serializable parent JVM saves default values for those variables.
• At the time of Deserialization JVM checks whether any parent class is non Serializable or
not. If any parent class is non Serializable JVM creates a separate object for every non
Serializable parent and shares its instance variables to the current object.
• For this JVM always calls no arg constructor(default constructor) of that non Serializable
parent hence every non Serializable parent should compulsory contain no arg
constructor otherwise we will get runtime exception.
Example 8:
import java.io. *;
class Animal

339
int i=10;
Animal(){
System.out.println("Animal constructor called");

class Dog extends Animal implements Serializable

int j=20;
Dog(){
System.out.println("Dog constructor called");

class SerializableWRTlnheritance

public static void main(String[] args)throws Exception{


Dog d1=new Dog();
dl.i=888;
dl.j=999;
FileOutputStream fos=new FileOutputStream(labc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos. writeObject( d1);
System.out.println(" Deserialization started");
FilelnputStream fis=new Hlelnputstreamtabc.ser"]:
ObjectlnputStream ois=new ObjectlnputStream(fis);
Dog d2=(Dog)ois.readObject();
System.out.println( d2.i+
I
••••••••• "+d2.j);
}
}
Output:
Animal constructor called
Dog constructor called
Deserialization started
Animal constructor called
10 999

340
Diagram:

abc.ser

341
Collections
• An array is an indexed collection of fixed no of homogeneous data elements. (or)
• An array represents a group of elements of same data type.
• The main advantage of array is we can represent huge no of elements by using single
variable. So that readability of the code will be improved.
limitations of Object[] array:
1) Arrays are fixed in size that is once we created an array there is no chance of increasing
(or) decreasing the size based on our requirement hence to use arrays concept
compulsory we should know the size in advance which may not possible always.
2) Arrays can hold only homogeneous data elements.
Example:
Student[] s=new Student[10000];
s[O]=new Student();/ /valid
s[l]=new Customer();/ jinvalid(compile time error)
Compile time error:
Test.java:7: cannot find symbol
Symbol: class Customer
Location: class Test
s[l]=new Customer();
3) But we can resolve this problem by using object type array(Object[]).
Example:
Object[] o=new Object[10000];
o[O]=new Student();
o[l]=new Customer();
4) Arrays concept is not implemented based on some data structure hence ready-made
methods support we can't expert. For every requirement we have to write the code
explicitly.
• To overcome the above limitations we should go for collections concept.
1) Collections are growable in nature that is based on our requirement we can increase
(or) decrease the size hence memory point of view collections concept is recommended
to use.
2) Collections can hold both homogeneous and heterogeneous objects.
3) Every collection class is implemented based on some standard data structure hence for
every requirement ready-made method support is available being a programmer we can
use these methods directly without writing the functionality on our own.

342
Differences between Arrays and Collections?
Arrays Collections
1) Arrays are fixed in size. 1) Collections are growable in nature.
2) Memory point of view arrays are not 2) Memory point of view collections are
recommended to use. highly recommended to use.
3) Performance point of view arrays are 3) Performance point of view collections
recommended to use. are not recommended to use.
4) Arrays can hold only homogeneous 4) Collections can hold both
data type elements. homogeneous and heterogeneous
elements.
5) There is no underlying data structure 5) Every collection class is implemented
for arrays and hence there is no based on some standard data structure
readymade method support. and hence readymade method support
is available.
6) Arrays can hold both primitives and 6) Collections can hold only objects but
object types. not primitives.
Collection: If we want to represent a group of objects as single entity then we should go for
collections.
Collection framework: It defines several classes and interfaces to represent a group of objects
as a single entity.
java C++
Collection Containers
Collection framework STL(Standard Template Library)
9(Nine) key interfaces of collection framework:
1. Collection 2. List 3. Set
4. Sorted Set 5. NavigableSet 6. Queue
7. Map 8. SortedMap 9. NavigableMap
Collection:
1) If we want to represent a group of "individual objects" as a single entity then we should
go for collection.
2) In general we can consider collection as root interface of entire collection framework.
3) Collection interface defines the most common methods which can be applicable for any
collection object.
list:
1) It is the child interface of Collection.
2) If we want to represent a group of individual objects as a single entity where "duplicates
are allow and insertion order must be preserved" then we should go for List interface.

343
Diagram:

r /)(l\
CoUeclioo(I)(1.2>")

ArrayList(C)(I.2) LinkedLisI(C)(1.2)
1.0v
legacy classes

• Vector and Stack classes are reengineered in 1.2 versions to implement List interface.
Set:
1) It is the child interface of Collection.
2) If we want to represent a group of individual objects as single entity "where duplicates
are not allow and insertion order is not preserved" then we should go for Set interface.
Diagram:
CoUectioo(l)(1.2v)

Set(D(1.2V)
I
HashSet(C)(1.2V)
»<. So rtedSet(D(1.2 V)

I
LinkedHashSet(C)(1.4V)
I
NavigableSet(l)(1.6V)

I
TreeSet(C)(1.2V)
SortedSet:
1) It is the child interface of Set.
2) If we want to represent a group of "unique objects" according to some sorting order
then we should go for SortedSet.
NavigableSet:
1) It is the child interface of SortedSet.
2) It provides several methods for navigation purposes.
Queue:
1) It is the child interface of Collection.
2) If we want to represent a group of individual objects prior to processing then we should
go for queue concept.

344
Diagram:

CoUectioll(l)(1.2v)

~ ..
PriorityQueue(C) BlockingQueue(I)

r--
~ Prtortrylllocking'QueuerC)

LinkedBlockingQueue(C)

1.5V

Note: All the above interfaces (Collection, List, Set, SortedSet, NavigableSet, and Queue) meant
for representing a group of individual objects.
• If we want to represent a group of objects as key-value pairs then we should go for Map.
Map:
1) Map is not child interface of Collection.
2) If we want to represent a group of objects as key-value pairs then we should go for Map
interface.
3) Duplicate keys are not allowed but values can be duplicated.
Diagram:
l\1np(l)(1.2V)

H.,hMjP(C)(l.,VJ Id,ntl.21 ~'P(I)(1'2v)


I .
Dictionary(AC)

Linked8nshl\1np(C)(1.4V) WeakfiashMap(C)(1.2V) NavirbleMap(l)(l.6V) Hashtable(C)

TreeMap(C)(1.2V)
I
Properties(C)
1.0V

SortedMap:
1) It is the child interface of Map.
2) If we want to represent a group of objects as key value pairs "according to some sorting
order of keys" then we should go for Sorted Map.
NavigableMap:
1) It is the child interface of Sorted Map and defines several methods for navigation
purposes.

345
What is the difference between Collection and Collections?
• "Collection is an "interface" which can be used to represent a group of objects as a
single entity. Whereas "Collections is an utility class" present in java.util package to
define several utility methods for Collection objects.
Coil ectio n--------------------i nterface
CoIIect io ns------------------c lass
• In collection framework the following are legacy characters.
1) Enumeration(l)
2) Dictionary(AC)
3) Vector(C)
4) Stack(C)
5) Hashtable(C)
6) Properties(C)
Diagram:
Collection(I)(1.2V)

List(l)(1.2)

I
An- yList(C)(1.2V) ~
Set(J)(1.2V)
~
.ueue(l)
.
Hasret(C)(1.2V) SortrSet(l)(1.2) Priol"ityQueue(C) BlockingQueue(I)
LinkedList(C)(1.2V)
~ PriorityBlockingQueue(C)
1.0V
LinkedHashSet(C)(1.4v)NavigableSet(l)
I
TreeSet(C)(1.2V)
l LinkedBlockingQueue(C)

1.5V
Diagram:
Map(I)(1.2V)

I
H.,hMap(C)(1.2V) . ?l~
IdenhtyHashMap(C) 1.4V) SOl"tedjap(I)(1.2V) Dictionary(AC)
I .
LinkedHashMap(C)(1.4V) WeakHashMap(C)(1.2V) NaviybleMap(J)(1.6V) Hashtable(C)

TreeMap(C)(1.2V)
I
Properties(C)
1.0V

Collection interface:
• If we want to represent a group of individual objects then we should go for Collection
interface. This interface defines the most common general methods which can be
applicable for any Collection object.
• The following is the list of methods present in Collection interface.
1) boolean add(Object 0);

346
2) boolean addAII(Collection c);
3) boolean remove(Object 0);
4) boolean removeAII(Object 0);
5) boolean retainAII(Collection c);
• To remove all objects except those present in c.
6) Void clear();
7) boolean contains(Object 0);
8) boolean containsAII(Collection c);
9) boolean isEmpty();
10) Int size();
11) Object[] toArray();
12) Iterator iterator();
• There is no concrete class which implements Collection interface directly.
List interface:
• It is the child interface of Collection.
• If we want to represent a group of individual objects where duplicates are allow and
insertion order is preserved. Then we should go for List.
• We can differentiate duplicate objects and we can maintain insertion order by means of
index hence "index play very important role in List".
• List interface defines the following specific methods.
1) boolean add(int index,Object 0);
2) boolean addAII(int index,Collectio c);
3) Object get(int index);
4) Object remove(int index);
5) Object set(int index,Object new);1 Ito replace
6) Int indexOf(Object 0);
• Returns index of first occurrence of "0".
7) Int lastlndexOf(Object 0);
8) Listlterator listlterator();
ArrayList:
1) The underlying data structure is resizable array (or) growable array.
2) Duplicate objects are allowed.
3) Insertion order preserved.
4) Heterogeneous objects are allowed.
5) Null insertion is possible.
Constructors:
1) ArrayList a=new ArrayListO;

347
• Creates an empty ArrayList object with default initial capacity "10" if ArrayList reaches
its max capacity then a new ArrayList object will be created with
New capacity=(current capacity*3/2)+1
2) ArrayList a=new ArrayList(int initialcapacity);
• Creates an empty ArrayList object with the specified initial capacity.
3) ArrayList a=new ArrayList(collection c);
• Creates an equivalent ArrayList object for the given Collection that is this constructor
meant for inter conversation between collection objects. That is to dance between
collection objects.
Demo program for ArrayList:
import java.uti!. *;
class ArrayListDemo

public static void main(String[] args)


{
ArrayList a=new ArrayList();
a.add(IA");
a.add(10);
a.addl''A"}:
a.add(null);
System.out.println(a);//[A, 10, A, null]
a.remove(2);
System.out.println(a);//[A, 10, null]
a.add(2,lm");
a.add("n");
System.out.println(a);//[A, 10, m, null, n]
}

• Usually we can use collection to hold and transfer objects to provide support for this
requirement every collection class implements Serializable and Cloneable interfaces.
• ArrayList and Vector classes implements RandomAccess interface so that any random
element we can access with the same speed.
• RandomAccess interface present in util package and doesn't contain any methods. It is a
marker interface.
Differences between ArrayList and Vector?
ArrayList Vector
1) No method is synchronized 1) Every method is synchronized
2) At a time multiple Threads are allow to 2) At a time only one Thread is allow to

348
operate on ArrayList object and hence operate on Vector object and hence
ArrayList object is not Thread safe. Vector object is Thread safe.
3) Relatively performance is high because 3) Relatively performance is low because
Threads are not required to wait. Threads are required to wait.
4) It is non legacy and introduced in 1.2v 4) It is legacy and introduced in l.Ov
Getting synchronized version of Arraylist object:
• Collections class defines the following method to return synchronized version of List.
Public static list synchronizedlist(list I);
Example:
ArrayList a=new arrayf.isu);
List 11=collections.synchronizedList( a);

I
synchronized
I
nonsynchronized
version version

• Similarly we can get synchronized version of Set and Map objects by using the following
methods.
1) public static Set synchronizedSet(Set s);
2) public static Map synchronizedMap(Map m);
• ArrayList is the best choice if our frequent operation is retrieval.
• ArrayList is the worst choice if our frequent operation is insertion (or) deletion in the
middle because it requires several internal shift operations.
Diagram:

o
l.add(2);
I.remove(3);

linkedlist:
1) The underlying data structure is double LinkedList
2) If our frequent operation is insertion (or) deletion in the middle then LinkedList is the
best choice.
3) If our frequent operation is retrieval operation then LinkedList is worst choice.
4) Duplicate objects are allowed.
5) Insertion order is preserved.
6) Heterogeneous objects are allowed.
7) Null insertion is possible.

349
8) Implements Serializable and Cloneable interfaces but not RandomAccess.
Diagram:

• Usually we can use LinkedList to implement Stacks and Queues to provide support for
this requirement Linked List class defines the following 6 specific methods.
1) void addFirst(Object 0);
2) void addLast(Object 0);
3) Object get+trstt):
4) Object gettastt):
5) Object removeFirstO;
6) Object rernovel.astt):
• We can apply these methods only on LinkedList object.
Constructors:
1) LinkedList I=new Linked List();
• Creates an empty LinkedList object.
2) LinkedList I=new LinkedList(Collection c);
• To create an equivalent LinkedList object for the given collection.
Example:
import java.uti!. *;
class LinkedListDemo

public static void main(String[] args)


{
LinkedList I=new LinkedList();
I.add("bhaskar");
l.add(30);
I.add(null);
I.add("bhaskar");
System.out.println(I);/ /[bhaskar, 30, null, bhaskar]
l.set(O,lsoftware");
System.out.println(I);/ /[software, 30, null, bhaskar]
l.setln'venkv"):
System.out.println(I);/ /[venky, 30, null, bhaskar]
I.removeLast();

350
System.out.println(I);/ /[venky, 3D, null]
I.add First("vvv");
System.out.println(I);/ /[vvv, venky, 3D, null]

Vector:
1) The underlying data structure is resizable array (or) growable array.
2) Duplicate objects are allowed.
3) Insertion order is preserved.
4) Heterogeneous objects are allowed.
5) Null insertion is possible.
6) Implements Serializable, Cloneable and RandomAccess interfaces.
• Every method present in Vector is synchronized and hence Vector is Thread safe.
Vector specific methods:
To add objects:
1) add(Object o);-----Collection
2) add(int index,Object o);-----List
3) addElement(Object o);-----Vector
To remove elements:
1) remove(Object o);--------Collection
2) remove(int index);--------------List
3) removeElement(Object o);----Vector
4) removeElementAt(int index);-----Vector
5) removeAIIElementsO;-----Vector
6) clearO;-------Collection
To get objects:
1) Object get(int index);---------------List
2) Object elementAt(int index);-----Vector
3) Object firstElementO;--------------Vector
4) Object lastElementO;---------------Vector
Other methods:
1) Int sizeO;/ /How many objects are added
2) Int capacityO;//Total capacity
3) Enumeration elernents(}:
Constructors:
1) Vector v=new Vectort):
• Creates an empty Vector object with default initial capacity 10.

351
• Once Vector reaches its maximum capacity then a new Vector object will be created
with double capacity. That is "newcapacitvecurrentcapacitv=Z".
2) Vector v=new Vector(int initialcapacity);
3) Vector v=new Vector(int initialcapacity, int incrementalcapacity);
4) Vector v=new Vector(Coliection c);
Example:
import java.util. *;
class VectorDemo

public static void main(String[] args)


{
Vector v=new Vectcrl):
System.out.println(v.capacity());/ /10
for(int i=1;i<=10;i++)
{
v.addElement(i);

System.out.printl n(v.capacityO);/ /10


v.addElement("A");
System.out.printl n(v.capacityO);/ /20
System.out.println(v);/ /[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]
}

Stack:
1) It is the child class of Vector.
2) Whenever last in first out order required then we should go for Stack.
Constructor:
• It contains only one constructor.
Stack s= new Stackl]:
Methods:
1) Object push(Object 0);
• To insert an object into the stack.
2) Object popt):
• To remove and return top of the stack.
3) Object peekj):
• To return top of the stack without removal.
4) boolean emptvf):
• Returns true if Stack is empty.

352
5) Int search(Object 0);
• Returns offset if the element is available otherwise returns "_1"
Example:
import java.uti!. *;
class StackDemo

public static void main(String[] args)


{
Stack s=new Stack();
s.pusht''A"):
s.pusht'B"):
s.pushfC"]:
System.out.println(s);//[A, B, C]
System.out.println(s.pop());/ /C
System.out.println(s);/ /[A, B]
System.out.println(s.peek());/ /B
Svstern.out.printlnfs.searchf'A'Tk/ /2
System .out.printl rus.searcht''?") );/ /-1
System.out.printl n(s.empty() );/ /false

The 3 cursors of java:


• If we want to get objects one by one from the collection then we should go for cursor.
There are 3 types of cursors available in java. They are:
1) Enumeration
2) Iterator
3) Listlterator
Enumeration:
1) We can use Enumeration to get objects one by one from the legacy collection objects.
2) We can create Enumeration object by using elements() method.
Enumeration e=v.elementsO;
L Vector Object
• Enumeration interface defines the following two methods
1) public boolean hasMoreElementsO;
2) public Object nextElementO;
Example:
import java.uti!. *;
class EnumerationDemo

353
public static void main(String[] args)
{
Vector v=new Vector();
for(int i=0;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v);/ 1[0, 1, 2, 3,4,5,5, 7,8,9, 10]
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer i=(lnteger)e.nextElement();
if(i%2==0)
System.out.println(i);1102 45810
}
System.out.print(v);II[O, 1,2,3,4,5,5,7,8,9, 10]

limitations of Enumeration:
1) We can apply Enumeration concept only for legacy classes and it is not a universal
cursor.
2) By using Enumeration we can get only read access and we can't perform remove
operations.
3) To overcome these limitations sun people introduced Iterator concept in 1.2v.
Iterator:
1) We can use Iterator to get objects one by one from any collection object.
2) We can apply Iterator concept for any collection object and it is a universal cursor.
3) While iterating the objects by Iterator we can perform both read and remove
operations.
• We can get Iterator object by using iterator() method of Collection interface.
Iterator itr=c.iteratorO;
• Iterator interface defines the following 3 methods.
1) public boolean hasNextO;
2) public object nextl]:
3) public void removeO;
Example:
import java.uti!. *;
class IteratorDemo

public static void main(String[] args)


{
ArrayList a=new ArrayList();
for(int i=0;i<=10;i++)
{

354
a.add(i);
}
System.out.println(a);/ 1[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator itr=a.iteratorf):
while(itr. hasNext())
{
Integer i=(lnteger)itr.nextO;
if(i%2==0)
System.out.println(i);IIO, 2, 4, 6, 8, 10
else
itr.rernovef}:
}
System.out.println(a);II[O, 2,4, 6, 8, 10]

limitations of Iterator:
1) Both enumeration and Iterator are single direction cursors only. That is we can always
move only forward direction and we can't move to the backward direction.
2) While iterating by Iterator we can perform only read and remove operations and we
can't perform replacement and addition of new objects.
3) To overcome these limitations sun people introduced listlterator concept.
listlterator:
1) Listlterator is the child interface of Iterator.
2) By using listlterator we can move either to the forward direction (or) to the backward
direction that is it is a bi-directional cursor.
3) While iterating by listlterator we can perform replacement and addition of new objects
in addition to read and remove operations
• By using listlterator method we can create listlterator object.
listlterator itr=l.IistiteratorO;
• Listlterator interface defines the following 9 methods.
1) public boolean hasNextO; }
2) public Object nextt): forward
3) public int nextlndext):
4) public boolean hasPreviousO; }
5) public Object previoust): backward
6) public int previouslndexf):
7) public void rernovet):
8) public void set(Object 0);
9) public void add(Object new);
Example:
import java.util. *;
class ListlteratorDemo

public static void main(String[] args)

355
LinkedList I=new LinkedList();
I.add("balakrishna ");
I.add("venki");
I.add("chiru");
I.add("nag");
System.out.println(I);/ /[balakrishna, venki, chiru, nag]
List Iterato r itr=I.1istlte rator();
while(itr. hasN ext())
{
String s=(String)itr.next();
if( s.eq uaIs(liven ki"))
{
itr.remove();
}
}
System.out.println(I);/ /[balakrishna, chiru, nag]

Case 1:
if(s.equals("chiru") )
{
itr.set("chran ");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chran, nag]
Case 2:
if(s.equals("nag"))
{
itr.add("chitu");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chiru, nag, chitu]
• The most powerful cursor is listlterator but its limitation is it is applicable only for "List
objects".
Compression of Enumeration Iterator and Listlterator?
Property Enumeration Iterator Listlterator
1) Is it legacy? yes no no
2) It is applicable Only legacy Applicable for any Applicable for only list
for? classes. collection object. objects.
3) Moment? Single direction Single direction
Bi-directional.
cursor(forward) cursor(forward

356
4) How to get it? By using By using By using listlteratorO
elementsO method.
iteratorOmethod.
method.
5) Accessibility? Only read. Both read and Read/remove/replace/add.
remove.
6) methods hasMoreElementO hasNextO 9 methods.
nextElementO nextO
removeO
Set interface:
1) It is the child interface of Collection.
2) If we want to represent a group of individual objects where duplicates are not allow and
insertion order is not preserved then we should go for Set interface.
Diagram:
CoUection(l)(1.2v)

I
Set(l)(1.2V)

»<.
HasbSet(C)(1.2V) SortedSet(l)(1.2V)
I . I
LinkedHashSet(C)(1.4 V) NavigableSet(I)(l.6V)

I
TreeSet(C)(1.2V)
• Set interface does not contain any new method we have to use only Collection interface
methods.
HashSet:
1) The underlying data structure is Hashtable.
2) Insertion order is not preserved and it is based on hash code of the objects.
3) Duplicate objects are not allowed.
4) If we are trying to insert duplicate objects we won't get compile time error and runtime
error addt) method simply returns false.
5) Heterogeneous objects are allowed.
6) Null insertion is possible.
7) Implements Serializable and Cloneable interfaces but not RandomAccess.
Constructors:
1) HashSet h=new HashSetO;
• Creates an empty HashSet object with default initial capacity 16 and default fill ratio
0.7S(fill ratio is also known as load factor).
2) HashSet h=new HashSet(int initialcapacity);
• Creates an empty HashSet object with the specified initial capacity and default fill ratio
0.75.

357
3) HashSet h=new HashSet(int initialcapacity,float fill ratio);
4) HashSet h=new HashSet(Coliection c);
Example:
import java.util. *;
class HashSetDemo

public static void main(String[] args)


{
HashSet h=new Hashsett):
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System .out.printl n(h .add("Z") );/ /false
System.out.println(h);//[null, D, B, C, 10, Z]
}

linkedHashSet:
1) It is the child class of HashSet.
2) LinkedHashSet is exactly same as HashSet except the following differences.
HashSet linkedHashSet
1) The underlying data structure is 1) The underlying data structure is a
Hashtable. combination of LinkedList and
Hashtable.
2) Insertion order is not preserved. 2) Insertion order is preserved.
3) Introduced in 1.2 v. 3) Introduced in 1.4v.
• In the above program if we are replacing HashSet with LinkedHashSet the output is [B,
C, D, Z, null, 10].That is insertion order is preserved.
Example:
import java.util. *;
class LinkedHashSetDemo

public static void main(String[] args)


{
LinkedHashSet h=new LinkedHashSetO;
h.add("B");
h.add("C");

358
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z") );/Ifalse
System.out.println(h);II[B, C, D, Z, null, 10]
}

Note: LinkedHashSet and LinkedHashMap commonly used for implementing "cache


applications" where insertion order must be preserved and duplicates are not allowed.
SortedSet:
1) It is child interface of Set.
2) If we want to represent a group of "unique objects" according to some sorting order
then we should go for SortedSet interface.
3) That sorting order can be either default natural sorting (or) customized sorting order.
• SortedSet interface define the following 6 specific methods.
1) Object firstf):
2) Object lastt):
3) SortedSet headSet(Object 0);
• Returns the SortedSet whose elements are <=0.
4) SortedSet tailSet(Object 0);
• It returns the SortedSet whose elements are >=0.
5) SortedSet subset(Object ol,Object 02);
• Returns the SortedSet whose elements are >=olbut <02.
6) Comparator cornparatorf):
• Returns the Comparator object that describes underlying sorting technique.
• If we are following default natural sorting order then this method returns null.
Diagram:

firstO-------------100
last----------------120
headSet(109)----[100,101,104,106]
tailSet(109)------[109,110,120]
sebSet(1 04,11 0)- [104,106,109]
comparatorO-----null

359
TreeSet:
1) The underlying data structure is balanced tree.
2) Duplicate objects are not allowed.
3) Insertion order is not preserved and it is based on some sorting order of objects.
4) Heterogeneous objects are not allowed if we are trying to insert heterogeneous objects
then we will get ClassCastException.
5) Null insertion is possible(only once).
Constructors:
1) TreeSet t=new TreeSetO;
• Creates an empty TreeSet object where all elements will be inserted according to
default natural sorting order.
2) TreeSet t=new TreeSet(Comparator c);
• Creates an empty TreeSet object where all objects will be inserted according to
customized sorting order specified by Comparator object.
3) TreeSet t=new TreeSet(SortedSet s);
4) TreeSet t=new TreeSet(Collection c);
Example 1:
import java.uti!. *;
class TreeSetDemo

public static void main(String[] args)


{
TreeSet t=new TreeSet();
t.add("A");
t.add("a");
t.add("B");
t.add("Z");
t.add("L");
Ilt.add(new Integer(10));IIClassCastException
IIt.add(null);1 INullPointerException
System.out.println(t);/ I[A, B, L, Z, a]
}

Null acceptance:
• For the empty TreeSet as the 1st element "null" insertion is possible but after inserting
that null if we are trying to insert any other we will get NullPointerException.
• For the non empty TreeSet if we are trying to insert null then we will get
NullPointerException.

360
Example 2:
import java.util. *;
class TreeSetDemo

public static void main(String[] args)


{
TreeSet t=new TreeSetf):
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("L"));
t.add(new StringBuffer("B"));
System.out.printl n(t);
}

Output:
Runtime Exception.
• Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuffer cannot
be cast to java.lang.Comparable
• If we are depending on default natural sorting order compulsory the objects should be
homogeneous and Comparable otherwise we will get ClassCastException.
• An object is said to be Comparable if and only if the corresponding class implements
Comparable interface.
• String class and all wrapper classes implements Comparable interface but StringBuffer
class doesn't implement Comparable interface hence in the above program we are
getting ClassCastException.
Comparable interface:
• Comparable interface present in java.lang package and contains only one method
compareToO method.
public int compareTo(Object obj);
Example:
obj1.compareTo(obj2);
Diagram:

361
Example 3:
class Test

public static void main(String[] args)


{
System.out.printl n("A" .compareTo("Z"));/ / -25
System.out.println("Z" .compareTo(" K"));/ /15
System.out.println("A" .compareTo("A") );//0
/ /System.out.println("A" .compareTo(new Integer(10) ));/ /Test.java:8:
compareTo(java.lang.String) in java.lang.String cannot be applied to (java.lang.lnteger)
/ /System.out.println("A" .compareTo(null));/ /NullPointerException

• If we are depending on default natural sorting order then internally JVM will use
compareToO method to arrange objects in sorting order.
Example 4:
import java.util. *;
class Test

public static void main(String[] args)


{
TreeSet t=new TreeSetf):
t.add(10);
t.add(O);
t.add(15);
t.add(10);
System.out.println(t);/ /[0, 10, 15]

compareToO method analysis:


Treeset t=new TreeSetOj
t.add(10)j-------~ [10]
t.add(O)j -ve o.compareTo(10)j [0,10]
() +ve
t.add 15 j 15.compareTo(0)j[O,15,10]
+ve
-------~ 15.compareTo(10)j [0,10,15]
+ve
t.add ()10 j 10.compareTo(0)j ~

[0,10,15]
O(zero)
-------~ 10.compareTo(10)j [0,10,15]

362
• If we are not satisfying with default natural sorting order (or) if default natural sorting
order is not available then we can define our own customized sorting by Comparator
object.
• Comparable meant for default natural sorting order.
• Comparator meant for customized sorting order.
Comparator interface:
• Comparator interface present in java.util package this interface defines the following 2
methods.
1) public int compare(Object obj1,Object Obj2);
Diagram:

2) public boolean equals(Objectobj);

• Whenever we are implementing Comparator interface we have to provide


implementation only for compareO method.
• Implementing equalsO method is optional because it is already available from Object
class through inheritance.
Requirement: Write a program to insert integer objects into the TreeSet where the sorting
order is descending order.
Program:
import java.util. *;
class Test

public static void main(String[] args)


{
TreeSet t=n ew TreeSet( new MyCo m paratorfl) ;------------( l)
t.add(lO);
t.add(O);
t.add(lS);
t.add(S);
t.add(20);
System.out.println(t);/ /[20, is. io. S, 0]

class MyComparator implements Comparator

363
public int compare(Object objl,Object obj2)
{
Integer il=(lnteger)objl;
Integer i2=(lnteger)obj2;
if(il<i2)
return +1;
else if(il>i2)
return -100;
else return 0;

• At line "1" if we are not passing Comparator object then JVM will always calls
compareTo() method which is meant for default natural sorting order(ascending
order)hence in this case the output is [0, 5, 10, 15, 20].
• At line "1" if we are passing Comparator object then JVM calls compare() method of
MyComparator class which is meant for customized sorting order(descending order)
hence in this case the output is [20, 15, 10, 5, 0].
Diagram:
TreeSet t=new TreeSet(new MyComparator())i
t.add(10)i [10]
t.add(O)i +ve ') compare(O,10) [10,0]
t.add(15)i -ve ') compare(15,10) [15,10,0]
t.add(5)i +ve ') compare(5,15) [15,5,10,0]
+ve ') compare(5,10) [15,10,5,0]
_-.....;;v...;;;e--=')~compare(5,O) [15,10,5,0]
t.add(20)i --.....;:')~ compare(20,15) [20,15,10,5,0]
Various alternative implementations of compareO method:
public int compare(Object objl,Object obj2)
{
Integer il=(lnteger)objl;
Integer i2=(lnteger)obj2;
Ilreturn i1.compareTo(i2);/ 1[0,5, 10, 15, 20]
Ilreturn -i1.compareTo(i2);11[20, 15, 10,5,0]
Ilreturn 1[20, 15, 10,5,0]
i2.compareTo(il);/
Ilreturn -i2.compareTo(il);/ 1[0, 5, 10, 15, 20]
Ilreturn -1;//[20, 5,15,0, 10]llreverse of insertion order
Ilreturn +1;//[10, 0,15,5, 20]llinsertion order

364
/ /return 0;/ /[10]and all the remaining elements treated as duplicate.

Requirement: Write a program to insert String objects into the TreeSet where the sorting order
is reverse of alphabetical order.
Program:
import java.uti!. *;
class TreeSetDemo

public static void main(String[] args)


{
TreeSet t=new TreeSet(new MyComparator());
t.add("Roja");
t.add("ShobaRani");
t.add("Raja Kumari");
t.add("Ganga Bhavani");
t.add("Ramulamma");
System.out.println(t);/ /[ShobaRani, Ramulamma, RajaKumari,
GangaBhavani]
}

class MyComparator implements Comparator

public int compare(Object objl,Object obj2)


{
String sl=objl.toStringO;
String s2=(String)obj2;
/ /return s2.compareTo(sl);
return -sl.compareTo(s2);

Requirement: Write a program to insert StringBuffer objects into the TreeSet where the sorting
order is alphabetical order.
Program:
import java.uti!. *;
class TreeSetDemo

public static void main(String[] args)


{

365
TreeSet t=new TreeSet(new MyComparator());
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("K"));
t.add(new StringBuffer("L"));
System.out.println(t);/ I [A, K, L, Z]

class MyComparator implements Comparator

public int compare(Object objl,Object obj2)


{
String sl=objl.toStringO;
String s2=obj2.toStringO;
return sl.compareTo(s2);

Note: Whenever we are defining our own customized sorting by Comparator then the objects
need not be Comparable.
Example: StringBuffer
Requirement: Write a program to insert String and StringBuffer objects into the TreeSet where
the sorting order is increasing length order. If 2 objects having the same length then consider
they alphabetical order.
Program:
import java.util. *;
class TreeSetDemo

public static void main(String[] args)


{
TreeSet t=new TreeSet(new MyComparator());
t.add("A");
t.add(new StringBuffer("ABC"));
t.add(new StringBuffer("AA"));
t.add("xx");
t.add("ABCD");
t.add("A");
System.out.println(t);/ I[A, AA, XX, ABC, ABCD]

366
class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)


{
String sl=obj l.tostringf]:
String s2=obj2.toStringO;
int Il=s Llengthl]:
int 12=s2.lengthO;
if(11<12)
return -1;
else if(11)12)
return 1;
else
return sl.compareTo(s2);

Note: If we are depending on default natural sorting order then the objects should be
"homogeneous and comparable" otherwise we will get ClassCastException. If we are defining
our own sorting by Comparator then objects "need not be homogeneous and comparable".
Comparable vs Comparator:
• For predefined Comparable classes default natural sorting order is already available if
we are not satisfied with default natural sorting order then we can define our own
customized sorting order by Comparator.
• For predefined non Comparable classes [like StringBuffer] default natural sorting order
is not available we can define our own sorting order by using Comparator object.
• For our own classes [like Customer, Student, and Employee] we can define default
natural sorting order by using Comparable interface. The person who is using our class,
if he is not satisfied with default natural sorting order then he can define his own sorting
order by using Comparator object.
Example:
import java.util. *;
class Employee implements Comparable

String name;
int eid;
Employee(String name,int eid)
{

367
this.name=name;
this.eid=eid;

public String tcStringf]


{
return name+"----"+eid;

public int compareTo(Object 0)


{
int eid1=this.eid;
int eid2=((Employee)0).eid;
if(eid1<eid2)
{
return -1;

else if(eid>eid2)
{
return 1;

else return 0;

class CompComp

public static void main(String[] args)


{
Employee e1=new Employee("nag",100);
Employee e2=new Employee("balaiah",200);
Employee e3=new Employee("chiru",SO);
Employee e4=new Employee("venki",lS0);
Employee eS=new Employee("nag",100);
TreeSet tl=new Treesett):
tl.add(e1);
tl.add(e2);
tl.add(e3);
tl.add(e4);
t1.add(eS);
System.out.println(tl);/ /[chiru----SO, nag----lOO, venki----1S0, balaiah----200]

368
TreeSet t2=new TreeSet(new MyComparator());
t2.add(e1);
t2.add(e2);
t2.add(e3);
t2.add(e4);
t2.add(e5);
System.out.println(t2);/ /[balaiah----200, chiru----50, nag----100, venki----150]

class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)


{
Employee e1=(Employee)obj1;
Employee e2=(Employee)obj2;
String sl=e1.name;
String s2=e2.name;
return s1.compareTo(s2);

Compression of Comparable and Comparator?


Coml2arable Coml2arator
1) Comparable meant for default natural 1) Comparator meant for customized
sorting order. sorting order.
2) Present in java.lang package. 2) Present in java.util package.
3) Contains only one method. 3) Contains 2 methods.
compareTo() method. Compare() method.
Equals() method.
4) String class and all wrapper 4) No predefined class implements
Classes implements Comparable Comparator.
interface.
Compression of Set implemented class objects'
Property HashSet Linked HashSet TreeSet
1) Underlying Hashtable. LinkedList Balanced Tree.
Data structure. +Hashtable.
2) Insertion order. Not preserved. Preserved. Not preserved (by
default).
3) Duplicate objects. Not allowed. Not allowed. Not allowed.
4) Sorting order. Not applicable. Not applicable. Applicable.
5) Heterogeneous Allowed. Allowed. Not allowed.

369
objects.
6) Null insertion. Allowed. Allowed. For the empty
TreeSet as the 1st
element null
insertion is possible
in all other cases we
will get NPE.
Map:
1) If we want to represent a group of objects as "key-value" pair then we should go for
Map interface.
2) Both key and value are objects only.
3) Duplicate keys are not allowed but values can be duplicated
4) Each key-value pair is called "one entry".
Diagram:

I~ <[h;;kar ~
<,
/
value object

l..
1__ <,
srmu
.:
/
Key object
one entry

103 prasad [each key- value pair is called entry]

104 sudheer

105 baji

Diagram:
Map(I)(1.2V)

I
H.,hMap(C)(1.2V) . ?l~
IdenhtyHashMap(C) I.4V) SOl"tedjap(I)(1.2V) Dictionary(AC)
I .
L·m k edB as hM
I ap
(C)( V)
1.4 I
WeakHashMap(C)(1.2V) NavigableMap(I)(1.6V) Hashtable(C)

TreeMap(C)(1.2V)
I
Properties(C)
l.OV

• Map interface is not child interface of Collection and hence we can't apply Collection
interface methods here.
• Map interface defines the following specific methods.
1) Object put(Object key.Object value);
• To add an entry to the Map, if key is already available then the old value replaced with
new value and old value will be returned.

370
Example:
import java.util. *;
class Map

public static void main(String[] args)


{
HashMap m=new Hashlvlapf}:
m.put("100","vijay");
System.out.println(m);/ /{100=vijay}
m. put("100", II bhaska r");
System.out.printl n( m);/ /{100=bhaskar}

2) void putAII(Map m);


3) Object get(Object key);
4) Object remove(Object key);
• It removes the entry associated with specified key and returns the corresponding value.
5) boolean containsKey(Object key);
6) boolean containsValue(Object value);
7) boolean isEmptyO;
8) Int sizet):
9) void clearf):
10) Set kevSetf):
• The set of keys we are getting.
11) Collection valuesf):
• The set of values we are getting.
12) Set entrvsetf):
• The set of entryset we are getting.
Entry interface:
• Each key-value pair is called one entry without existing Map object there is no chance of
existing entry object hence interface entry is define inside Map interface(inner
interface).
Example:
interface Map

................. ,

................. /

371
interface Entry

Object getKey(); }
Object getValue(); n Entry we can apply these 3 methods.
Object setValue(Object new);

HashMap:
1) The underlying data structure is Hashtable.
2) Duplicate keys are not allowed but values can be duplicated.
3) Insertion order is not preserved and it is based on hash code of the keys.
4) Heterogeneous objects are allowed for both key and value.
5) Null is allowed for keys(only once) and for values(any number).
Differences between HashMap and Hashtable?
HashMap Hashtable
1) No method is synchronized. 1) Every method is synchronized.
2) Multiple Threads can operate 2) Multiple Threads can't operate
simultaneously on HashMap object and simultaneously on Hashtable object
hence it is not Thread safe. and hence Hashtable object is Thread
safe.
3) Relatively performance is high. 3) Relatively performance is low.
4) Null is allowed for both key and value. 4) Null is not allowed for both key and
value otherwise we will get
NullPointerException.
5) It is non legacy and introduced in 1.2v. 5) It is legacy and introduced in 1.0v.

How to get synchronized version of HashMap:


• By default HashMap object is not synchronized. But we can get synchronized version by
using the following method of Collections class.
public static Map synchronizedMap(Map m1)
Constructors:
1) HashMap m=new Hashlvlapf]:
• Creates an empty HashMap object with default initial capacity 16 and default fill ratio
"07SJl

2) HashMap m=new HashMap(int initialcapacity);


3) HashMap m =new HashMap(int initialcapacity, float fillratio);
4) HashMap m=new HashMap(Map m);

372
Example:
import java.util. *;
class HashMapDemo

public static void main(String[] args)


{
HashMap m=new Hashlvlapf}:
m.put("chiranjeevi",700);
m.put("balaiah",800);
m. put("ven katesh ,200);
II

m.put("nagarjuna",500);
System.out.println(m);/ /{nagarjuna=500, venkatesh=200, balaiah=800,
chiranjeevi=700}
System.out.println(m. put("ch iranjeevi" ,100) );//700
Set s=m.kevsetf]:
System.out.println(s);//[nagarjuna, venkatesh, balaiah, chiranjeevi]
Collection c=m.valuesfl:
System.out.println(c);/ /[500,200,800, 100]
Set sl=m.entrySetO;
System.out.println(sl);/ /[nagarjuna=500, venkatesh=200, balaiah=800,
chiranjeevi=100]
Iterator itr=sl.iteratorO;
while(itr.hasNextO)
{
Map.Entry m1=(Map.Entry)itr.nextO;

System.out.println(m1.getKeyO+" "+ml.getValueO);/ /nagarjuna .500


/ /venkatesh 200
/ /balaiah 800
/ / ch ira njeevi 100
if( m 1.getKey() .eq uaIs( nagarj u na"))
II

{
ml.setValue(1000);

System.out.println(m);//{nagarjuna=1000, venkatesh=200, balaiah=800,


chiranjeevi=100}

373
Linkedl+ashlvlan:
HashMap LinkedHashMap
1) The underlying data structure is 1) The underlying data structure is a
Hashtable. combination of Hashtable+ LinkedList.
2) Insertion order is not preserved. 2) Insertion order is preserved.
3) introduced in 1.2.v. 3) Introduced in 1.4v.
Note: in the above program if we are replacing HashMap with LinkedHashMap then the output
is {chiranjeevi=100, balaiah 800, venkatesh 200, nagarjuna 1000} that is insertion
order is preserved.
Note: in general we can use LinkedHashSet and LinkedHashMap for implementing cache
applications.
IdentityHashMap:
1) It is exactly same as HashMap except the following differences.
2) In the case of HashMap JVM will always use ".equalsO"method to identify duplicate
keys.
3) But in the case of IdentityHashMap JVM will use== (double equal operator) to identify
duplicate keys.
Example:
import java.uti!. *;
class HashMapDemo

public static void main(String[] args)


{
HashMap m=new Hashlvlapi}:
Integer i1=new Integer(10);
Integer i2=new Integer(10);
m.put(i1,"pavan");
m.put(i2,"kalyan");
System.out.println(m);

• In the above program i1 and i2 are duplicate keys because i1.equals(i2) returns true.
• In the above program if we replace HashMap with IdentityHashMap then i1 and i2 are
not duplicate keys because i1==i2 is false hence in this case the output is {10=pavan,
10=kalyan}.
System.out.printl n( m.get(10));/ In ull
10==i 1------false
10==i2------false

374
WeakHashMap:
• It is exactly same as HashMap except the following differences.
• In the case of normal HashMap, an object is not eligible for GC even though it doesn't
have any references if it is associated with HashMap. That is HashMap dominates
garbage collector.
• But in the case of WeakHashMap if an object does not have any references then it's
always eligible for GC even though it is associated with WeakHashMap that is garbage
collector dominates WeakHashMap.
Example:
import java.util, *;
class WeakHashMapDemo

public static void main(String[] args)throws Exception


{
WeakHashMap m=new WeakHashMapO;
Temp t=new Temp(]:
m.put(t, "bhaskar");
System.out.println(m);/ I{Temp=bhaska r}
t=null;
Svstern.gcf):
Thread.sleep(SOOO);
System.out.println(m);/ In

class Temp

public String tostrlngf)


{
return "Temp";

public void finalizeO

System.out.println("finalizeO method called");

Output:
{Temp=bhaskar}
finalizeO method called

375
{}
Diagram:

hhesl(ar

• In the above program if we replace WeakHashMap with normal HashMap then object
won't be destroyed by the garbage collector in this the output is
{Temp=bhaskar}
{Temp=bhaskar}
SortedMap:
• It is the child interface of Map.
• If we want to represent a group of key-value pairs according to some sorting order of
keys then we should go for SortedMap.
• Sorting is possible only based on the keys but not based on values.
• SortedMap interface defines the following 6 specific methods.
1) Object firsyKeyO;
2) Object lastkevt):
3) SortedMap headMap(Object key);
4) SortedMap tailMap(Object key);
5) SortedMap subMap(Object key1,Object key2);
6) Comparator comparatort):
TreeMap:
1) The underlying data structure is RED-BLACKTree.
2) Duplicate keys are not allowed but values can be duplicated.
3) Insertion order is not preserved and all entries will be inserted according to some
sorting order of keys.
4) If we are depending on default natural sorting order keys should be homogeneous and
Comparable otherwise we will get ClassCastException.
5) If we are defining our own sorting order by Comparator then keys can be heterogeneous
and non Comparable.

376
6) There are no restrictions on values they can be heterogeneous and non Comparable.
7) For the empty TreeMap as first entry null key is allowed but after inserting that entry if
we are trying to insert any other entry we will get NullPointerException.
8) For the non empty TreeMap if we are trying to insert an entry with null key we will get
NullPointerException.
9) There are no restrictions for null values.
Constructors:
1) TreeMap t=new Treelvlapl]:
• For default natural sorting order.
2) TreeMap t=new TreeMap(Comparator c);
• For customized sorting order.
3) TreeMap t=new TreeMap(SortedMap m);
4) TreeMap t=new TreeMap(Map m);
Example 1:
import java.util. *;
class TreeMapDemo

public static void main(String[] args)


{
TreeMap t=new Treelvlapf):
t.put(100, "ZZZ");
t.put(103, "YYY");
t.put(101, "XXX");
t.put(104,106);
t.put(107,null);
I/t.putt" FFF","XXX");/ /ClassCastException
I It.put(null, "xxx");1 IN ull PointerException
System.out.println(t);/ 1{100=ZZZ, 101=XXX, 103=YYY, 104=106, 107=null}

Example 2:
import java.util. *;
class TreeMapDemo

public static void main(String[] args)


{
TreeMap t=new TreeMap(new MyComparator());
t.put("XXX",10);

377
t.put(IAAA",20);
t.put(IZZZ",30);
t.put(ILLL",40);
System.out.println(t);/ /{ZZZ=30, XXX=10, LLL=40, AAA=20}

class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)


{
String sl=obj l.tostringf]:
String s2=obj2.toStringO;
return s2.compareTo(sl);

Hashtable:
1) The underlying data structure is Hashtable.
2) Insertion order is not preserved and it is based on hash code of the keys.
3) Heterogeneous objects are allowed for both keys and values.
4) Null key (or) null value is not allowed otherwise we will get NullPointerException.
5) Duplicate keys are allowed but values can be duplicated.
Constructors:
1) Hashtable h=new Hashtablef):
• Creates an empty Hashtable object with default initialcapacity 11 and default fill ratio
0.75.
2) Hashtable h=new Hashtable(int initialcapacity);
3) Hashtable h=new Hashtable(int initialcapacitv.float fillratio);
4) Hashtable h=new Hashtable (Map m);
Example:
import java.util. *;
class HashtableDemo

public static void main(String[] args)


{
Hashtable h=new Hashtablef):
h.put(new Temp(5),IA");
h.put(new Temp(2),IB");
h.put(new Temp(6),IC");

378
h.put(new Temp(lS),"D");
h.put(new Temp(23),"E");
h.put(new Temp(16),"F");
System.out.println(h);//{6=C, 16=F, S=A, lS=D, 2=B, 23=E}

class Temp

int i;
Temp(int i)
{
this.i=i;

public int hashCode()


{
return i;

public String toString()


{
return i+"";

Diagram:

10
9
8
7
6 6=C

5 5=A 16=F
4 15=0
3
2 2=B
1 23=E
0

Note: if we change hasCode() method of Temp class as follows.


public int hashCode()
{

379
return i%9;

• Then the output is {16=F, 15=D, 6=(, 23=E, 5=A, 2=B}.


Diagram:
10
9
8
7 16=F
6 6=C,lS=0
S S=A,23=E
4
3
2 2=8
1
0

Note: if we change initial capacity as 25.


Hashtable h=new Hashtable(25);
Diagram:
24
23 23=E
22
21
20
19
18
17
16 16=F
15 15=0
14
13

12
11
10
9
8
7
6 6=C

5 5=A

4
3
2 2=8
1
0

Properties:
1) Properties class is the child class of Hashtable.
2) If anything which changes frequently such type of values not recommended to hardcode
in java application because for every change we have to recompile, rebuild and

380
redeployed the application and even server restart also required sometimes it creates a
big business impact to the client.
3) Such type of variable things we have to hardcode in property files and we have to read
the values from the property files.
4) The main advantage in this approach is if there is any change in property files
automatically those changes will be available to java application just redeployment is
enough.
5) By using Properties object we can read and hold properties from property files into java
application.
Constructor:
Properties p=new PropertiesO;
• In properties both key and value "should be String type only".
Methods:
1) String getPrperty(String propertyname) ;
• Returns the value associated with specified property.
2) String setproperty(String propertvnarne.String propertyvalue);
• To set a new property.
3) Enumeration propertyNamesO;
4) void loadtlnputstream is);/ / Any InputStream we can pass.
• To load Properties from property files into java Properties object.
5) void store(OutputStream os.String comment);! / Any OutputStream we can pass.
• To store the properties from Properties object into properties file.
Diagram:

Properties
object storelO tputStream os String comment)

property file
Example:
import java.uti!. *;
import java.io. *;
class Properties Demo

public static void main(String[] args)throws Exception


{
Properties p=new Propertiest):
FilelnputStream fis=new Hlelnput'Strearnf'labc.properties"):

381
p.load(fis);
System.out.println(p);/ /{user=scott, password=tiger, venki=8888}
String s=p.getProperty("venki");
System.out.println(s);/ /8888
p.setProperty("nag", "9999999");
Enumeration e=p.propertyNames();
while(e.hasMoreElements())
{
String sl=(String)e.nextElement();
System.out.println(sl);/ /nag
//user
//password
//venki

FileOutputStream fos=new FileOutputStream("abc.properties");


p.storetfos.l'updated by bhaskar for scjp demo class");

Property file:
user=scott
nag=9999999
password=tiger
venki=8888

abc.properties
1.5 enhancements (Queue interface)
1) If we want to represent a group of individual objects prior (happening before something
else) to processing then we should go for Queue interface.
Diagram:
Collection{I)(1.2)

/ ~U.(IJ

List{I)(1.2) /">;
PriorityQueue (C) BlockingQueue(l)

~ PriorityBlockingQueue (C)
ArrayList{C)(l.2) LinkedList{C)(1.2) ~LinkedBlockingQueUe(c)
2) Usually Queue follows first in first out order but based on our requirement we can
implement our own order also.
3) From 1.Sv onwards LinkedList also implements Queue interface.

382
4) LinkedList based implementation of Queue always follows first in first out order.
Queue interface methods:
1) boolean after(Object 0);
• To add an object to the Queue.
2) Object pollf}:
• To remove and return head element of the Queue, if Queue is empty then we will get
null.
3) Object rernovet):
• To remove and return head element of the Queue. If Queue is empty then this method
raises Runtime Exception saying NoSuchElementException.
4) Object peekt):
• To return head element of the Queue without removal, if Queue is empty this method
returns null.
5) Object elernentt):
• It returns head element of the Queue and if Queue is empty then it will raise Runtime
Exception saying NoSuchElementException.
PriorityQueue:
1) We can use PriorityQueue to represent a group of individual objects prior to processing
according to some priority.
2) The priority order can be either default natural sorting order (or) customized sorting
order specified by Comparator object.
3) If we are depending on default natural sorting order then the objects must be
homogeneous and Comparable otherwise we will get ClassCastException.
4) If we are defining our own customized sorting order by Comparator then the objects
need not be homogeneous and Comparable.
5) Duplicate objects are not allowed.
6) Insertion order is not preserved but all objects will be inserted according to some
priority.
7) Null is not allowed even as the 1st element for empty PriorityQueue.
Constructors:
1) PriorityQueue q=new PriorityQueueO;
• Creates an empty PriorityQueue with default initial capacity 11 and default natural
sorting order.
2) PriorityQueue q=new PriorityQueue(int initialcapacitv.Cornparator c);
3) PriorityQueue q=new PriorityQueue(int initialcapacity);
4) PriorityQueue q=new PriorityQueue(Collection c);
5) PriorityQueue q=new PriorityQueue(SortedSet s);

383
Example 1:
import java.util. *;
class PriorityQueueDemo

public static void main(String[] args)


{
PriorityQueue q=new PriorityQueueO;
/ /System.out.println(q.peekO);/ /null
/ /System.out.println(q.elementO);/ /NoSuchElementException
for(int i=O;i<=lO;i++)

q.offer(i);

System.out.println(q);/ /[0, 1,2,3,4,5,6, 7, 8, 9, 10]


System.out.println( q.poIIO);/ /0
System.out.println(q);/ /[1, 3, 2, 7, 4, 5, 6, 10,8,9]
}

Note: Some platforms may not provide proper supports for PriorityQueue [windowsXP].
Example 2:
import java.util. *;
class PriorityQueueDemo

public static void main(String[] args)


{
PriorityQueue q=new PriorityQueue(15,new MyComparator());
q.offert''A"]:
q.offert"Z"):
q.ottert"t"):
q.offertB"):
System.out.println(q);//[Z, B, L, A]
}

class MyComparator implements Comparator

public int compare(Object objl,Object obj2)


{
String sl=(String)objl;

384
String s2=obj2.toStringO;
return s2.compareTo(sl);

1.6v Enhancements (NavigableSet and NavigableMap)


NavigableSet:
1) It is the child interface of SortedSet.
2) It provides several methods for navigation purposes.
Diagram:
Collection(I)(1.2)

I
Set(I)(1.2)

I
SortedSet(l) (1.2)

I
N avigablcSet(J)(J .6)

I
TreeSel (C)(1.2)

• NavigableSet interface defines the following methods.


1) ceiling(e);
• It returns the lowest element which is >=e.
2) higher(e);
• It returns the lowest element which is >e.
3) floor(e);
• It returns highest element which is <=e.
4) lower(e);
• It returns height element which is <e.
5) poliFirst 0;
• Remove and return i" element.
6) pollLast 0;
• Remove and return last element.
7) descendingSet 0;
• Returns SortedSet in reverse order.

385
Diagram:

2000

3000

4000
5999
Example:
import java.util. *;
class NavigableSetDemo

public static void main(String[] args)


{
TreeSet<lnteger> t=new TreeSet<lnteger>O;
t.add(1000);
t.add(2000);
t.add(3000);
t.add(4000);
t.add(SOOO);
System.out.println(t);/ /[1000, 2000, 3000, 4000, 5000]
System.out.println(t.ceiling(2000));/ /2000
System.out.printl n(t.h igher(2000) );//3000
System.out.println(t.floor(3000));/ /3000
System.out.printl n(t.lower(3000) );//2000
System .out. pri ntl n(t. poll First());/ /1000
System.out.printl n(t.poIILastO );//5000
System.out.println(t.descendingSetO);/ /[4000,3000, 2000]
System.out.println(t);/ /[2000, 3000, 4000]
}

NavigableMap:
• It is the child interface of SortedMap and it defines several methods for navigation
purpose.

386
Diagram:
Map(I)(1.2)

I
SortedMap(I)(1.2)

I
NavigableMap(I)(1.6)

I
TreeMap(C)(1.2)
• NavigableMap interface defines the following methods.
1) ceilingKey(e);
2) higherKey(e);
3) floorKey(e);
4) lowerKey(e);
5) pollFirstEntryO;
6) poll tastfntrvf):
7) descendinglvlapt]:
Example:
import java.util. *;
class NavigableMapDemo

public static void main(String[] args)


{
Tree M ap<Stri ng,Stri ng> t=new Tree Map<Stri ng,Stri ng>();
t.put("b","banana");
t.put("c","cat");
t.put("a","apple");
t.put("d","dog");
t.put("g","gun");
System.out.println(t);/ /{a=apple, b=banana, c=cat, d=dog, g=gun}
System.out.println(t.ceili ngKey("c"));/ / c
System.out.println(t.higherKey("e"));/ /g
System.out.printl n(t.floorKey("e") );/ / d
System.out.println(t.lowerKey("e"));/ /d
System.out.printl n(t.poIIFirstEntryO);/ /a=apple
System.out.println(t.poIILastEntryO);/ /g=gun
System.out.println(t.descendingMap());/ /{d=dog, c=cat, b=banana}
System.out.println(t);/ /{b=banana, c=cat, d=dog}

387
Diagram:
a=apple

b=banana

c=cat

d=dog

g=gun

Collections class:
• Collections class defines several utility methods for collection objects.
Sorting the elements of a List:
• Collections class defines the following methods to perform sorting the elements of a
List.
public static void sort(List I);
• To sort the elements of List according to default natural sorting order in this case the
elements should be homogeneous and comparable otherwise we will get
ClassCastException.
• The List should not contain null otherwise we will get NullPointerException.
public static void sort(List I,Comparator c);
• To sort the elements of List according to customized sorting order.
Program 1: To sort elements of List according to natural sorting order.
import java.utiL *;
class CollectionsDemo

public static void main(String[] args)


{
ArrayList I=new ArrayList();
Ladd(IZ");
Ladd(IA");
Ladd(IK");
Ladd(IN");
IILadd(new Integer(lO));IIClassCastException
IILadd(null);/ INullPointerException
System.out.println("Before sorting :"+I);II[Z, A, K, N]
Collections.so rt(I);
System.out.println("After sorting :"+I);II[A, K, N, Z]

388
Program 2: To sort elements of List according to customized sorting order.
import java.util. *;
class CollectionsDemo

public static void main(String[] args)


{
ArrayList I=new Arravustt):
l.add(IZ");
l.add(IA");
l.add(IK");
l.add(IL");
I.add(new Integer(10));
IIl.add(null);/ INullPointerException
System.out.println("Before sorting :"+I);//[Z, A, K, L, 10]
Collections.sort(l,new MyComparatorO);
System.out.println("After sorting :"+1);/ I[Z, L, K, A, 10]
}

class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)


{
String sl=(String)obj1;
String s2=obj2.toStringO;
return s2.compareTo(sl);

Searching the elements of a list:


• Collections class defines the following methods to search the elements of a List.
public static int binarySearch(list I,Object obj);
• If the List is sorted according to default natural sorting order then we have to use this
method.
public static int binarySearch(list I,Object obj,Comparator c);
• If the List is sorted according to Comparator then we have to use this method.

389
Program 1: To search elements of List.
import java.util. *;
class CollectionsSearchDemo

public static void main(String[] args)


{
ArrayList I=new Arravtistt]:
l.add(IZ");
l.add(IA");
l.add(IM");
l.add(IK");
I.add("a");
System.out.println(I);II[Z, A, M, K, a]
Collections.so rt( I);
System.out.println(I);II[A, K, M, Z, a]
System .out.printl n(Collections. bmarvsearchtl.'?") );113
System.out.printl n(Collections. binarySearch(I,"J ") );11-2
}

Diagram:
,....!!0--r-~1
~..J.2:.._,......:3~.....:4:L=;----:';)~
successful search

IAIK IMlzla I
-1 -2 -3 -4 -5 --""';';)31> unsuccessful search
Program 2:
import java.util. *;
class CollectionsSearchDemo

public static void main(String[] args)


{
ArrayList I=new Arravustt):
l.add(15);
l.add(O);
l.add(20);
l.add(10);
l.add(5);
System.out.println(I);11[15, 0, 20, 10,5]
Collections.sort(I,new MyComparatorO);
System.out.println(I);11[20, 15, 10, 5, 0]

390
System.out.println(Collections.binarySearch(I,10,new MyComparatorO));//2
System.out.println(Collections.binarySearch(I,13,new MyComparatorO));/ /-3
System.out.println(Collections.binarySearch(I,17) );//-6
}

class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)


{
Integer i1=(lnteger)obj1;
Integer i2=(lnteger)obj2;
return i2.compareTo(i1);

Diagram:
~0!..,....;1!...._~2L.,~3--r~4!....:::;---;>~successful
search

120 115 110 I I I


5 0
-1 -2 -3 -4 -5 --->~unsuccessful search
Conclusions:
1) Internally these search methods will use binary search algorithm.
2) Successful search returns index unsuccessful search returns insertion point.
3) Insertion point is the location where we can place the element in the sorted list.
4) Before calling binarySearchO method compulsory the list should be sorted otherwise we
will get unpredictable results.
5) If the list is sorted according to Comparator then at the time of search operation also we
should pass the same Comparator object otherwise we will get unpredictable results.
Note:
• For the list of n elements with respect to binary SearchO method.
Successful search range is: 0 to n-1.
Unsuccessful search results range is: -(n+1)to -1.
Total result range is: -(n+1)to n-1.

391
Example:
-1 -2 -3 -4 ~ unsuccessful search

I Iy IzI
X
o 1 2 ------>~successful search
successful result range is: 0 to 2
unsuccessful result range is: -4 to -1
Total result range is : -4 to 2
Reversing the elements of List:
public static void reverse(List I);
reverseO vs reverseOrderO method
• We can use reverset) method to reverse the elements of List.
• Where as we can use reverseOrderO method to get reversed Comparator.
Comparator cl=Coliections.reverseOrder(Comparator C)i

1
Descending order
1
Ascending order
Program: To reverse elements of list.
import java.util. *;
class CollectionsReverseDemo

public static void main(String[] args)


{
ArrayList I=new Arravl.istf):
l.add(15);
l.add(O);
l.add(20);
l.add(10);
l.add(5);
System.out.println(I);/ /[15, 0, 20, 10, 5]
Collections. reverse( I);
System.out.println(I);/ /[5, 10, 20, 0, 15]

Arrays class:
• Arrays class defines several utility methods for arrays.
Sorting the elements of array:
public static void sort(primitive[] p);/ /any primitive data type we can give

392
• To sort the elements of primitive array according to default natural sorting order.
public static void sort(object[] 0);
• To sort the elements of object[] array according to default natural sorting order.
• In this case objects should be homogeneous and Comparable.
public static void sort(object[] o.Cornparator c);
• To sort the elements of object[] array according to customized sorting order.
Note: We can sort object[] array either by default natural sorting order (or) customized sorting
order but we can sort primitive arrays only by default natural sorting order.
Program: To sort elements of array.
import java.util, *;
class ArraySortDemo

public static void main(String[] args)


{
int[] a={10,5,20,11,6};
System.out.println("primitive array before sorting");
for(int a1:a)

System.out.println( a1);

Arrays.sort(a);
System.out.println("primitive array after sorting");
for(int a1: a)
{
System.out.printl n(a1);

String[] s={"A","Z","B"};
System.out.println("Object array before sorting");
for(String sl: s)
{
System.out.printl n(sl);

Arrays.sort(s);
System.out.println("Object array after sorting");
for(String sl:s)
{
System.out.printl n(sl);

393
Arrays.sort(s,new MyComparator());
System.out.println("Object array after sorting by Comparator:");
for(String s1: s)
{
System.out.printl n(s1);

class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)


{
String s1=obj1.toString();
String s2=obj2.toString();
return s2.compareTo(s1);

Searching the elements of array:


• Arrays class defines the following methods to search elements of array.
1) public static int binarySearch(primitive[] p,primitive key);
2) public static int binarySearch(Object[] p, object key);
3) public static int binarySearch(Object[] p,Object key,Comparator c);
• All rules of Arrays class binarySearch() method are exactly same as Collections class
binarySearch() method.
Program: To search elements of array.
import java.util. *;
class ArraysSearchDemo

public static void main(String[] args)


{
int[] a={10,5,20,11,6};
Arrays.sort(a);
System.out.println(Arrays. binarySearch( a,6));/ /1
System.out.println(Arrays. binarySearch( a,14) );/ /-5
String[] s={"A","Z","B"};
Arrays.sort(s);
System.out.printl n(Arrays. binarySearch(s, "Z"));/ /2
System.out.println(Arrays. binarySearch(s, "S") );//-3

394
Arrays.sort(s,new MyComparator());
System .out.printl n(Arrays. binarySearch(s, "Z", new MyComparatorO) );//0
System .out.printl n(Arrays. binarySearch(s, "S",new MyComparatorO) );//-2
System.out.printl n(Arrays. binarySearch(s, "N "));/ / -4( un predictable result)
}

Converting array to List:


• Arrays class defines the following method to view array as List.
public static List asList (Object[] 0);
• Strictly speaking we are not creating an independent List object just we are viewing
array in List form.
• By using List reference if we are performing any change automatically these changes will
be reflected to array reference similarly by using array reference if we are performing
any change automatically these changes will be reflected to the List reference.
• By using List reference if we are trying to perform any operation which varies the size
then we will get runtime exception saying UnsupportedOperationException.
• By using List reference if we are trying to insert heterogeneous objects we will get
runtime exception saying ArrayStoreException.
Program: To view array in List form.
import java.util. *;
class ArraysAsListDemo

public static void main(String[] args)


{
String[] s={"A", "Z"," B"};
List I=Arrays.asList(s);
System.out.println(I);/ /[A, Z, B]
s[O]="K";
System.out.println(I);/ /[K, Z, B]
I.set(l," L");
for(String sl: s)
System.out.println(sl);/ /K,L,B
/ /I.add("bhaskar");/ /UnsupportedOperationException
/ /l.remove(2);/ /UnsupportedOperationException
/ /l.set(l,new Integer(10));/ / ArrayStoreException
}

395
Diagram:

String[]

List I
S~YT5l I~
~.
z
~

396
Generics
Agenda:
1) Introduction
2) Generic Classes
3) Bounded Types
4) Generic methods and wild card character
5) Communication with non generic code
6) Conclusions
Introduction:
Case 1:
• Arrays are always type safe that is we can provide the guarantee for the type of
elements present inside array.
• For example if our programming requirement is to hold String type of objects it is
recommended to use String array. In the case of string array we can add only string type
of objects by mistake if we are trying to add any other type we will get compile time
error.
Example:
String[] s=new String[600Ji
s[OJ=ldurga"i
s[lJ=lpavan"i E:\SCJP>javac Test.java
s[2J=new Integer(lO)i(invalid)-....;cl:r.l.""'E--)~Test.java:8: incompatible types
found : java.lang.lnteger
required: java.lang.String
• That is we can always provide guarantee for the type of elements present inside array
and hence arrays are safe to use with respect to type that is arrays are type safe.
• But collections are not type safe that is we can't provide any guarantee for the type of
elements present inside collection.
• For example if our programming requirement is to hold only string type of objects it is
never recommended to go for ArrayList.
• By mistake if we are trying to add any other type we won't get any compile time error
but the program may fail at runtime.

397
Example:
ArrayList I=new ArrayListO;
I.add("vijaya");
I.add(" bhaska ra");
I.add(new Integer(10));

String namel=(String)l.get(O);
String name2=(String)l.get(1);
R.E ) Exception in thread "main" java.lang.ClassCastException:
String name3=(String)l.get(2);(invalid)
[ava.lang.Integer cannot be cast to java.lang.String

• Hence we can't provide guarantee for the type of elements present inside collections
that is collections are not safe to use with respect to type.
Case 2: In the case of array at the time of retrieval it is not required to perform any type
casting.
Example:
String[] s=new String(600);
s[O)="vijaya"j
s[l)="bhaskara"j

String namel=ls[O)j
1.... --')30> At the time of retrieval
type casting is not required.

• But in the case of collection at the time of retrieval compulsory we should perform type
casting otherwise we will get compile time error.
Example:
ArrayList I=new ArrayListO;
I.add("vijaya");
I.add("bhaskara"); est.java:9: incompatible types
String name1= l.get(O);~ ound : java.lang.Object
required: java.lang.String
String name1=I.get(O);

String name1=(String)l.get(O);
• That is in collections type casting is bigger headache.

398
• To overcome the above problems of collections(type-safety, type casting)sun people
introduced generics concept in 1.5v hence the main objectives of generics are:
1) To provide type safety to the collections.
2) To resolve type casting problems.
• To hold only string type of objects we can create a generic version of ArrayList as
follows.
Example:
ArrayList<String> I=new ArrayList<String>()j
I.add("vijaya")j
C.E> Test.java:8: cannot find symbol
l.add(lO)j(invalid)
symbol : method add(int)
location: class java.utiI.ArrayList<java.lang.String>
l.add(lO)j
• For this ArrayList we can add only string type of objects by mistake if we are trying to
add any other type we will get compile time error that is through generics we are
getting type safety.
• At the time of retrieval it is not required to perform any type casting we can assign
elements directly to string type variables.
Example:
ArrayList<String> I=new ArrayList<String>()j
I.add(" A")j

String name1= I.get(O)j


c.:.;Type casting is not required
• That is through generic syntax we can resolve type casting problems.
Conclusion!:
• Polymorphism concept is applicable only for the base type but not for parameter
type[usage of parent reference to hold child object is called polymorphism].
Example:
I--parameter
.... type

Arraylist<String> 11=new Arraylist<String>Oi


base Type __ ----'I
list<String> 12=new Arraylist<String>()i
Coliection<String> 13=new ArrayList<String>Oi
Test.java:9: incompatible types
ArrayList<Object> 14=new ArrayList<String>Oi~ found : java.util.ArrayList<java.lang.String>
required: java.util.ArrayList<java.lang.Object>
ArrayList<Object> 14=new ArrayList<String>()i

399
Concluson2:
• For the parameter type we can use any class or interface but not primitive value(type).
Example:

ArrayList<int> I=new ArrayList<int>(); r::---:-. -~-----:----------.


I . Test.Java:6:unexpected type
~found :int
required: reference
ArrayList<int> I=new ArrayList<int>()i

Generic classes:
• Untill.4v ArrayList class is declared as follows.
Example:
class ArrayList

add(Object 0);
Object get(int index);

• add() method can take object as the argument and hence we can add any type of object
to the ArrayList. Due to this we are not getting type safety.
• The return type of get() method is object hence at the time of retrieval compulsory we
should perform type casting.
• But in 1.5v a generic version of ArrayList class is declared as follows.
Example:
. '-1 ---Type parameter
classArrayLlst<T>
{
add!Tt)j
T get(int index);
}

• Based on our requirement T will be replaced with our provided type. For Example
• To hold only string type of objects we can create ArrayList object as follows.

Example:
ArrayList<String> I=new ArrayList<String>O;
• For this requirement compiler considered ArrayList class is
Example:
class ArrayList<String>

add (String s);


String get(int index);

400
• add() method can take only string type as argument hence we can add only string type
of objects to the List. By mistake if we are trying to add any other type we will get
compile time error.
Example:
import java.utiL *;
class Test
{
public static void main(String[] args)
{
ArrayList<String> I=new ArrayList<String>();
I.add(" Ali);
Test.java:8: cannot find symbol
Ladd( 10),·____.::C=. E=----....;::::::.....'lIo1
;> symbol : method add(int)
}
location: class java.utiLArrayList<java.lang.String>
}
l.add(10);
• Hence through generics we are getting type safety.
• At the time of retrieval it is not required to perform any type casting we can assign its
values directly to string variables.
Example:
import java.utiL *;
class Test
{
public static void main(String[] args)
{
ArrayList<String> I=new ArrayList<String>O;
Ladd("A");
Ladd("lO");
String namel= (get(O);
} )Type casting is not required
}
• Based on our requirement we can create our own generic classes also.
Example:
class Account<T>
{}
Account<Gold> gl=new Account<Gold>();
Account<Silver> g2=new Account<Silver>();
Example:
class UDGenerics<T>

T obj;

401
UDGenerics(T obj)
{
this.obj=obj;

public void show()


{
System.out.println("The type of object is :"+obj.getClass().getName());

public T getObject()
{
return obj:

class GenericsDemo

public static void main(String[] args)


{
UDGenerics<lnteger> gl=new UDGenerics<lnteger>(10);
gl.show();
System .out. pri ntl n(gl.getOb ject());
UDGenerics<String> g2=new UDGenerics<String>("bhaskar");
g2.show();
System .out. pri ntl n(g2.getOb ject());
UDGenerics<Double> g3=new UDGenerics<Double>(10.5);
g3.show();
System. out. pri ntl n(g3.getOb ject());

Output:
The type of object is: java.lang.lnteger
10
The type of object is: java.lang. String
Bhaskar
The type of object is: java.lang. Double
10.5
Bounded types:
• We can bound the type parameter for a particular range by using extends keyword such
types are called bounded types.

402
Example 1:
class Teste]'>
{}
Test <Integer> t1=new Test < Integer>O;
Test <String> t2=new Test < String>O;
• Here as the type parameter we can pass any type and there are no restrictions hence it
is unbounded type.
Example 2:
class Test<T extends x>
{}
• If x is a class then as the type parameter we can pass either x or its child classes.
• If x is an interface then as the type parameter we can pass either x or its implementation
classes.
Example 1:
class Test<T extends Number>
{}
class Testl
{
public static void main(String[] args)
{
Test<lnteger> U=new Test<lnteger>();
Test<String> t2=new Test<String>(); ) type parameter java.lang.String is not within its bound
Test<String> t2=new Test<String>()i
}
}

Example 2:
class Test<T extends Runnable>
{}
class Testl
{
public static void main(String[) args)
{
Test<Thread> tl=new Test<Thread>()i
estl.java:8: type parameter java.lang.String is not within its bound
Test<String> t2=new Test<String>()i C.E
Test<String> t2=new Test<String>Oi

• We can't define bounded types by using implements and super keyword.


Example:
class Test<T implements Runnable> class Test<T super String>
{} {}
(invalid) (invalid)

• But implements keyword purpose we can replace with extends keyword.

403
• As the type parameter we can use any valid java identifier but it convention to use T
always.
Example:
class Test<X> class Test<bhaskar>
{} {}
• We can pass any no of type parameters need not be one.
Example:

r---- key type


class HaShMap<k v»
{} I'-----value type
HashMap<lnteger,String> h=new HashMap<lnteger,String>O;
• We can define bounded types even in combination also.
Example 1:
class Test<T extends Number&Runnable>
{}(valid)
• As the type parameter we can pass any type which extends Number class and
implements Runnable interface.
Example 2:
class Test<T extends Number&Runnable&Comparable>
{}(valid)
Example 3:
class Test<T extends Number&String>
{}(invalid)
• We can't extend more than one class at a time.
Example 4:
class Test<T extends Runnable&Comparable>
{}(valid)
Example 5:
class Test<T extends Runnable&Number>
{}(invalid)
• We have to take 1st class followed by interface.
Generic methods and wild-card character (?):
methodOne(ArrayList<String> I): This method is applicable for ArrayList of only String type.
Example:
l.add("A");
I.add(null);
l.add(10);/ /(invalid)

404
• Within the method we can add only String type of objects and null to the List.
methodOne(Arraylist<?> I): We can use this method for ArrayList of any type but within the
method we can't add anything to the List except null.
Example:
I.add(null);/ /(valid)
l.add(IA");/ /(invalid)
l.add(lO);/ /(invalid)
• This method is useful whenever we are performing only read operation.
methodOne(Arraylist<? Extends x> I):
• If x is a class then this method is applicable for ArrayList of either x type or its child
classes.
• If x is an interface then this method is applicable for ArrayList of either x type or its
implementation classes.
• In this case also within the method we can't add anything to the List except null.
methodOne(Arraylist<? super x> I):
• If x is a class then this method is applicable for ArrayList of either x type or its super
classes.
• If x is an interface then this method is applicable for ArrayList of either x type or super
classes of implementation class of x.
• But within the method we can add x type objects and null to the List.
Which of the following declarations are allowed?
1) ArrayList<String> 11=new ArrayList<String>();/ /(valid)
2) ArrayList<?> 12=new ArrayList<String>();/ /(valid)
3) ArrayList<?> 13=new ArrayList<lnteger>();/ /(valid)
4) Arravl.istc? extends Number> 14=new ArrayList<lnteger>();/ /(valid)
5) ArrayList<? extends Number> 15=new ArrayList<String>();(invalid)
Output:
Compile time error.
Test.java:10: incompatible types
Found : java. uti I.ArrayList<java .Iang.Stri ng>
Required: java.utiI.ArrayList<? extends java.lang.Number>
ArrayList<? extends Number> 15=new ArrayList<String>();
6) Arravl.istci'> 16=new ArrayList<? extends Number>();
Output:
Compile time error
Test.java:ll: unexpected type
found :? extends java. lang. Number
required: class or interface without bounds

405
ArrayList<?> 16=new ArrayList<? extends Number>();
7) ArrayList<?> 17=new ArrayList<?>();
Output:
Test.java:12: unexpected type
Found :?
Required: class or interface without bounds
Arravl.ist-cP> 17=new ArrayList<?>();
• We can declare the type parameter either at class level or method level.
Declaring type parameter at class level:
class Test<T>

We can use anywhere this 'T'.

Declaring type parameter at method level:


• We have to declare just before return type.
Example:
public <T> void methodOnel(T t){}/ /valid
public <T extends Number> void methodOne2(T t){}/ /valid
public <T extends Number&Comparable> void methodOne3(T t){}//valid
public <T extends Number&Comparable&Runnable> void methodOne4(T t){}//valid
public <T extends Number& Thread> void methodOne(T t){}/ /invalid
Output:
Compile time error.
Test.java:7: interface expected here
public <T extends Number& Thread> void methodOne(T t){}/ /valid
public <T extends Runnable&Number> void methodOne(T t){}/ /invalid
Output:
Compile time error.
Test.java:8: interface expected here
public <T extends Runnable&Number> void methodOne(T t){}/ /valid
Communication with non generic code:
• To provide compatibility with old version sun people compramized the concept of
generics in very few area's the following is one such area.
Example:
import java.util. *;
class Test

public static void main(String[] args)

406
ArrayList<Stri ng> I=new ArrayList<Stri ng>();
l.add(IA");
I Il.add(lO);1 IC.E:cannot find symbol, method add(int)
methodOne(I);
l.add(lO.S);/ IC.E:cannot find symbol,method add(double)
System.out.println(I);II[A, lO, lO.S, true]

public static void methodOne(ArrayList I)


{
l.add(lO);
l.add(lO.S);
I.add(true);

Note:
• Generics concept is applicable only at compile time, at runtime there is no such type of
concept. Hence the following declarations are equal.
ArrayList I=new ArrayList<String>O; }
ArrayList I=new ArrayList<lnteger>O; All are equal.
ArrayList I=new ArrayListO;
Example 1:
import java.util, *;
class Test

public static void main(String[] args)


{
ArrayList I=new ArrayList<String>();
l.add(lO);
l.add(lO.S);
I.add(true);
System.out.println(I);1 I [lO, lO.5, true]

Example 2:
import java.util, *;
class Test

407
public void methodOne(ArrayList<String> I){}
public void methodOne(ArrayList<lnteger> I){}

Output:
Compile time error.
Test.java:4: name clash: methodOne(java.utiI.ArrayList<java.lang.String» and me
thodOne(java.utiI.ArrayList<java.lang.lnteger» have the same erasure
public void methodOne(ArrayList<String> I){}
• The following 2 declarations are equal.
ArrayList<String> 11=new ArrayListO;
ArrayList<String> 12=new ArrayList<String>O;
• For these ArrayList objects we can add only String type of objects.
Example:
Il.add(IA");/ /valid
Il.add(lO); / /invalid

408
Inner Classes
• Sometimes we can declare a class inside another class such type of classes are called
inner classes.
Diagram:

IT
1995may23rd jdk1.0------.1.performance

2.GUlbugs
istoo low

-v- jdk1.1 JITcompiler0.00000000001%


-----~2.EventHandling
• Sun people introduced inner classes in 1.1 version as part of "EventHandling" to resolve
GUI bugs.
• But because of powerful features and benefits of inner classes slowly the programmers
starts using in regular coding also.
• Without existing one type of object if there is no chance of existing another type of
object then we should go for inner classes.
Example: Without existing University object there is no chance of existing Department object
hence we have to define Department class inside University class.
Example1:
classUniversity------Outer class
{
classDepartment--- inner class
{
}
}
Example 2: Without existing Bank object there is no chance of existing Account object hence
we have to define Account class inside Bank class.
Example:
classBank------ Outer class
{
classAccount--- inner class
{
}
}
Example 3: Without existing Map object there is no chance of existing Entry object hence Entry
interface is define inside Map interface.

409
Example:
interface Map ----outer interface
{
interface EntrY--inner interface
{
}
}
Diagram:
I. \

<,
/
Entry

Note: The relationship between outer class and inner class is not IS-A relationship and it is Has-
A relationship.
• Based on the purpose and position of declaration all inner classes are divided into 4
types. They are:
1) Normal or Regular inner classes
2) Method local inner classes
3) Anonymous inner classes
4) Static nested classes.
1. Normal (or) Regular inner class: If we are declaring any named class inside another class
directly without static modifier such type of inner classes are called normal or regular inner
classes.
Example:
class Outer

class Inner
{
}

410
Output:
javac Outer.java

~
Outer .class Outer$lnner .class
E:\scjp>java Outer
Exception in thread "main" java.lang.NoSuchMethodError: main
E:\scjp>java Outer$lnner
Exception in thread "main" java.lang.NoSuchMethodError: main
Example:
class Outer

class Inner
{
}
public static void main(String[] args)
{
Svstern.out.printlnf'touter class main method"):

Output:
javac Outer.java
--- Outer. class
--- OuterSlnner.class
E:\scjp>java Outer
outer class main method
E:\scjp>java Outer$lnner
Exception in thread "main" java.lang.NoSuchMethodError: main

• Inside inner class we can't declare static members. Hence it is not possible to declare
main() method and we can't invoke inner class directly from the commend prompt.
Example:
class Outer

class Inner

public static void main(String[] args)


{
Svstern.out.printlnf'fnner class main method"):

411
Output:
E:\scjp>javac Outer.java
Outer.java:5: inner classes cannot have static declarations
public static void main(String[] args)
Accessing inner class code from static area of outer class:
Example:
class Outer

class Inner

public void methodonef)]


System.out.println("inner class method");

public static void main(String[] args)


{
Outer o=new OuterOj }
Outer.lnner i=o.new lnnerl]: (or)
i.methodonel]:
Outer.lnner i=new OuterO.new InnerOj}
i.methodonei): (or)

new OuterO.new InnerO.methodOneOj

Accessing inner class code from instance area of outer class:


Example:
class Outer

class Inner

public void methodOneO


{
System.out.println("inner class method");

public void methodTwoO


{

412
Inner i=new Inner();
i.methodOne();

public static void main(String[] args)


{
Outer o=new Outer();
o.methodTwo();

Output:
E:\scjp>javac Outer.java
E:\scjp>java Outer
Inner class method
Accessing inner class code from outside of outer class:
Example:
class Outer

class Inner

public void methodOne()

System.out.println("inner class method");

class Test

public static void main(String[] args)


{
new Outer().new Inner().methodOne();

Output:
Inner class method

413
From static area of outer class From instance area of outer class
(or) Inner i=new InnerOj
From outside of outer class i.methodonet]:
Outer o=new OuterOj
Outer.lnner i=o.new InnerOj
l.methodonet):

• From inner class we can access all members of outer class (both static and non-static,
private and non private methods and variables) directly.
Example:
class Outer

int x=10;
static int y=20;
class Inner{
public void methodOneO
{
System.out.println(x);/ /10
System.out.println(y);/ /20

public static void main(String[] args)


{
new Outerlj.new lnnerfj.methodonet):

• Within the inner class "this" always refers current inner class object. To refer current
outer class object we have to use "outer class name.this".
Example:
class Outer

int x=10;
class Inner

int x=100;

414
public void methodOne()
{
int x=1000;
System.out.println(x);/ /1000
System.out.println(this.x);/ /100
System.out.println(Outer.this.x);/ /10

public static void main(String[] args)


{
new Outer().new Inner().methodOne();

• The applicable modifiers for outer classes are:


1) public
2) default
3) final
4) abstract
5) strictfp
• But for the inner classes in addition to this the following modifiers also allowed.
Diagram:
public
private
default
+ protected
final
static[static nested classes]
abstract
strictfp

Method local inner classes:


• Sometimes we can declare a class inside a method such type of inner classes are called
method local inner classes.
• The main objective of method local inner class is to define method specific repeatedly
required functionality.
• We can access method local inner class only within the method where we declared it.
That is from outside of the method we can't access. As the scope of method local inner
classes is very less, this type of inner classes are most rarely used type of inner classes.
Example:
class Test

415
public void methodOne()
{
class Inner

public void sum(int i,int j)


{
System.out.println("The sum:"+(i+j));

Inner i=new Inner();


i.sum(10,20);

'"'"'"IJII
i.sum(100,200);
J" J" "" J II J I

i.sum(1000,2000);
11111111111111111

public static void main(String[] args)


{
new Test().methodOne();

Output:
The sum: 30
The sum: 300
The sum: 3000
• If we are declaring inner class inside instance method then we can access both static
and non static members of outer class directly.
• But if we are declaring inner class inside static method then we can access only static
members of outer class directly and we can't access instance members directly.
Example:
class Test

int x=lO;
static int y=20;
public void methodOne()
{
class Inner

416
public void methodTwo()
{
System.out.println(x);1110
System.out.println(y);1120

Inner i=new lnnert):


i.method'Iwot):

public static void main(String[] args)


{
new Test().methodOne();

• If we declare methodOne() method as static then we will get compile time error saying
"non-static variable x cannot be referenced from a static context".
• From method local inner class we can't access local variables of the method in which we
declared it. But if that local variable is declared as final then we won't get any compile
time error.
Example:
class Test

int x=10;
public void methodOneO
{
int y=20;
class Inner

public void methodTwo()


{
System.out.println(x);1110
System.out.println(y); IIC.E: local variable y is accessed from
within inner class; needs to be declared final.

Inner i=new lnnerf):


i.methodTwoO;

417
public static void main(String[] args)
{
new Testtj.methodonef]:

• If we declared y as final then we won't get any compile time error.


• Consider the following declaration.
class Test

int i=10;
static int j=20;
public void methodOneO

int k=30;
final int 1=40;
class Inner

public void methodTwoO


{
System.out.println(i); )
System.out.println(j); line 1
System.out.printl n(k);
System .out.println(I);

Inner i=new lnnerl):


i.methodTwoO;

public static void main(String[] args)


{
new Testtl.methodonefl:

• At line 1which of the following variables we can access?


vt i ~ j )( k ~I
• If we declare methodOneO method as static then which variables we can access at line
1?

418
)Ki vtfl
• If we declare methodTwoO as static then we will get compile time error because we
can't declare static members inside inner classes.
• The only applicable modifiers for method local inner classes are:
1) final
2) abstract
3) strictfp
• By mistake if we are declaring any other modifier we will get compile time error.
Anonymous inner classes:
• Sometimes we can declare inner class without name such type of inner classes are
called anonymous inner classes.
• The main objective of anonymous inner classes is "just for instant use".
• There are 3 types of anonymous inner classes
1) Anonymous inner class that extends a class.
2) Anonymous inner class that implements an interface.
3) Anonymous inner class that defined inside method arguments.
Anonymous inner class that extends a class:
class PopCorn

public void tasteO


{
System.out.println("spicy");

class Test

public static void main(String[] args)


{
PopCorn p=new PopCornO

public void tasteO


{
System.out.println("salty");

};
p.tasteO;/ /salty

419
PopCorn p1=new PopCorn();
pl.taste();/ /spicy

Analysis:
1) PopCorn p=new PopCorn{);
• We are just creating a PopCorn object.
2) PopCorn p=new PopCorn{)
{
};
• We are creating child class without name for the PopCorn class and for that child class
we are creating an object with Parent PopCorn reference.
3) PopCorn p=new PopCorn{)
{
public void taste{)
{
System.out.println("salty");
}
};
1) We are creating child class for PopCorn without name.
2) We are overriding taste() method.
3) We are creating object for that child class with parent reference.
Note: Inside Anonymous inner classes we can take or declare new methods but outside of
anonymous inner classes we can't call these methods directly because we are depending on
parent reference.[parent reference can be used to hold child class object but by using that
reference we can't call child specific methods]. These methods just for internal purpose only.
Example 1:
class PopCorn

public void taste()


{
System.out.println("spicy");

class Test

public static void main(String[] args)


{

420
PopCorn p=new PopCorn()
{
public void taste()
{
methodOne();/ /valid call{internal purpose)
System.out.println{"salty");

public void methodOne()


{
System.out.println{"child specific method");

};
/ /p.methodOne();/ /here we can not call{outside inner class)
p.taste();/ /salty
PopCorn pl=new PopCorn();
pl.taste();/ /spicy

Output:
Child specific method
Salty
Spicy
Example 2:
class Test

public static void main{String[] args)


{
Thread t=new Thread()
{
public void run()
{
for{int i=O;i<10;i++)
{
System.out.println{"child thread");

};
t.start();

421
for(int i=O;i<10;i++)
{
System.out.println("main thread");

Anonymous Inner Class that implements an interface:


Example:
class InnerClassesDemo

public static void main(String[] args)


{
Runnable r=new RunnableO//here we are not creating for Runnable interface,
we are creating implements class object.

public void runO


{
for(int i=O;i<10;i++)
{
System.out.println("Child thread");

};
Thread t=new Thread(r);
t.startf):
for(int i=O;i<10;i++)
{
System.out.println("Main thread");

Anonymous Inner Class that define inside method arguments:


Example:
class Test

public static void main(String[] args)


{
new Thread(

422
new Runnable()

public void run()


{
for{int i=O;i<10;i++}
{
System.out.println{"child thread"};

}}.start();
for{int i=O;i<10;i++}
{
System.out.println{"main thread"};

Output:
• This output belongs to example 2, anonymous inner class that implements an interface
example and anonymous inner class that define inside method arguments example.
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Child thread
Child thread
Child thread
Child thread
Child thread
Child thread
Child thread
Child thread
Child thread

423
Child thread
Difference between ~eneral class and anonvmous inner classes'
General Class Anonymous Inner Class
1) A general class can extends only one 1) Ofcource anonymous inner class also
class at a time. can extends only one class at a time.
2) A general class can implement any no. 2) But anonymous inner class can
Of interfaces at a time. implement only one interface at a
time.
3) A general class can extends a class and 3) But anonymous inner class can extends
can implement an interface a class or can implements an interface
simultaneously. but not both simultaneously.
Static nested classes:
• Sometimes we can declare inner classes with static modifier such type of inner classes
are called static nested classes.
• In the case of normal or regular inner classes without existing outer class object there is
no chance of existing inner class object.
• But in the case of static nested class without existing outer class object there may be a
chance of existing static nested class object.
Example:
class Test

static class Nested

public void methodOne()


{
$ystem.out.println("nested class method");

public static void main(String[] args)


{
Test.Nested t=new Test.Nestedl]:
t.methodOne();

• Inside static nested classes we can declare static members including main() method
also. Hence it is possible to invoke static nested class directly from the command
prompt.

424
Example:
class Test

static class Nested

public static void main(String[] args)


{
System.out.println("nested class main method");

public static void main(String[] args)


{
System.out.println("outer class main method");

Output:
E:\SCJP>javac Test.java
E:\SCJP>java Test
Outer class main method
E:\SCJP>java Test$Nested
Nested class main method
• From the normal inner class we can access both static and non static members of outer
class but from static nested class we can access only static members of outer class.
Example:
class Test

int x=10;
static int y=20;
static class Nested

public void methodOne()


{
System.out.println(x);/ /C.E:non-static variable x cannot be referenced
from a static context
System.out.printl n(y);

425
Compression between normal or regular class and static nested class?
Normal/regular inner class Static nested class
1) Without existing outer class object 1) Without existing outer class object
there is no chance of existing inner there may be a chance of existing static
class object. That is inner class object is nested class object. That is static
always associated with outer class nested class object is not associated
object. with outer class object.
2) Inside normal or regular inner class we 2) Inside static nested class we can
can't declare static members. declare static members.
3) Inside normal inner class we can't 3) Inside static nested class we can
declare mainO method and hence we declare mainO method and hence we
can't invoke regular inner class directly can invoke static nested class directly
from the command prompt. from the command prompt.
4) From the normal or regular inner class 4) From static nested class we can access
we can access both static and non only static members of outer class
static members of outer class directly. directly.

426
Internationalization
• The process of designing a web application such that it supports various countries,
various languages without performing any changes in the application is called
Internationalization.
• We can implement Internationalization by using the following classes. They are:
1) Locale
2) NumberFormat
3) DateFormat
1. Locale: A Locale object can be used to represent a geographic (country) location (or)
language.
• Locale class present in java.util package.
• It is a final class and direct child class of Object implements Cloneable and Serializable
Interfaces.
How to create a Locale object:
• We can create a Locale object by using the following constructors of Locale class.
1) Locale I=new Locale(String language);
2) Locale I=new Locale(String language,String country);
• Locale class already defines some predefined Locale constants. We can use these
constants directly.
Example:
Locale. UK
Locale. US
Locale. ITALY
Locale. CHINA
Important methods of Locale class:
1) public static Locale getDefault()
2) public static void setDefault(Locale I)
3) public String getLanguage()
4) public String getDisplayLanguage(Locale I)
5) public String getCountry()
6) public String getDisplayCountry(Locale I)
7) public static String[] getlSOLanguages()
8) public static String[] getlSOCountries()
9) public static Locale[] getAvailableLocales()
Example for Locale:
import java.util. *;
class LocaleDemo{
public static void main(String args[]H
Locale 11=Locale.getDefault();
j jSystem.out.println(l1.getCountry()+" ..... " +11.getLanguage());

427
j jSystem .out.println (ll.getDisplayCou ntry()+" ..... +ll.getDisplayLanguage());
II

Locale 12=new Locale("pa"/'IN");


Locale.setDefau It(12);
String[] s3=Locale.getISOLanguages();
for(String 54:53)
{
j jSystem.out.print("ISO language is :");
j jSystem.out.println(s4);
}
String[] s4=Locale.getISOCountries();
for(String 55:54)
{
System.out.print("ISO Country is:");
System.out.println(s5 );
}
Locale[] s=Locale.getAvailableLocales();
for(Locale 51:5)
{
j jSystem.out.print("Available locales is:");
j jSystem.out. pri ntln(sl.getDisplayCountry()+" ...... +sl.getDisplayLa nguage());
II

}}}
NumberFormat:
• Various countries follow various styles to represent number.
Example:
l,23A56. 789------------IN DIA
123A56.789-------------US
123.456,789-------------ITALY
• By using NumberFormat class we can format a number according to a particular Locale.
• NumberFormat class present in java.Text package and it is an abstract class.
• Hence we can't create an object by using constructor.
NumberFormat nf=new NumberFormat(); --------invalid
Getting NumberFormat object for the default Locale:
• NumberFormat class defines the following methods for this.
l}public static NumberFormat getlnstance();
2}public static NumberFormat getCurrencylnstance();
3}public static NumberFormat getPercentlnstance();
4)public static NumberFormat getNumberlnstance();
r:-b-ot"":'h-a-r-e'--sa-m----.e
Getting NumberFormat object for the specific Locale:
• The methods are exactly same but we have to pass the corresponding Locale object as
argument.

428
Example: public static NumberFormat getNumberlnstance(Locale I);
• Once we got NumberFormat object we can call the following methods to format and
parse numbers.
1) public String format(long I);
2) public String format(double d);
• To convert a number from java form to Locale specific form.
1) public Number parse(String source)throws ParseException
• To convert from Locale specific String form to java specific form.
Example:
import java.util. *;
import java.text. *;
class NumberFormatDemo

public static void main(String args[]H


double d=123456.789;
NumberFormat nf=NumberFormat.getl nstance(Locale.ITALY);
System.out.println("ITALY form is :"+nfJormat(d));
}
}
Output:
ITALYform is :123.456,789
Requirement: Write a program to print a java number in INDIA, UK, US and ITALY currency
formats.
Program:
import java.util. *;
import java.text. *;
class NumberFormatDemo

public static void main(String args[]H


double d=123456.789;
Locale INDIA=new Locale("pa","IN");
NumberFormat nf=NumberFormat.getCurrencylnstance(INDIA);
System.out.println("INDIA notation is :"+nfJormat(d));
NumberFormat nf1=N umberFormat.getCurrencyl nstance(Locale. UK);
System.out.println("UK notation is :"+nf1.format(d));
NumberFormat nf2=NumberFormat.getCurrencylnstance(Locale.US);
System.out.println("US notation is :"+nf2.format(d));
NumberFormat nf3=NumberFormat.getCurrencyl nstance(Locale.ITAL Y);
System.out.println("ITALY notation is :"+nf3.format(d));
}}
Output:
INDIA notation is: INR 123,456.79
UK notation is: u123,456.79
US notation is: $123,456.79

429
ITALY notation is: c 123.456J9
Setting Maximum, Minimum, Fraction and Integer digits:
• NumberFormat class defines the following methods for this purpose.
1) public void setMaximumFractionDigits(int n);
2) public void setMinimumFractionDigits(int n);
3) public void setMaximumlntegerDigits(int n);
4) public void setMinimumlntegerDigits(int n);
Example:
import java.text. *;
public class NumberFormatExample
{
public static void main(String[] args){
NumberFormat nf=NumberFormat.getlnstanceO;
nf.setMaximumFractionDigits(3);
System .out. pri ntl n(nf. format( 123.4));
System. out. pri ntl n(nf. format( 123 .4567));
nf.setMinimumFractionDigits(3);
System .out. pri ntl n(nf. format( 123.4));
System. out. pri ntl n(nf. format( 123 .4567));
nf.setMaximumlntegerDigits(3);
System .out. pri ntl n(nf. format( 1.234));
System.out.printl n(nf. format( 123456. 789));
nf.setMinimumlntegerDigits(3);
System. out. pri ntl n(nf. format( 1.234));
System.out.printl n( nf. format( 123456. 789));
}}
Output:
123.4
123.457
123.400
123.457
1.234
456.789
001.234
456.789
DateFormat: Various countries follow various styles to represent Date. We can format the date
according to a particular locale by using DateFormat class.
• DateFormat class present in java.text package and it is an abstract class.
Getting DateFormat object for default locale:
• DateFormat class defines the following methods for this purpose.

430
l)public static DateFormat getlnstance();
2)public static DateFormat getDatelnstance();
3)public static DateFormat getDatelnstance(int style);

T
Date Format. FULL---------------------->0
Date Format. LONG---------------------> 1
DateFormat.MEDIMUM------------->2
Date Format.SHORT --------------------> 3
Getting DateFormat object for the specific Locale:
1) public static DateFormat getDatelnstance(int style, Locale I);
• Once we got DateFormat object we can format and parse Date by using the following
methods.
1) public String format(Date date);
• To convert the date from java form to locale specific string form.
1) public Date parse(String source)throws ParseException
• To convert the date from locale specific form to java form.
Requirement: Write a program to represent current system date in all possible styles of us
format.
Program:
import java.text. *;
import java.util. *;
public class DateFormatDemo
{
public static void main(String args[]H
System.out.println("full form is :"+DateFormat.getDatelnstance(O).format(new Date()));
System.out.println("long form is :"+DateFormat.getDatelnstance(l).format(new Date()));
System.out.println("medium form is :"+DateFormat.getDatelnstance(2).format(new Date()));
System.out.println("short form is :"+DateFormat.getDatelnstance(3).format(new Date()));
}
}
Output:
Full form is: Wednesday, July 20, 2011
Long form is: July 20,2011
Medium form is: Jul 20, 2011
Short form is: 7/20/11
Note: The default style is medium style.
Requirement: Write a program to represent current system date in UK, US and ITALY styles.
Program:
import java.text. *;
import java.util. *;
public class DateFormatDemo
{

431
public static void main(String args[]H
DateFormat UK=DateFormat.getDatelnstance(O,Locale.UK);
DateFormat US=DateFormat.getDatelnstance(O,Locale.US);
DateFormat ITALY=DateFormat.getDatelnstance(O,Locale.ITALY);
System.out.println("UK style is :"+UK.format(new Date()));
System.out.println("US style is :"+US.format(new Date()));
System.out.println("ITALY style is :"+ITALY.format(new Date()));
}
}
Output:
UK style is: Wednesday, 20 July 2011
US style is: Wednesday, July 20, 2011
ITALY style is: mercoled= 20 luglio 2011
Getting DateFormat object to get both date and time:
• DateFormat class defines the following methods for this.
l)public static DateFormat getDateTImelnstanceOi
2.)public static DateFormat getDateTimelnstance(int date Style, int timestvle):
3)publlc static DateFormat getDateTimelnstance(int dajtYle, Int timeYVle,Locale I);

o to 3 0 to 3
Example:
import java.text. *;
import java.util. *;
public class DateFormatDemo
{
public static void main(String args[]H
DateFormat ITALY=DateFormat.getDateTime Instance(O,O,Locale.ITALY);
System.out.println("ITALY style is:"+ITALY.format(new DateO));
}
}
Output:
ITALY style is: rnercoled= 20 luglio 201123.21.30 1ST

432
Development
Javac: we can use Javac to compile a single or group of ".java files".
Syntax:
javac [options) Test.java (valid)

r
-source
Test.java Demo.java (valid)
* .java (valid)
-version
-cp <path>
-d <directory>

Java: we can use java command to run a single ".class file".


Syntax:
java [options] classfile arg[O] arg[l] .
-version
-ea/-esa/-da/-dsa
-0
-cp/ -classpath

Classpath: Class path describes the location where the required ".class files" are available. We
can set the class path in the following 3 ways.
1) Permanently by using environment variable "classpath". This class path will be
preserved after system restart also.
2) Temporary for a particular command prompt level by using "set" command.
Example:

set classpath=%classpath%;O:\durga_classes;.;

• Once if you close the command prompt automatically this class path will be lost.
3) We can set the class path for a particular command level by using "_Cp" (or) "-class
path". This class path is applicable only for that command execution. After executing
the command this classpath will be lost.
• Among the 3 ways of setting the class path the most common way is setting class path
at command level by using "_Cp".
Example 1:
class Rain

public static void main(String args[]H

433
System.out.println("Raining of jobs these days");
}
}
Analysis:
D:\Java>javac Rain.java (valid)
D:\Java>java Rain (valid)
Raining of jobs these days.
D:\>java Rain (invalid)
Exception in thread "main" java.lang.NoClassDefFoundError: Rain
D:\>java -cp D:\java Rain (valid)
Raining of jobs these days.
D:\>java Rain (invalid)
C:\>java -cp d:\java Rain (valid)
Raining of jobs these days
Example 2:

C: 0:
public class Fresher class ItCompany
{ {
public void methodOne(){ public static void main(String args[]){
System.out.println("i want job Fresher f=new Fresher();
immediately" ); ~.methodOne();
} System.out.println("don't worry you will
} ~et 500n •...");
}
Analysis: }
C:\>javac Fresher.java (valid)
D:\>javac ItCompany.java (invalid)
compile time error: ItCompany.java:4: cannot find symbol
symbol : class Fresher
location: class ItCompany
Fresher f=new Freaher();
D:\>javac -cp c: ItCompany.java(valid)
D:\>java ItCompany
Runtime error:NoClassDefFoundError: Fresher
D:\>java -cp c: ItCompany
Runtime error:NoClassDefFoundError: ItCompany
D:\>java -cp .;c: ItCompany (valid)
i want job immediately
don't worry you will get soon ....
E:\>java -cp D:;C: ItCompany (valid)

434
Example 3:

E:
package pack1.pack2; package pack3.pack4; import pack3.pack4.Saif;
public class Kareena{ import packl.pack2.Kareena; class Bhaskar{
public void methodOneO{ public class Saif{ public static void main(String
System.out.println("hello soiL.can public void methodTwoO{ args(]){
u please set hellotune"); Kareena k=new KareenaO; Saif s=new SaifO;
} k.methodOneO; s.methodTwoO;
} System.out.println("not possible as i am in System.out.println("kareena
c:-packl SCJPclass");}} can i help vou");}}
~pack2 D:-pack3
~Kareena.class ~pack4
~ Saif.class

Analysis:

C:\>javac -d . Kareena.java (valid)


D:\>javac -d . Saif.java (invalid) ~ compile time error
Saif.java:S: cannot find symbol
symbol : class Kareena
location: class pack3.pack4.Saif
Kareena k=new KareenaO;
D:\>javac -cp c: -d . Saif.java (valid)
E:\>javac Bhaskar.java (invalid) ~ compile time error
Bhaskar.java:4: cannot find symbol
symbol : class Saif
location: class Bhaskar
Saif s=new Saif 0;
E:\>javac -cp d: Bhaskar.java (valid)
E:\>java Bhaskar (invalid) ----~ Runtime error
NoClassDefFoundError: pack3/pack4/Saif
E:\>java -cp d: Bhaskar (invalid) ---7!Ri!u~n!!!ti!!!m~e~e~r~ro~r
NoClassDefFoundError: Bhaskar

E:\>java -cp .;d: Bhaskar (invalid) ~Runtime error


NoClassDefFoundError: packl/pack2/Kareena
E:\>java -cp .;d:;c: Bhaskar (valid)~output:
hello soif ...can u please set hellotune
not possible as i am in SCJPclass
kareena can i help you
F:\>java -cp E:;D:;C: Bhaskar (valid)~output:
hello soiL.can u please set hellotune
not possible as i am in SCJPclass
kareena can i help you
Note: if any folder structure created because of package statement. It should be resolved by
import statement only and the location of base package should be make it available in class
path.
Note: in classpath the order of locations is very important and it should be from left to right.

435
Example 4:

E:
class Nagavalli{ class Nagavalli{ class Nagavalli{
public static void main(String args[]){ public static void main(String args[]){ public static void
System.out.println("C:Nagavalli executed"); System.out.println(" D:Nagavalii executed"); main(String args[]){
}} }} System.out.println
("E:Nagavalii executed");
}}

Analysis:
C:\>javac Nagavalli.java (valid)
D:\>javac NagavallLjava (valid)
E:\>javac NagavallLjava (valid)
C:\>java Nagavalli output:
C:Nagavalii executed
C:\>java -cp e:;d:;c: Nagavalli output:
E:Nagavalii executed
C:\>java -cp d:;e:;c: Nagavalli output:
D:Nagavalii executed
Jar file: If several dependent classes present then it is never recommended to set the classpath
individual for every component. We have to group all these ".class files" into a single jar file and
we have to make that jar file available to the classpath.
Example: All required classes to develop a Servlet are grouped into a single jar file (Servlet-
api.jar) hence while compiling Servlet classes we have to make this jar file available in the
classpath.
What is the difference between Jar, War and Ear?
Jar (java archive): Represents a group of ".class files".
War (web archive): Represents a web application which may contains Servlets, JSP, HTML
pages, JavaScript files etc.
Ear (Enterprise archive): it represents an enterprise application which may contain Servlets,
JSP, EJB'S,JMS component etc.
• In generally an ear file consists of a group of war files and jar files.
Ear=war+ jar
Various Commands:
To create a jar file:
D:\Enum>jar -cvf bhaskar.jar Beer.class Test.class X.class
D:\Enum>jar -cvf bhaskar.jar * .class
To extract a jar file:
D:\Enum>jar -xvf bhaskar.jar
To display table of contents of a jar file:
D:\Enum>jar -tvf bhaskar.jar

436
Example 5:
public class BhaskarColorFulCalc{
public static int add(int x,int y){
return x*y;

public static int multiply(int x,int y){


return 2*x*y;
}}
Analysis:
C:\>javac BhaskarColorFulCalc.java
C:\>jar -cvf bhaskar.jar BhaskarColorFulCalc.class
Example 6:
class Client{
public static void main(String args[]H
System.out.println(BhaskarColorFuICalc.add(lO,20));
System.out.println(BhaskarColorFuICalc.multiply(lO,20));
}}
Analysis:
D:\Enum>javac Client.java (invalid)
D:\Enum>javac -cp c: Client.java (invalid)
D:\Enum>javac -cp c:\bhaskar.jar Client.java (valid)
D:\Enum>java -cp .;c:\bhaskar.jar Client (valid)
Note: Whenever we are placing jar file in the classpath compulsory we have to specify the
name of the jar file also and just location is not enough.
System properties:
• For every system some persistence information is available in the form of system
properties. These may include name of the os, java version, vendor of jvm etc.
• We can get system properties by using getProperties() method of system class. The
following program displays all the system properties.
Example 7:
import java.util. *;
class Test{
public static void main(String args[]H
/ /Properties is a class in util package.
/ /here getPropertes() method returns the Properties object.
Properties p=System.getProperties();
p.1ist(System .out);
}

437
How to set system property from the command prompt:
• We can set system property from the command prompt by using -D option.
Command:
D:\Enum>java -Dbhaskar=scjp Test

propertyname
\II T
propertyvalue

What is the difference between path and classpath?


Path: We can use "path variable" to specify the location where required binary executables are
available.
• If we are not setting path then "java" and "Javac" commands won't work.
Classpath: We can use "classpath variable" to describe location where required class files are
available.
• If we are not setting classpath then our program won't compile and run.
What is the difference between JDK, JREand JVM?
JDK (java development kit): To develop and run java applications the required environment is
JDK.
JRE(java runtime environment): To run java application the required environment is JRE.
JVM (java virtual machine): To execute java application the required virtual machine is JVM.
Diagram:

+Development
Tools

JDK
~ JDK=JRE+Development Tools.
~ JRE=JVM+Libraries.
~ JRE is the part of JDK.
~ Jvm is the part of JRE.
Note: At client side JREis required and at developers side JDK is required.
Shortcut way to place a jar files:
• If we are placing jar file in the following location then it is not required to set classpath
explicitly.

438
JDK
LJRE
I LUB
ILEXT
I ~*.jar

439
ENUM
• We can use enum to define a group of named constants.
Example 1:
enum Month

JAN,FEB,MAR,DEC;
}
Example 2:
enum Beer

• Enum concept introduced in 1.5 versions.


• When compared with old languages enum java's enum is more powerful.
• By using enum we can define our own data types which are also come enumerated data
types.
Internal implementation of enum:
• Internally enum's are implemented by using class concept. Every enum constant is a
reference variable to that enum type object.
• Every enum constant is implicitly public static final always.
Example 3·
enum Beer final class Beer extends java.lang.Enum{
{ , public static final Beer KF=new BeerO;
/
KF,KO; public static final Beer KO=new Beert):
} }
Diagram:

KF----D KO----D
Declaration and usage of enum:
Example 4:
enum Beer

KF,KO,RC,FO;//here semicolon is optional.


}
class Test

public static void main(String args[]H

440
Beer b1=Beer.KF;
System.out.printl n(b1);
}
}
Output:
D:\Enum>java Test
KF
Note: Every enum constant internally static hence we can access by using "enum name".
Enum vs switch statement:
• Until 1.4 versions the allowed types for the switch statement are byte, short, char into
But from 1.5 version onwards in addition to this the corresponding wrapper classes and
enum type also allowed. That is from 1.5 version onwards we can use enum type as
argument to switch statement.
Diagram:

byte Byte

switch(x)
short Short
{
} + I Stringl
int Integer 1.7v

char Character
1.4v +
lenuml
1.Sv

Example:
enum Beer

KF,KO,RC,FO;
}
class Test{
public static void main(String args[]}{
Beer b1=Beer.RC;
sWitch(b1}{
case KF:
System.out.println("it is childrens brand");
break;
case KO:
System.out.println("it is too lite");
break;
case RC:

441
System.out.println("it is too hot");
break;
case FO:
System.out.println("buy one get one");
break;
default:
System.out.println("other brands are not good");

}}
Output:
D:\Enum>java Test
It is too hot
• If we are passing enum type as argument to switch statement then every case label
should be a valid enum constant otherwise we will get compile time error.
Example:
enum Beer

KF,KO,RC,FO;
}
class Test{
public static void main(String args[]H
Beer b1=Beer.RC;
switchfb Ij]
case KF:
case RC:
case KALYANI:
}}}
Output:
Compile time error.
D:\Enum>javac Test.java
Test.java:l1: unqualified enumeration constant name required
case KALYANI:
• We can declare enum either outside the class or within the class but not inside a
method. If we declare enum outside the class the allowed modifiers are:
1) public
2) default
3) strictfp.
• If we declare enum inside a class then the allowed modifiers are:

442
1) public private
2) default + protected
3) strictfp static

Example:

class X
class X {
enumX
public void methodOneO{
{}
class Y enum Y nu x
{} {}
}
C}
:
output:
compile time error.
(valid) (valid) } D:\Enum>javac X.java
X.java:4: enum types must not be local
enumX
Enum vs inheritance:
• Every enum in java is the direct child class of java.lang.Enum class hence it is not
possible to extends any other enum.
• Every enum is implicitly final hence we can't create child enum.
• Because of above reasons we can conclude inheritance concept is not applicable for
enum's explicitly.
• But enum can implement any no. Of interfaces simultaneously.
Example:

enumX class X
enum X extends Enum
{} {}
{}
enum Y extends X enum Y extends X
{} {}
(invalid) (invalid) (invalid)

Example:

enum X
{}
class Y extends X
{}
output: interface X
compile time error. {}
D:\Enum>javac Y.java enum Y implements X
Y.java:3: cannot inherit from final X {}
class Y extends X
(valid)
Y.java:3: enum types are not extensible
class Y extends X
(invalid)

Java.lang.Enum: Every enum in java is the direct child class of java.lang.Enum. The power of
enum is inheriting from this class only.

443
• It is abstract class and it is direct child class of "Object class" it implements Serializable
and Comparable.
valuesO method: Every enum implicitly contains a static valuesO method to list all constants of
enum.
Example: Beer[] b=Beer.valuesO;
ordinalO method: Within enum the order of constants is important we can specify by its ordinal
value.
• We can find ordinal value(index value) of enum constant by using ordinalO method.
Example: public int ordinalt):
Example:
enum Beer

KF,KO,RC,FO;
}
class Test{
public static void main(String args[]H
Beer[] b=Beer.valuesO;
for(Beer bl:b)/ /this is forEach loop.
{
System.out.printl n(bl +"....... +b 1.ord ina 10);
II

}}}
Output:
D:\Enum>java Test
KF O
KO 1
RC 2
FO 3
Specialty of java enum: When compared with old languages enum java's enum is more
powerful because in addition to constants we can take normal variables, constructors, methods
etc which may not possible in old languages.
• Inside enum we can declare main method and even we can invoke enum directly from
the command prompt.
Example:
enum Fish{
GOLD,APOLO,STAR;
public static void main(String args[]H
System.out.println("enum mainO method called");
}}

444
Output:
D:\Enum>java Fish
enum main() method called
• In addition to constants if we are taking any extra members like methods then the list of
constants should be in the 1st line and should ends with semicolon.
• If we are taking any extra member then enum should contain at least one constant. Any
wayan empty enum is always valid.
Example:
enum X{
enum X{ public void methodOne(){
A/B/C;/ there semicolon mandatory. }
public void methodOne(){ A,B,C;
} }
(valid)
} (invalid)

enum X enum X enum X


{ {
public void methodOne(){
} public void methodOne(){
(invalid) (valid)
} } (valid)
}
Enum vs constructor: Enum can contain constructor. Every enum constant represents an object
of that enum class which is static hence all enum constants will be created at the time of class
loading automatically and hence constructor will be executed at the time of enum class loading
for every enum constants.
Example:
enum Beer{
KF,KO,RC,FO;
Beer(){
System.out.println("Constructor called. ");
}
}
class Test{
public static void main(String args[]H
Beer b=Beer.KF;
System.out.println("hello.");
}}
Output:
D:\Enum>java Test
Constructor called.
Constructor called.
Constructor called.

445
Constructor called.
Hello.
• We can't create enum object explicitly and hence we can't invoke constructor directly.
Example:
enum Beer{
KF,KO,RC,FO;
BeerO{
System.out.printl n("constructor called");

class Test{
public static void main(String args[]){
Beer b=new Beer();
System.out.printl n(b);
}}
Output:
Compile time error.
D:\Enum>javac Test.java
Test.java:9: enum types may not be instantiated
Beer b=new Beer();
Example:
KF==>public static final Beer KF=new BeerO;
KF(lOO)==>public static final Beer KF=new Beer(lOO);
enum Beer

KF(100), KO(70), RC( 65), Fo(90), KAL VAN I;


int price;
Beer(int price){
this.price=price;

BeerO
{
this.price=125;

public int getPrice()


{
return price;

446
class Test{
public static void main(String args[]H
Beer[] b=Seer.valuesf):
for(Beer bl:b)
{
System.out. println (b 1 +" u -b l.getPriceO);
}}}
• Inside enum we can take both instance and static methods but it is not possible to take
abstract methods.
Case 1:
• Every enum constant represents an object hence whatever the methods we can apply
on the normal objects we can apply the same methods on enum constants also.
Which of the following expressions are valid?
1) Beer. KF==Beer. RC----------------------------> false
2) Beer. KF.equals( Beer. RC) ------------------->false
3) Beer. KF< Beer. RC------------------------------>i nva Iid
4) Beer. KF.ordinaIO<Beer. RC.ordinaIO------>valid
Case 2:
Example 1:
package packl;
public enum Fish

STAR/GUPPY;
}
Example 2:
package pack2;
jjimport static packl.Fish.*;
import static packl.Fish.STAR;
class A

public static void main(String args[]H


System.out.println(STAR);
}

1) Import packl. *; ---------------------------->invalid


2) Import packl.Fish; ------------------------->invalid
3) import static packl.Fish. *; --------------->valid

447
4) import static packl.Fish.STAR; ---------->valid
Example 3:
package pack3;
j /trnport packl.Fish;
import packl. *;
j jimport static packl.Fish.GUPPY;
import static packl.Fish. *;
class B

public static void main(String args[]H


Fish f=Fish.STAR;
System.out.println(GUPPY);
}
}
Case 3:
enum Color

BLUE,RED
{
public void info(){
System.out.println("Dangerous color");

},GREEN;
public void info()
{
System.out.printl n(" Universal color");
}}
class Test{
public static void main(String args[]H
Color[] c=Color.values();
for(Color cl:c)

cl.info();
}}}
Output:
Universal color
Dangerous color
Universal color

448
Regular expression
• A Regular Expression is a expression which represents a group of Strings according to a
particular pattern.
Example:
• We can write a Regular Expression to represent all valid mail ids.
• We can write a Regular Expression to represent all valid mobile numbers.
The main important application areas of Regular Expression are:
• To implement validation logic.
• To develop Pattern matching applications.
• To develop translators like compilers, interpreters etc.
• To develop digital circuits.
• To develop communication protocols like TCP/IP, UDP etc.
Example:
import java.util.regex. ":
class RegularExpressionDemo

public static void main(String[] args)


{
int count=O;
Pattern p=Pattern.compile("ab");
Matcher m=p.matcher("abbbabbaba");
while(m.findO)
{
count++;
System .out. pri ntl n(m .sta rtO+ II ------ II +m.e nd 0+ II ------ II +m .group());

System.out.println("The no of occurences :"+count);

Output:
0------ 2 ------a b
4------6------a b
7------9------a b
The no of occurrences: 3
Pattern class:
• A Pattern object represents "compiled version of Regular Expression".
• We can create a Pattern object by using compileO method of Pattern class.

449
public static Pattern compile(String regex);
Example:
Pattern p=Pattern.compile(lab");
Note: if we refer API we will get more information about pattern class.
Matcher:
• A Matcher object can be used to match character sequences against a Regular
Expression. We can create a Matcher object by using matcher() method of Pattern
class.
public Matcher matcher(String target);
Matcher m=p.matcher("abbbabbaba");
Important methods of Matcher class:
1) boolean findl):
• It attempts to find next match and returns true if it is available otherwise returns false.
2) int startt]:
• Returns the start index of the match.
3) int endt):
• Returns the offset(equalize) after the last character matched.(or)
• Returns the end index of the matched.
4) String groupt]:
• Returns the matched Pattern.
Note: Pattern and Matcher classes are available in java.util.regex package.
Character classes:
[abc)-------------------Either 'a' or 'b' or 'c'
[I\abc)-----------------Except 'a' and 'b' and 'c'
[a-z)--------------------Any lower case alphabet symbol
[A-Z)--------------------Any upper case alphabet symbol
[a-zA-Z)----------------Any alphabet symbol
[0-9) --------------------Any digit from a to 9
[a-zA-ZO-9)------------Any alphanumeric character
Example:
import java.util.regex. ":
class RegularExpressionDemo

public static void main(String[) args)

Pattern p=Pattern.compile("x");
Matcher m=p.matcher("alb7@z#");
while(m.find())

450
System .out. pri ntl n(m .sta rtO+ II ------- II +rn .gro upO);

Output:
x=[abc] x= [I\abc] x=[O-9] x=[a-z]
O-------a 1-------1 1-------1 O-------a
2-------b 3-------7 3-------7 2-------b
4-------@ 5-------z
5-------z
6-------#
Predefined character classes:
\s---------------------space cha racter
\d---------------------Any digit from 0 to 9[0-9]
\ w---------------------Any word cha racter[a-zA-ZO-9]
. ---------------------Any character including special characters.
Example:
import java.util.regex. *;
class RegularExpressionDemo

public static void main(String[] args)


{
Pattern p=Pattern.compile("x");
Matcher m=p.matcher("alb7@z#");
while(m.findO)
{
System. out. pri ntl n(m .sta rtO+ II ------- II +rn .gro upO);

Output:
x=\ \5 x=\ \d x=\ \w _x_=_._
4------- 1-------1 O------a O-------a
3-------7 1-------1 1-------1
2------b 2-------b
3-------7 3-------7
6-------z 4-------
5-------@
6-------z
7-------#

451
Quantifiers:
• Quantifiers can be used to specify no of characters to match.
a----------------------- Exactly on e a' I

a+----------------------At least one 'a'


a*----------------------Any no of a's including zero number
a? ----------------------At most one a' I

Example:
import java.util.regex. *;
class RegularExpressionDemo

public static void main(String[] args)


{
Pattern p=Pattern.compile(lx");
Matcher m=p.matcher("abaabaaab");
while(m.findO)
{
System .out. pri ntl n(m .sta rtO+ "-------" +rn .gro upO);

Output:
x=a x=a+ x=a* x=a?
O-------a O-------a O-------a O-------a
2-------a 2-------aa 1------- 1-------
3-------a 5-------aaa 2-------aa 2-------a
5-------a 4------- 3-------a
6-------a 5-------aaa 4-------
7-------a 8------- 5-------a
9------- 6-------a
7-------a
8-------
9-------
Pattern class splitO method:
• Pattern class contains splitf) method to split the given string against a regular
expression.
Example 1:
import java.util.regex. *;
class RegularExpressionDemo

452
public static void main(String[] args)
{
Pattern p=Pattern.compile("\ \5");
String[] s=p.split("bhaskar software solutions");
for(String 51:5)
{
System.out.println(sl);/ /bhaskar
/ /software
/ /solutions

Example 2:
import java.util.regex. *;
class RegularExpressionDemo

public static void main(String[] args)


{
Pattern p=Pattern.compile("\ \."); (or)[.]
String[] s=p.split( u www.dugrajobs.com u );

for(String 51:5)
{
System.out.println(sl);/ /www
/ /dugrajobs
//com

String class splitO method:


• String class also contains splitl] method to split the given string against a regular
expression.
Example:
import java.util.regex. *;
class RegularExpressionDemo

public static void main(String[] args)


{
String s=u www.durgajobs.com ..;

453
String[] s1=s.split("\ \. ");
for(String s2:s1)
{
System.out.println(s2);/ /www
//durgajobs
//com

Note:
• String class split() method can take regular expression as argument where as pattern
class split() method can take target string as the argument.
StringTokenizer:
• This class present in java.util package.
• It is a specially designed class to perform string tokenization.
Example 1:
import java.uti!. *;
class RegularExpressionDemo

public static void main(String[] args)

StringTokenizer st=new StringTokenizer("durga software solutions");


while(st.hasMoreTokens())
{
System.out.printl n(st. nextToken());/ / durga
/ /software
/ /solutions

• The default regular expression for the StringTokenizer is space.


Example 2:
import java.uti!. *;
class RegularExpressionDemo

public static void main(String[] args)


{

454
StringTokenizer st=new StringTokenizer(ll,99,988I,I,");

1 J
Target
Regular Expression
/ /StringTokenizer st=new StringTokenizer(11,99,9881,1,");
while(st.hasMoreTokensO)

System.out.println(st.nextToken());/ /1
//99
//988

Requirement: Write a regular expression to represent all valid identifiers in yava language.
Rules:
The allowed characters are:
1) atoz,AtoZ,Oto9,-,#
2) The 1st character should be alphabet symbol only.
3) The length of the identifier should be at least 2.
Program:
import java.util.regex. *;
class RegularExpressionDemo

public static void main(String[] args)


{
Pattern p=Pattern.compile(l[a-zA-Z][a-zA-ZO-9-#]+"); (or)
Pattern p=Pattern .compile(" [a-zA-Z] [a-zA-ZO-9-#] [a-zA-ZO-9-#] * ");
Matcher m=p.matcher(args[O]);
if(m.findO&&m.group().equals(args[O]))
{
System.out.println("valid identifier");

else

System. out. pri ntl n(" inva Iid id entifier");

455
Output:
E:\scjp>javac RegularExpressionDemo.java
E:\scjp>java RegularExpressionDemo bhaskar
Valid identifier
E:\scjp>java RegularExpressionDemo ?bhaskar
Invalid identifier
Requirement: Write a regular expression to represent all mobile numbers.
Rules:
1) Should contain exactly 10 digits.
2) The 1st digit should be 7 to 9.
Program:
import java.util.regex. ":
class RegularExpressionDemo

public static void main(String[] args)


{
Pattern p=Pattern .compile("[7 -9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] ");
j jPattern p=Pattern.compile(" [7-9][0-9]{9}");
Matcher m=p.matcher(args[O]);
if(m.find()&&m.group().equals(args[O]))
{
$ystem.out.println("valid number");

else

$ystem.out.println("invalid number");

Analysis:
10 digits mobile:
[7-9] [0-9][0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] (or)
[7-9][0-9]{9}
Output:
E:\scjp>javac RegularExpressionDemo.java
E:\scjp>java RegularExpressionDemo 9989308279
Valid number
E:\scjp>java RegularExpressionDemo 6989308279

456
Invalid number
10 digits (or) 11 digits:
(O?[7-9][O-9]{9})
Output:
E:\scjp>javac RegularExpressionDemo.java
E:\scjp>java RegularExpressionDemo 9989308279
Valid number
E:\scjp>java RegularExpressionDemo 09989308279
Valid number
E:\scjp>java RegularExpressionDemo 919989308279
Invalid number
10 digits (Or) 11 digit (or) 12 digits:
(OI91)?[7-9][O-9]{9} (or)
(91)?( O?[7 -9] [O-9]{9})
E:\scjp>javac RegularExpressionDemo.java
E:\scjp>java RegularExpressionDemo 9989308279
Valid number
E:\scjp>java RegularExpressionDemo 09989308279
Valid number
E:\scjp>java RegularExpressionDemo 919989308279
Valid number
E:\scjp>java RegularExpressionDemo 69989308279
Invalid number
Requirement: Write a regular expression to represent all Mail Ids.
Program:
import java.util.regex. *;
class RegularExpressionDemo

public static void main(String[] args)


{
Pattern p=Pattern.compi le(" [a-zA-Z] [a-zA-ZO-9-.] *@[a-zA-ZO-9]+([.][a-zA-Z]+)+");
Matcher m=p.matcher(args[O]);
if(m.find()&&m.group().equals(args[O]))
{
System.out.println("valid mail id");

else

457
System.out.println("invalid mail id");

Output:
E:\scjp>javac RegularExpressionDemo.java
E:\scjp>java RegularExpressionDemo bhaskar86.vaka@gmail.com
Valid mail id
E:\scjp>java RegularExpressionDemo 999bhaskar86.vaka@gmail.com
Invalid mail id
E:\scjp>java RegularExpressionDemo 999bhaskar86.vaka@gmail.co9
Invalid mail id
Requirement: Write a program to extract all valid mobile numbers from a file.
Diazram:
9989308279
9989308279
9052142606
9700720065 ~ 9052142606
9700720065
6998930827
1111111111 output.txt
6666666666
3333333333
input.txt

Program:
import java.util.regex. ":
import java.io. *;
class RegularExpressionDemo

public static void main(String[] args)throws IOException


{
PrintWriter out=new PrintWriter("outputtxt");
BufferedReader br=new BufferedReader(new FileReader("input.txt"));
Pattern p=Pattern .compile(" [7 -9][O-9]{9}");
String line=br.readLineO;
while(line !=null)
{
Matcher m=p.matcher(line);
while(m.find())
{
out.pnntlntm.groupfj):

458
line=br.read Linet):

out.flusht):

Requirement: Write a program to extract all Mail IDS from the File.
Note: In the above program replace mobile number regular expression with MAIL ID regular
expression.
Requirement: Write a program to display all .txt file names present in E:\scjp folder.
Program:
import java.util.regex. *;
import java.io. *;
class RegularExpressionDemo

public static void main(String[] args)throws IOException


{
int count=O;
Pattern p=Pattern.compile("[a-zA-ZO-9-$.]+[.]txt");
File f=new File("E:\ \scjp");
String[] s=f.listl]:
for(String sl:s)
{
Matcher m=p.matcher(sl);
if(m.findO&&m.group().equals(sl))
{
count++;
System.out.printl n(sl);

System.out.println(count);

Output:
input.txt
output.txt
outut.txt
3

459

You might also like