You are on page 1of 460

1

Language Fundamentals
1. Identifiers
2. Reserved words
3. Data types
4. Literals
5. Arrays
6. Types of variabless
7. ar ar! "et#od
$. %ain "et#od
&. 'o""and line ar!("ents
1). *ava +odin! standards
Identifier: A na"e in ,ava pro!ra" is +alled identifier. It "ay be +lass na"e- "et#od na"e-
variable na"e and label na"e.
Example:

Rules to define java identifiers:
Rule 1: T#e only allowed +#ara+ters in ,ava identifiers are.
1/ a to 0
2/ A to 1
3/ ) to &
4/ 2
5/ 3
Rule 2: If we are (sin! any ot#er +#ara+ter we will !et +o"pile ti"e error.
Example:
1/ total2n("ber4444444valid
2/ Total5444444444444444444invalid
Rule 3: identifiers are not allowed to starts wit# di!it.
Example:
1/ A6'123444444444valid
2/ 123A6'444444444invalid
Rule 4: ,ava identifiers are +ase sensitive (p +o(rse ,ava lan!(a!e itself treated as +ase sensitive
lan!(a!e.



2

Example:
+lass Test7
int n("ber81)9
int :("ber82)9
int :;%6<R82)9 we +an differentiate wit# +ase.
int :(%b<r83)9
=>
Rule 5: T#ere is no len!t# li"it for ,ava identifiers b(t it is not re+o""ended to ta?e "ore t#an
15 len!t#s.
Rule 6: @e +anAt (se reserved words as identifiers.
Example: int if81)9 44444444444444invalid
Rule : All predefined ,ava +lass na"es and interfa+e na"es we (se as identifiers.
Example 1:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
int Ctrin!81)9
Cyste".o(t.printlnBCtrin!/9
==
!utput:
1)
Example 2:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
int R(nnable81)9
Cyste".o(t.printlnBR(nnable/9
==
!utput:
1)
<ven t#o(!# it is le!al to (se +lass na"es and interfa+e na"es as identifiers b(t it is not a !ood
pro!ra""in! pra+ti+e.
"#i$# of t#e follo%ing are valid java identifiers&






3



Reserved %ords:
In ,ava so"e identifiers are reserved to asso+iate so"e f(n+tionality or "eanin! s(+#
type of reserved identifiers are +alled reserved words.
'iagram:

Reserved %ords for data t(pes:
1/ byte
2/ s#ort
3/ int
4/ lon!
5/ float
6/ do(ble
7/ +#ar
$/ boolean
Reserved %ords for flo% $ontrol:
1/ if
2/ else
3/ swit+#
4/ +ase
5/ defa(lt
6/ for
7/ do

4

$/ w#ile
&/ brea?
1)/ +ontin(e
11/ ret(rn
)e(%ords for modifiers:
1/ p(bli+
2/ private
3/ prote+ted
4/ stati+
5/ final
6/ abstra+t
7/ syn+#roni0ed
$/ native
&/ stri+tfpB1.2 version/
1)/ transient
11/ volatile
)e(%ords for ex$eption #andling:
1/ try
2/ +at+#
3/ finally
4/ t#row
5/ t#rows
6/ assertB1.4 version/
*lass related +e(%ords:
1/ +lass
2/ pa+?a!e
3/ i"port
4/ eEtends
5/ i"ple"ents
6/ interfa+e
!,je$t related +e(%ords:
1/ new
2/ instan+eof
3/ s(per
4/ t#is
-oid return t(pe +e(%ord:
If a "et#od wonAt ret(rn anyt#in! +o"p(lsory t#at "et#od s#o(ld be de+lared wit# t#e
void ret(rn type in ,ava b(t it is optional in 'FF.

5

1/ void
.nused +e(%ords:
goto. 'reate several proble"s in old lan!(a!es and #en+e it is banned in ,ava.
*onst: ;se final instead of t#is.
6y "ista?e if we are (sin! t#ese ?eywords in o(r pro!ra" we will !et +o"pile ti"e
error.
Reserved literals:
1/ tr(e val(es for boolean data type.
2/ false
3/ n(ll44444444444444444 defa(lt val(e for ob,e+t referen+e.
Enum:
T#is ?eyword introd(+ed in 1.5v to define a !ro(p of na"ed +onstants
Example:
en(" 6eer
7
GH- R'- GI- HI9
=
/ote: All reserved words in ,ava +ontain only lower+ase alp#abet sy"bols.
:ew ?eywords are.
Ctri+tfp444444444441.2
Assert44444444444441.4
<n("444444444444441.5
"#i$# of t#e follo%ing list $ontains onl( java reserved %ords&
1/ final- finally- finali0e Binvalid/JJ#ere finali0e is a "et#od in Ib,e+t +lass.
2/ t#row- t#rows- t#rownBinvalid/JJt#rown is not available in ,ava
3/ brea?- +ontin(e- ret(rn- eEitBinvalid/JJeEit is not reserved ?eyword
4/ !oto- +onstantBinvalid/JJ#ere +onstant is not reserved ?eyword
5/ byte- s#ort- Inte!er- lon!Binvalid/JJ#ere Inte!er is a wrapper +lass
6/ eEtends- i"ple"ents- i"portsBinvalid/JJi"ports ?eyword is not available in ,ava
7/ finali0e- syn+#roni0edBinvalid/JJfinali0e is a "et#od in Ib,e+t +lass
$/ instan+eof- si0eIfBinvalid/JJsi0eIf is not reserved ?eyword
&/ new- deleteBinvalid/JJdelete is not a ?eyword
1)/ :one of t#e aboveBvalid/
"#i$# of t#e follo%ing are valid java +e(%ords&
1/ p(bli+Bvalid/
2/ stati+Bvalid/
3/ voidBvalid/
4/ "ainBinvalid/
5/ Ctrin!Binvalid/
6/ ar!sBinvalid/

6

'ata t(pes: <very variable #as a type- every eEpression #as a type and all types are stri+tly
define "ore over every assi!n"ent s#o(ld be +#e+?ed by t#e +o"piler by t#e type
+o"patibility #en+e ,ava lan!(a!e is +onsidered as stron!ly typed lan!(a!e.
0ava is pure o,je$t oriented programming or not&
*ava is not +onsidered as p(re ob,e+t oriented pro!ra""in! lan!(a!e be+a(se several
oops feat(res Bli?e "(ltiple in#eritan+e- operator overloadin!/ are not s(pported by
,ava "oreover we are dependin! on pri"itive data types w#i+# are non ob,e+ts.
'iagram:

<E+ept 6oolean and +#ar all re"ainin! data types are +onsidered as si!ned data types
be+a(se we +an represent bot# KFveL andL4veL n("bers.
1(te:
Ci0e. 1byte B$bits/
%aEval(e. F127
%inval(e.412$
Ran!e.412$to 127D42
7
to 2
7
41>


T#e "ost si!nifi+ant bit a+ts as si!n bit. K)L "eans KFveL n("ber and K1L "eans KMveL
n("ber.
KFveL n("bers will be represented dire+tly in t#e "e"ory w#ereas KMveL n("bers will
be represented in 2As +o"ple"ent for".

7

Example:
byte b81)9
byte b2813)9JJ'.<.possible loss of pre+ision
byte b81).59JJ'.<.possible loss of pre+ision
byte b8tr(e9JJ'.<.in+o"patible types
byte b8Nd(r!aN9JJ'.<.in+o"patible types
byte data type is best s(itable if we are #andlin! data in ter"s of strea"s eit#er fro"
t#e file or fro" t#e networ?.
2#ort:
T#e "ost rarely (sed data type in ,ava is s#ort.
Ci0e. 2 bytes
Ran!e. 43276$ to 32767B42
15
to 2
15
41/
Example:
s#ort s813)9
s#ort s83276$9JJ'.<.possible loss of pre+ision
s#ort s8tr(e9JJ'.<.in+o"patible types
C#ort data type is best s(itable for 16 bit pro+essors li?e $)$6 b(t t#ese pro+essors are
+o"pletely o(tdated and #en+e t#e +orrespondin! s#ort data type is also o(t data type.
Int:
T#is is "ost +o""only (sed data type in ,ava.
Ci0e. 4 bytes
Ran!e.421474$364$ to 21474$3647 B42
31
to 2
31
41/
Example:
int i813)9
int i81).59JJ'.<.possible loss of pre+ision
int i8tr(e9JJ'.<.in+o"patible types
long:
@#enever int is not eno(!# to #old bi! val(es t#en we s#o(ld !o for lon! data type.
Example:
To #old t#e no. If +#ara+ters present in a bi! file int "ay not eno(!# #en+e t#e ret(rn
type of len!t#B/ "et#od is lon!.
lon! l8f.len!t#B/9JJf is a file
Ci0e. $ bytes
Ran!e.42
63
to 2
63
41
/ote: All t#e above data types Bbyte- s#ort- int and lon!/ +an be (sed to represent w#ole
n("bers. If we want to represent real n("bers t#en we s#o(ld !o for floatin! point data types.
Floating 3oint 'ata t(pes:
float dou,le
1/ If we want to 5 to 6 de+i"al pla+es of
a++(ra+y t#en we s#o(ld !o for float.

1/ If we want to 14 to 15 de+i"al pla+es
of a++(ra+y t#en we s#o(ld !o for
do(ble.
2/ Ci0e.4 bytes. 2/ Ci0e.$ bytes.
3/ Ran!e.43.4e3$ to 3.4e3$. 3/ 41.7e3)$ to1.7e3)$.

$

4/ float follows sin!le pre+ision. 4/ do(ble follows do(ble pre+ision.
,oolean data t(pe:
Ci0e. :ot appli+able Bvirt(al "a+#ine dependent/
Ran!e. :ot appli+able b(t allowed val(es are tr(e or false.
"#i$# of t#e follo%ing ,oolean de$larations are valid&
Example 1:
boolean b8tr(e9
boolean b8Tr(e9JJ'.<.+annot find sy"bol
boolean b8NTr(eN9JJ'.<.in+o"patible types
boolean b8)9JJ'.<.in+o"patible types
Example 2:

*#ar data t(pe:
In ,ava we are allowed to (se any worldwide alp#abets +#ara+ter and ,ava is ;ni+ode
based to represent all t#ese +#ara+ters one byte is not eno(!# +o"p(lsory we s#o(ld !o
for 2 bytes.
2i4e: 2 ,(tes
Range: 5 to 65535
Example:
+#ar +#18&79
+#ar +#28655369JJ'.<.possible loss of pre+ision
2ummar( of java primitive data t(pe:
data t(pe si4e Range *orresponding
"rapper $lass
'efault value
6yte 1 byte 42
7
to 2
7
41
B412$ to 127/
6yte )
C#ort 2 bytes 42
15
to 2
15
41
B43276$ to
32767/
C#ort )
Int 4 bytes 42
31
to 2
31
41
B421474$364$ to
21474$3647/
Inte!er )
Lon! $ bytes 42
63
to 2
63
41 Lon! )
Hloat 4 bytes 43.4e3$ to
3.4e3$
Hloat ).)

&

Do(ble $ bytes 41.7e3)$ to
1.7e3)$
Do(ble ).)
6oolean :ot appli+able :ot
appli+ableBb(t
allowed val(es
tr(eOfalse/
6oolean false
'#ar 2 bytes ) to 65535 '#ara+ter )Brepresents
blan? spa+e/
T#e defa(lt val(e for t#e ob,e+t referen+es is Kn(llL.
Literals:
Any +onstant val(e w#i+# +an be assi!ned to t#e variable is +alled literal.
Example:

Integral Literals: Hor t#e inte!ral data types Bbyte- s#ort- int and lon!/ we +an spe+ify literal
val(e in t#e followin! ways.
1/ 'e$imal literals: Allowed di!its are ) to &.
Example: int E81)9
2/ !$tal literals: Allowed di!its are ) to 7. Literal val(e s#o(ld be prefiEed wit# 0ero.
Example: int E8)1)9
3/ 6exa 'e$imal literals: T#e allowed di!its are ) to &- A to 1. Hor t#e eEtra di!its we +an
(se bot# (pper +ase and lower +ase +#ara+ters. T#is is one of very few areas w#ere ,ava
is not +ase sensitive. Literal val(e s#o(ld be prefiEed wit# oEBor/oP.
Example: int E8)E1)9
T#ese are t#e only possible ways to spe+ify inte!ral literal.
"#i$# of t#e follo%ing are valid de$larations&
1/ int E8)7$69JJ'.<.inte!er n("ber too lar!e. )7$6Binvalid/
2/ int E8)EHA'<9Bvalid/
3/ int E8)Ebeef9Bvalid/
4/ int E8)E6eer9JJ'.<.Q9Q eEpe+tedBinvalid/
JJ.int E8)E6eer9
R
5/ int E8)Eabb2+d9Bvalid/
Example:
int E81)9
int y8)1)9
int 08)E1)9
Cyste".o(t.printlnBEFN4444NFyFN4444NF0/9 JJ1)4444$444416
6y defa(lt every inte!ral literal is int type b(t we +an spe+ify eEpli+itly as lon! type by
s(ffiEin! wit# s"all KlL Bor/ +apital KLL.


1)

Example:
int E81)9Bvalid/
lon! l81)L9Bvalid/
lon! l81)9Bvalid/
int E81)l9JJ'.<.possible loss of pre+isionBinvalid/
T#ere is no dire+t way to spe+ify byte and s#ort literals eEpli+itly. 6(t w#enever we are
assi!nin! inte!ral literal to t#e byte variables and its val(e wit#in t#e ran!e of byte
+o"piler a(to"ati+ally treats as byte literal. Ci"ilarly s#ort literal also.
Example:
byte b81)9Bvalid/
byte b813)9JJ'.<.possible loss of pre+isionBinvalid/
s#ort s8327679Bvalid/
s#ort s83276$9JJ'.<.possible loss of pre+isionBinvalid/
Floating 3oint Literals: Hloatin! point literal is by defa(lt do(ble type b(t we +an spe+ify
eEpli+itly as float type by s(ffiEin! wit# f or H.
Example:
float f8123.4569JJ'.<.possible loss of pre+isionBinvalid/
float f8123.456f9Bvalid/
do(ble d8123.4569Bvalid/
@e +an spe+ify eEpli+itly floatin! point literal as do(ble type by s(ffiEin! wit# d or D.
Example:
do(ble d8123.456D9
@e +an spe+ify floatin! point literal only in de+i"al for" and we +anAt spe+ify in o+tal
and #eEade+i"al for"s.
Example:
do(ble d8123.4569Bvalid/
do(ble d8)123.4569Bvalid/
do(ble d8)E123.4569JJ'.<."alfor"ed floatin! point literalBinvalid/
"#i$# of t#e follo%ing floating point de$larations are valid&
1/ float f8123.4569JJ'.<.possible loss of pre+isionBinvalid/
2/ float f8123.456D9JJ'.<.possible loss of pre+isionBinvalid/
3/ do(ble d8)E123.4569JJ'.<."alfor"ed floatin! point literalBinvalid/
4/ do(ble d8)EHa+e9Bvalid/
5/ do(ble d8)E6eef9Bvalid/
@e +an assi!n inte!ral literal dire+tly to t#e floatin! point data types and t#at inte!ral
literal +an be spe+ified in o+tal and SeEa de+i"al for" also.
Example:
do(ble d8)E6eef9
Cyste".o(t.printlnBd/9JJ4$$7&.)
6(t we +anAt assi!n floatin! point literal dire+tly to t#e inte!ral types.
Example:
int E81).)9JJ'.<.possible loss of pre+ision
@e +an spe+ify floatin! point literal even in eEponential for" alsoBsi!nifi+ant notation/.

11

Example:
do(ble d81)e29JJ88T1)U1)
2
Bvalid/
Cyste".o(t.printlnBd/9JJ1))).)
float f81)e29JJ'.<.possible loss of pre+isionBinvalid/
float f81)e2H9Bvalid/
1oolean literals: T#e only allowed val(es for t#e boolean type are tr(e Bor/ false w#ere +ase is
i"portant.
Example:
1/ boolean b8tr(e9Bvalid/
2/ boolean b8)9JJ'.<.in+o"patible typesBinvalid/
3/ boolean b8Tr(e9JJ'.<.+annot find sy"bolBinvalid/
4/ boolean b8Ntr(eN9JJ'.<.in+o"patible typesBinvalid/
*#ar literals:
1/ A +#ar literal +an be represented as sin!le +#ara+ter wit#in sin!le V(otes.
Example:
1/ +#ar +#8QaQ9Bvalid/
2/ +#ar +#8a9JJ'.<.+annot find sy"bolBinvalid/
3/ +#ar +#8NaN9JJ'.<.in+o"patible typesBinvalid/
4/ +#ar +#8QabQ9JJ'.<.(n+losed +#ara+ter literalBinvalid/
2/ @e +an spe+ify a +#ar literal as inte!ral literal w#i+# represents ;ni+ode of t#at
+#ara+ter. @e +an spe+ify t#at inte!ral literal eit#er in de+i"al or o+tal or #eEade+i"al
for" b(t allowed val(es ran!e is ) to 65535.
Example:
1/ +#ar +#8&79Bvalid/
2/ +#ar +#8)EHa+e9 Bvalid/
Cyste".o(t.printlnB+#/9JJW
3/ +#ar +#8655369JJ'.<. possible loss of pre+isionBinvalid/
3/ @e +an represent a +#ar literal by ;ni+ode representation w#i+# is not#in! b(t XY(EEEEA.
Example:
1/ +#ar +#18QY())61Q9
Cyste".o(t.printlnB+#1/9JJa
2/ +#ar +#28Y())629JJ'.<.+annot find sy"bol
3/ +#ar +#38QYifa+eQ9JJ'.<.ille!al es+ape +#ara+ter
4/ <very es+ape +#ara+ter in ,ava a+ts as a +#ar literal.
Example:
1/ +#ar +#8QYnQ9JJBvalid/
2/ +#ar +#8QYlQ9JJ'.<.ille!al es+ape +#ara+terBinvalid/
Es$ape *#ara$ter 'es$ription
Yn :ew line
Yt Sori0ontal tab
Yr 'arria!e ret(rn
Yf Hor" feed
Yb 6a+? spa+e +#ara+ter

12

YA Cin!le V(ote
YL Do(ble V(ote
YY 6a+? spa+e
"#i$# of t#e follo%ing $#ar de$larations are valid&
1/ +#ar +#8a9JJ'.<.+annot find sy"bolBinvalid/
2/ +#ar +#8QabQ9JJ'.<.(n+losed +#ara+ter literalBinvalid/
3/ +#ar +#8655369JJ'.<.possible loss of pre+isionBinvalid/
4/ +#ar +#8Y(fa+e9JJ'.<.ille!al +#ara+ter. Y642)6Binvalid/
5/ +#ar +#8QJnQ9JJ'.<.(n+losed +#ara+ter literalBinvalid/
6/ none of t#e above.Bvalid/
2tring literals:
Any seV(en+e of +#ara+ters wit# in do(ble V(otes is treated as Ctrin! literal.
Example:
Ctrin! s8Nb#as?arN9Bvalid/
'iagram:


7rra(s
1/ Introd(+tion
2/ Array de+laration
3/ Array +onstr(+tion
4/ Array initiali0ation
5/ Array de+laration- +onstr(+tion- initiali0ation in a sin!le line.
6/ len!t# s len!t#B/ "et#od
7/ Anony"o(s arrays
$/ Array ele"ent assi!n"ents
&/ Array variable assi!n"ents.
An array is an indeEed +olle+tion of fiEed n("ber of #o"o!eneo(s data ele"ents.
T#e "ain advanta!e of arrays is we +an represent "(ltiple val(es wit# t#e sa"e na"e
so t#at readability of t#e +ode will be i"proved.
6(t t#e "ain disadvanta!e of arrays is.
HiEed in si0e t#at is on+e we +reated an array t#ere is no +#an+e of in+reasin! or
de+reasin! t#e si0e based on o(r reV(ire"ent t#at is to (se arrays +on+ept +o"p(lsory
we s#o(ld ?now t#e si0e in advan+e w#i+# "ay not possible always.
@e +an resolve t#is proble" by (sin! +olle+tions.
7rra( de$larations:
2ingle dimensional arra( de$laration:


13

Example:
intD> a9JJre+o""ended to (se be+a(se na"e is +learly separated fro" t#e type
int D>a9
int aD>9
At t#e ti"e of de+laration we +anAt spe+ify t#e si0e ot#erwise we will !et +o"pile ti"e
error.
Example:
intD> a9JJvalid
intD5> a9JJinvalid
Two dimensional array declaration:
Example:
int[][] a;
int [][]a;
int a[][]; All are valid.
int[] []a;
int[] a[];
int []a[];
8#ree dimensional arra( de$laration:
Example:
intD>D>D> a9
int D>D>D>a9
int aD>D>D>9
intD> D>D>a9
intD> aD>D>9 7ll are valid9
intD> D>aD>9
intD>D> D>a9
intD>D> aD>9
int D>aD>D>9
int D>D>aD>9
"#i$# of t#e follo%ing de$larations are valid&
1/ intD> a1-b19JJa41-b41Bvalid/
2/ intD> a2D>-b29JJa42-b41Bvalid/
3/ intD> D>a3-b39JJa42-b42Bvalid/
4/ intD> a-D>b9JJ'.<.ZidentifierT eEpe+tedBinvalid/
If we want to spe+ify t#e di"ension before t#e variable t#at r(le is appli+able only for
t#e 1
st
variable. Ce+ond variable onwards we +anAt apply in t#e sa"e de+laration.



14

Example:

7rra( $onstru$tion: <very array in ,ava is an ob,e+t #en+e we +an +reate by (sin! new operator.
Example:
intD> a8new intD3>9
'iagram:

Hor every array type +orrespondin! +lasses are available b(t t#ese +lasses are part of
,ava lan!(a!e and not available to t#e pro!ra""er level.
7rra( 8(pe $orresponding $lass name
intD> DI
intD>D> DDI
do(bleD>
.
.
DD
.
.
Rule 1:
At t#e ti"e of array +reation +o"p(lsory we s#o(ld spe+ify t#e si0e ot#erwise we will
!et +o"pile ti"e error.
Example:
intD> a8new intD3>9
intD> a8new intD>9JJ'.<.array di"ension "issin!
Rule 2:
It is le!al to #ave an array wit# si0e 0ero in ,ava.
Example:
intD> a8new intD)>9
Cyste".o(t.printlnBa.len!t#/9JJ)
Rule 3:
If we are ta?in! array si0e wit# 4ve int val(e t#en we will !et r(nti"e eE+eption sayin!
:e!ativeArrayCi0e<E+eption.
Example:
intD> a8new intD43>9JJR.<.:e!ativeArrayCi0e<E+eption
Rule 4:
T#e allowed data types to spe+ify array si0e are byte- s#ort- +#ar- int. 6y "ista?e if we
are (sin! any ot#er type we will !et +o"pile ti"e error.
Example:
intD> a8new intDQaQ>9JJBvalid/

15

byte b81)9
intD> a8new intDb>9JJBvalid/
s#ort s82)9
intD> a8new intDs>9JJBvalid/
intD> a8new intD1)l>9JJ'.<.possible loss of pre+isionJJBinvalid/
intD> a8new intD1).5>9JJ'.<.possible loss of pre+isionJJBinvalid/
Rule 5:
T#e "aEi"(" allowed array si0e in ,ava is "aEi"(" val(e of int si0e D21474$3647>.
Example:
intD> a18new intD21474$3647>9Bvalid/
intD> a28new intD21474$364$>9JJ'.<.inte!er n("ber too lar!e. 21474$364$Binvalid/
8%o dimensional arra( $reation:
In ,ava "(ltidi"ensional arrays are i"ple"ented as array of arrays approa+# b(t not
"atriE for".
T#e "ain advanta!e of t#is approa+# is to i"prove "e"ory (tili0ation.
Example 1:
intD>D> a8new intD2>D>9
aD)>8new intD3>9
aD1>8new intD2>9
'iagram:

Example 2:
intD>D>D> a8new intD2>D>D>9
aD)>8new intD3>D>9
aD)>D)>8new intD1>9
aD)>D1>8new intD2>9
aD)>D2>8new intD3>9
aD1>8new intD2>D2>9
'iagram:






16



"#i$# of t#e follo%ing de$larations are valid&
1/ intD> a8new intD>JJ'.<. array di"ension "issin!Binvalid/
2/ intD>D> a8new intD3>D4>9Bvalid/
3/ intD>D> a8new intD3>D>9Bvalid/
4/ intD>D> a8new intD>D4>9JJ'.<.Q>Q eEpe+tedBinvalid/
5/ intD>D>D> a8new intD3>D4>D5>9Bvalid/
6/ intD>D>D> a8new intD3>D4>D>9Bvalid/
7/ intD>D>D> a8new intD3>D>D5>9JJ'.<.Q>Q eEpe+tedBinvalid/
7rra( initiali4ation. @#enever we are +reatin! an array every ele"ent is initiali0ed wit# defa(lt
val(e a(to"ati+ally.
Example 1:
intD> a8new intD3>9
Cyste".o(t.printlnBa/9JJDI[3e25a5

Cyste".o(t.printlnBaD)>/9JJ)
'iagram:

/ote: @#enever we are tryin! to print any ob,e+t referen+e internally toCtrin!B/ "et#od will be
eEe+(ted w#i+# is i"ple"ented by defa(lt to ret(rn t#e followin!.
+lassna"e[#eEade+i"alstrin!representationof#as#+ode.
Example 2:

Cyste".o(t.printlnBa/9JJDDI[3e25a5
Cyste".o(t.printlnBaD)>/9JJDI[1&$21f
Cyste".o(t.printlnBaD)>D)>/9JJ)
'iagram:

17


Example 3:
intD>D> a8new intD2>D>9
Cyste".o(t.printlnBa/9JJDDI[3e25a5
Cyste".o(t.printlnBaD)>/9JJn(ll
Cyste".o(t.printlnBaD)>D)>/9JJR.<.:(ll\ointer<E+eption
'iagram:

In+e we +reated an array all its ele"ents by defa(lt initiali0ed wit# defa(lt val(es. If we
are not satisfied wit# t#ose defa(lt val(es t#en we +an replays wit# o(r +(sto"i0ed
val(es.
Example:
intD> a8new intD4>9
aD)>81)9
aD1>82)9
aD2>83)9
aD3>84)9
aD4>85)9JJR.<.ArrayIndeEI(tIf6o(nds<E+eption. 4
aD44>86)9JJR.<.ArrayIndeEI(tIf6o(nds<E+eption. 44
'iagram:

/ote: if we are tryin! to a++ess array ele"ent wit# o(t of ran!e indeE we will !et R(nti"e
<E+eption sayin! ArrayIndeEI(tIf6o(nds<E+eption.
'e$laration $onstru$tion and initiali4ation of an arra( in a single line:
@e +an perfor" de+laration +onstr(+tion and initiali0ation of an array in a sin!le line.
Example:


1$

+#arD> +#87QaQ-QeQ-QiQ-QoQ-Q(Q=9Bvalid/
Ctrin!D> s87NbalayyaN-Nven?iN-Nna!N-N+#ir(N=9Bvalid/
@e +an eEtend t#is s#ort +(t even for "(lti di"ensional arrays also.

Example:
intD>D> a8771)-2)-3)=-74)-5)==9]
'iagram:

Example:
intD>D>D> a87771)-2)-3)=-74)-5)==-776)=-77)-$)=-7&)-1))-11)===9
'iagram:

intD>D>D> a87771)-2)-3)=-74)-5)==-776)=-77)-$)=-7&)-1))-11)===9
Cyste".o(t.printlnBaD)>D1>D1>/9JJ5)Bvalid/
Cyste".o(t.printlnBaD1>D)>D2>/9JJR.<.ArrayIndeEI(tIf6o(nds<E+eption. 2Binvalid/
Cyste".o(t.printlnBaD1>D2>D1>/9JJ1))Bvalid/
Cyste".o(t.printlnBaD1>D2>D2>/9JJ11)Bvalid/
Cyste".o(t.printlnBaD2>D1>D)>/9JJR.<.ArrayIndeEI(tIf6o(nds<E+eption. 2Binvalid/
Cyste".o(t.printlnBaD1>D1>D1>/9JJ$)Bvalid/
If we want to (se t#is s#ort +(t +o"p(lsory we s#o(ld perfor" de+laration- +onstr(+tion
and initiali0ation in a sin!le line. If we are tryin! to divide into "(ltiple lines t#en we will
!et +o"pile ti"e error.
Example:


lengt# -s lengt#:;:
lengt#:
1/ It is t#e final variable appli+able only for arrays.
2/ It represents t#e si0e of t#e array.

1&

Example:
intD> E8new intD3>9
Cyste".o(t.printlnBE.len!t#B//9JJ'.<. +annot find sy"bol
Cyste".o(t.printlnBE.len!t#/9JJ3

lengt#:; met#od:
1/ It is a final "et#od appli+able for Ctrin! ob,e+ts.
2/ It ret(rns t#e no of +#ara+ters present in t#e Ctrin!.
Example:
Ctrin! s8Nb#as?arN9
Cyste".o(t.printlnBs.len!t#/9JJ'.<.+annot find sy"bol
Cyste".o(t.printlnBs.len!t#B//9JJ7
In "(ltidi"ensional arrays len!t# variable represents only base si0e b(t not total si0e.
Example:
intD>D> a8new intD6>D3>9
Cyste".o(t.printlnBa.len!t#/9JJ6
Cyste".o(t.printlnBaD)>.len!t#/9JJ3
'iagram:

len!t# variable appli+able only for arrays w#ere as len!t#B/"et#od is appli+able for
Ctrin! ob,e+ts.
7non(mous 7rra(s:
Co"eti"es we +an +reate an array wit#o(t na"e s(+# type of na"eless arrays are
+alled anony"o(s arrays.
T#e "ain ob,e+tive of anony"o(s arrays is Kjust for instant useL.
@e +an +reate anony"o(s array as follows.
new intD>71)-2)-3)-4)=9Bvalid/
new intD>D>771)-2)=-73)-4)==9Bvalid/
At t#e ti"e of anony"o(s array +reation we +anAt spe+ify t#e si0e ot#erwise we will !et
+o"pile ti"e error.
Example:
new intD3>71)-2)-3)-4)=9JJ'.<.Q9Q eEpe+tedBinvalid/
new intD>71)-2)-3)-4)=9Bvalid/
6ased on o(r pro!ra""in! reV(ire"ent we +an !ive t#e na"e for anony"o(s array
t#en it is no lon!er anony"o(s.
Example:

2)

intD> a8new intD>71)-2)-3)-4)=9Bvalid/
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBs("Bnew intD>71)-2)-3)-4)=//9JJ1))
=
p(bli+ stati+ int s("BintD> E/
7
int total8)9
forBint E1.E/
7
total8totalFE19
=
ret(rn total9
=
=
7rra( element assignments:
*ase 1: In t#e +ase of pri"itive array as array ele"ent any type is allowed w#i+# +an be
pro"oted to de+lared type.
Example 1: Hor t#e int type arrays t#e allowed array ele"ent types are byte- s#ort- +#ar int.
intD> a8new intD1)>9
aD)>8&79JJBvalid/
aD1>8QaQ9JJBvalid/
byte b81)9
aD2>8b9JJBvalid/
s#ort s82)9
aD3>8s9JJBvalid/
aD4>81)l9JJ'.<.possible loss of pre+ision
Example 2: Hor float type arrays t#e allowed ele"ent types are byte- s#ort- +#ar- int- lon!- float.
*ase 2: In t#e +ase of Ib,e+t type arrays as array ele"ents we +an provide eit#er de+lared type
ob,e+ts or its +#ild +lass ob,e+ts.
Example 1:
Ib,e+tD> a8new Ib,e+tD1)>9
aD)>8new Inte!erB1)/9JJBvalid/
aD1>8new Ib,e+tB/9JJBvalid/
aD2>8new Ctrin!BNb#as?arN/9JJBvalid/

21

Example 2:
:("berD> n8new :("berD1)>9
nD)>8new Inte!erB1)/9JJBvalid/
nD1>8new Do(bleB1).5/9JJBvalid/
nD2>8new Ctrin!BNb#as?arN/9JJ'.<.in+o"patible typesJJBinvalid/
'iagram:

*ase 3: In t#e +ase of interfa+e type arrays as array ele"ents we +an provide its i"ple"ented
+lass ob,e+ts.
Example:
R(nnableD> r8new R(nnableD1)>9
rD)>8new T#readB/9
rD1>8new Ctrin!BNb#as?arN/9JJ'.<. in+o"patible types
7rra( 8(pe 7llo%ed Element 8(pe
1/ \ri"itive arrays. 1/ Any type w#i+# +an be pro"oted to
de+lared type.
2/ Ib,e+t type arrays.

2/ <it#er de+lared type or its +#ild +lass
ob,e+ts.
3/ Interfa+e type arrays. 3/ Its i"ple"ented +lass ob,e+ts.
4/ Abstra+t +lass type arrays. 4/ Its +#ild +lass ob,e+ts are allowed.
7rra( varia,le assignments:
*ase 1:
<le"ent level pro"otions are not appli+able at array level.
A +#ar val(e +an be pro"oted to int type b(t +#ar array +annot be pro"oted to int
array.
Example:
intD> a871)-2)-3)=9
+#arD> +#87QaQ-QbQ-Q+Q=9
intD> b8a9JJBvalid/
intD> +8+#9JJ'.<.in+o"patible typesBinvalid/
"#i$# of t#e follo%ing promotions are valid&

22


/ote: In t#e +ase of ob,e+t type arrays +#ild type array +an be assi!n to parent type array
variable.

Example:
Ctrin!D> s87NAN-N6N=9
Ib,e+tD> o8s9
*ase 2: @#enever we are assi!nin! one array to anot#er array internal ele"ents wonAt be +opy
,(st referen+e variables will be reassi!ned #en+e si0es are not i"portant b(t types "(st be
"at+#ed.
Example:
intD> a871)-2)-3)-4)-5)-6)-7)=9
intD> b87$)-&)=9
a8b9JJBvalid/
b8a9JJBvalid/
'iagram:

*ase 3: @#enever we are assi!nin! one array to anot#er array di"ensions "(st be "at+#ed
t#at is in t#e pla+e of one di"ensional array we s#o(ld provide t#e sa"e type only ot#erwise
we will !et +o"pile ti"e error.
Example:
intD>D> a8new intD3>D>9
aD)>8new intD4>D5>9JJ'.<.in+o"patible typesBinvalid/
aD)>81)9JJ'.<.in+o"patible typesBinvalid/
aD)>8new intD4>9JJBvalid/
/ote: @#enever we are perfor"in! array assi!n"ents t#e types and di"ensions "(st be
"at+#ed b(t si0es are not i"portant.
Example 1:

23

intD>D> a8new intD3>D2>9
aD)>8new intD3>9
aD1>8new intD4>9
a8new intD4>D3>9
'iagram:








Total #ow "any ob,e+ts +reatedW
7ns: 11
Sow "any ob,e+ts eli!ible for ^'. 6
Example 2:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!D> ar!#87NAN-N6N=9
ar!s8ar!#9
Cyste".o(t.printlnBar!s.len!t#/9JJ2
forBint i8)9iZ8ar!s.len!t#9iFF/
7
Cyste".o(t.printlnBar!sDi>/9
=
=
=
!utput:
,ava Test E y
R9E: ArrayIndeEI(tIf6o(nds<E+eption. 2
,ava Test E

24

R9E: ArrayIndeEI(tIf6o(nds<E+eption. 2
,ava Test
R9E: ArrayIndeEI(tIf6o(nds<E+eption. 2
/ote: Repla+e wit# iZar!s.len!t#.
Example 3:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!D> ar!#87NAN-N6N=9
ar!s8ar!#9
Cyste".o(t.printlnBar!s.len!t#/9JJ2
forBint i8)9iZar!s.len!t#9iFF/
7
Cyste".o(t.printlnBar!sDi>/9
=
=
=
!utput:
2
A
6
8(pes of -aria,les
6ased t#e type of val(e represented by t#e variable all variables are divided into 2
types. T#ey are.
1/ \ri"itive variables
2/ Referen+e variables
\ri"itive variables. \ri"itive variables +an be (sed to represent pri"itive val(es.
Example: int E81)9
Referen$e varia,les: Referen+e variables +an be (sed to refer ob,e+ts.
Example: Ct(dent s8new Ct(dentB/9
'iagram:

6ased on t#e p(rpose and position of de+laration all variables are divided into t#e
followin! 3 types.
1/ Instan+e variables
2/ Ctati+ variables
3/ Lo+al variables
Instan$e varia,les:

25

If t#e val(e of a variable is varied fro" ob,e+t to ob,e+t s(+# type of variables are +alled
instan+e variables.
Hor every ob,e+t a separate +opy of instan+e variables will be +reated.
Instan+e variables will be +reated at t#e ti"e of ob,e+t +reation and destroyed at t#e
ti"e of ob,e+t destr(+tion #en+e t#e s+ope of instan+e variables is eEa+tly sa"e as
s+ope of ob,e+ts.
Instan+e variables will be stored on t#e #eap as t#e part of ob,e+t.
Instan+e variables s#o(ld be de+lared wit# in t#e +lass dire+tly b(t o(tside of any
"et#od or blo+? or +onstr(+tor.
Instan+e variables +an be a++essed dire+tly fro" Instan+e area. 6(t +annot be a++essed
dire+tly fro" stati+ area.
6(t by (sin! ob,e+t referen+e we +an a++ess instan+e variables fro" stati+ area.
Example:
+lass Test
7
int i81)9
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
JJCyste".o(t.printlnBi/9JJ'.<.non4stati+ variable i +annot be referen+ed fro" a
stati+ +onteEtBinvalid/
Test t8new TestB/9
Cyste".o(t.printlnBt.i/9JJ1)Bvalid/
t."et#odIneB/9
=
p(bli+ void "et#odIneB/
7
Cyste".o(t.printlnBi/9JJ1)Bvalid/
=
=
Hor t#e instan+e variables it is not reV(ired to perfor" initiali0ation *% will always
provide defa(lt val(es.
Example:
+lass Test
7
boolean b9
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t8new TestB/9

26

Cyste".o(t.printlnBt.b/9JJfalse
=
=
Instan+e variables also ?nown as ob,e+t level variables or attrib(tes.
2tati$ varia,les:
If t#e val(e of a variable is not varied fro" ob,e+t to ob,e+t s(+# type of variables is not
re+o""ended to de+lare as instan+e variables. @e #ave to de+lare s(+# type of
variables at +lass level by (sin! stati+ "odifier.
In t#e +ase of instan+e variables for every ob,e+t a separate +opy will be +reated b(t in
t#e +ase of stati+ variables for entire +lass only one +opy will be +reated and s#ared by
every ob,e+t of t#at +lass.
Ctati+ variables will be +rated at t#e ti"e of +lass loadin! and destroyed at t#e ti"e of
+lass (nloadin! #en+e t#e s+ope of t#e stati+ variable is eEa+tly sa"e as t#e s+ope of t#e
9$lass file.
Ctati+ variables will be stored in "et#od area. Ctati+ variables s#o(ld be de+lared wit# in
t#e +lass dire+tly b(t o(tside of any "et#od or blo+? or +onstr(+tor.
Ctati+ variables +an be a++essed fro" bot# instan+e and stati+ areas dire+tly.
@e +an a++ess stati+ variables eit#er by +lass na"e or by ob,e+t referen+e b(t (sa!e of
+lass na"e is re+o""ended.
6(t wit#in t#e sa"e +lass it is not reV(ired to (se +lass na"e we +an a++ess dire+tly.
1/ Ctart *%.
2/ 'reate and start %ain T#read by *%.
3/ Lo+ateBfind/ Test.+lass by "ain T#read.
4/ Load Test.+lass by "ain T#read.
5/ <Ee+(tion of "ainB/ "et#od.
6/ ;nload Test.+lass
7/ Ter"inate "ain T#read.
$/ C#(tdown *%.
Example:
+lass Test
7
stati+ int i81)9
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t8new TestB/9
Cyste".o(t.printlnBt.i/9JJ1)
Cyste".o(t.printlnBTest.i/9JJ1)
Cyste".o(t.printlnBi/9JJ1)

27

=
=
Hor t#e stati+ variables it is not reV(ired to perfor" initiali0ation eEpli+itly- *% will
always provide defa(lt val(es.
Example:
+lass Test
7
stati+ Ctrin! s9
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBs/9JJn(ll
=
=
Example:
+lass Test
7
int E81)9
stati+ int y82)9
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t18new TestB/9
t1.E8$$$9
t1.y8&&&9
Test t28new TestB/9
Cyste".o(t.printlnBt2.EFN4444NFt2.y/9JJ1)4444&&&
=
=
'iagram:

Ctati+ variables also ?nown as +lass level variables or fields.
Lo$al varia,les:
Co"e ti"e to "eet te"porary reV(ire"ents of t#e pro!ra""er we +an de+lare
variables inside a "et#od or blo+? or +onstr(+tors s(+# type of variables are +alled lo+al
variables or a(to"ati+ variables or te"porary variables or sta+? variables.

2$

T#e lo+al variables will be +reated as part of t#e blo+? eEe+(tion in w#i+# it is de+lared
and destroyed on+e t#at blo+? eEe+(tion +o"pletes. Sen+e t#e s+ope of t#e lo+al
variables is eEa+tly sa"e as s+ope of t#e blo+? in w#i+# we de+lared.
Example 1:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int i8)9
forBint ,8)9,Z39,FF/
7
i8iF,9
=

=
=
Example 2:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
try
7
int i8Inte!er.parseIntBNtenN/9
=
+at+#B:(ll\ointer<E+eption e/
7

=
=
=
T#e lo+al variables will be stored on t#e sta+?.

2&

Hor t#e lo+al variables *% wonAt provide any defa(lt val(es +o"p(lsory we s#o(ld
perfor" initiali0ation eEpli+itly before (sin! t#at variable.
Example:

Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E9
ifBar!s.len!t#T)/
7
E81)9
=
Cyste".o(t.printlnBE/9JJ'.<.variable E "i!#t not #ave been initiali0ed
=
=
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E9
ifBar!s.len!t#T)/
7
E81)9
=
else
7
E82)9
=
Cyste".o(t.printlnBE/9
=

3)

=
!utput:
,ava Test E
1)
,ava Test E y
1)
,ava Test
2)
It is never re+o""ended to perfor" initiali0ation for t#e lo+al variables inside lo!i+al
blo+?s be+a(se t#ere is no !(arantee of eEe+(tin! t#at blo+? always at r(nti"e.
It is #i!#ly re+o""ended to perfor" initiali0ation for t#e lo+al variables at t#e ti"e of
de+laration at least wit# defa(lt val(es.
/ote: T#e only appli+able "odifier for lo+al variables is final. If we are (sin! any ot#er
"odifier we will !et +o"pile ti"e error.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7

p(bli+ int E81)9
private int E81)9
prote+ted int E81)9 *9E: illegal start of expression
stati+ int E81)9
volatile int E81)9
transient int E81)9
final int E81)9JJ:valid;
=
=
*on$lusions:
1/ Hor t#e stati+ and instan+e variables it is not reV(ired to perfor" initiali0ation eEpli+itly
*% will provide defa(lt val(es. 6(t for t#e lo+al variables *% wonAt provide any
defa(lt val(es +o"p(lsory we s#o(ld perfor" initiali0ation eEpli+itly before (sin! t#at
variable.
2/ Hor every ob,e+t a separate +opy of instan+e variable will be +reated w#ereas for entire
+lass a sin!le +opy of stati+ variable will be +reated. Hor every T#read a separate +opy of
lo+al variable will be +reated.

31

3/ Instan+e and stati+ variables +an be a++essed by "(ltiple T#reads si"(ltaneo(sly and
#en+e t#ese are not T#read safe b(t lo+al variables +an be a++essed by only one T#read
at a ti"e and #en+e lo+al variables are T#read safe.
./ initiali4ed arra(s
Example:
+lass Test
7
intD> a9
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t18new TestB/9
Cyste".o(t.printlnBt1.a/9JJn(ll
Cyste".o(t.printlnBt1.aD)>/9JJR.<.:(ll\ointer<E+eption
=
=
Instan$e level:
Example 1:
intD> a9
Cyste".o(t.printlnBob,.a/9JJn(ll
Cyste".o(t.printlnBob,.aD)>/9JJR.<.:(ll\ointer<E+eption
Example 2:
intD> a8new intD3>9
Cyste".o(t.printlnBob,.a/9JJDI[3e25a5
Cyste".o(t.printlnBob,.aD)>/9JJ)
2tati$ level:
Example 1:
stati+ intD> a9
Cyste".o(t.printlnBa/9JJn(ll
Cyste".o(t.printlnBaD)>/9JJR.<.:(ll\ointer<E+eption
Example 2:
stati+ intD> a8new intD3>9
Cyste".o(t.printlnBa/9JJDI[3e25a5
Cyste".o(t.printlnBaD)>/9JJ)
Lo$al level:
Example 1:
intD> a9
Cyste".o(t.printlnBa/9 *9E: varia,le a mig#t not #ave ,een initiali4ed
Cyste".o(t.printlnBaD)>/9

32

Example 2:
intD> a8new intD3>9
Cyste".o(t.printlnBa/9JJDI[3e25a5
Cyste".o(t.printlnBaD)>/9JJ)
In+e we +reated an array every ele"ent is always initiali0ed wit# defa(lt val(es
irrespe+tive of w#et#er it is stati+ or instan+e or lo+al array.
-ar< arg met#ods :varia,le no of argument met#ods; :195;
;ntil 1.4v we +anAt de+lared a "et#od wit# variable no. If ar!("ents. If t#ere is a
+#an!e in no of ar!("ents +o"p(lsory we #ave to define a new "et#od. T#is approa+#
in+reases len!t# of t#e +ode and red(+es readability. 6(t fro" 1.5 version onwards we
+an de+lare a "et#od wit# variable no. If ar!("ents s(+# type of "et#ods are +alled
var4ar! "et#ods.
@e +an de+lare a var4ar! "et#od as follows.

@e +an +all or invo?e t#is "et#od by passin! any no. If int val(es in+l(din! 0ero
n("ber.
Example:
+lass Test
7
p(bli+ stati+ void "et#odIneBint... E/
7
Cyste".o(t.printlnBNvar4ar! "et#odN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
"et#odIneB/9
"et#odIneB1)/9
"et#odIneB1)-2)-3)/9
=
=
!utput:
var4ar! "et#od
var4ar! "et#od
var4ar! "et#od
Internally var4ar! para"eter i"ple"ented by (sin! sin!le di"ensional array #en+e
wit#in t#e var4ar! "et#od we +an different ar!("ents by (sin! indeE.
Example:

33

+lass Test
7
p(bli+ stati+ void s("Bint... E/
7
int total8)9
forBint i8)9iZE.len!t#9iFF/
7
total8totalFEDi>9
=
Cyste".o(t.printlnBNT#e s(" .NFtotal/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
s("B/9
s("B1)/9
s("B1)-2)/9
s("B1)-2)-3)-4)/9
=
=
!utput:
T#e s(". )
T#e s(". 1)
T#e s(". 3)
T#e s(". 1))
*ase 1:
"#i$# of t#e follo%ing var<arg met#od de$larations are valid&
1/ "et#odIneBint... E/Bvalid/
2/ "et#odIneBint ...E/Bvalid/
3/ "et#odIneBint E.../Binvalid/
4/ "et#odIneBint. ..E/Binvalid/
5/ "et#odIneBint .E../Binvalid/
*ase 2: @e +an "iE var4ar! para"eter wit# !eneral para"eters also.
Example:
"et#odIneBint a-int... b/
"et#odIneBCtrin! s-int... E/ valid
*ase 3: if we "iE var4ar! para"eter wit# !eneral para"eter t#en var4ar! para"eter s#o(ld be
t#e last para"eter.
Example:

34

"et#odIneBint... a-int b/Binvalid/
*ase 4: @e +an ta?e only one var4ar! para"eter inside var4ar! "et#od
Example:
"et#odIneBint... a-int... b/Binvalid/
*ase 5:
+lass Test
7
p(bli+ stati+ void "et#odIneBint i/
7
Cyste".o(t.printlnBN!eneral "et#odN/9
=
p(bli+ stati+ void "et#odIneBint... i/
7
Cyste".o(t.printlnBNvar4ar! "et#odN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
"et#odIneB/9JJvar4ar! "et#od
"et#odIneB1)-2)/9JJvar4ar! "et#od
"et#odIneB1)/9JJ!eneral "et#od
=
=
In !eneral var4ar! "et#od will !et least priority t#at is if no ot#er "et#od "at+#ed t#en
only var4ar! "et#od will !et t#e +#an+e t#is is eEa+tly sa"e as defa(lt +ase inside a
swit+#.
*ase 6: Hor t#e var4ar! "et#ods we +an provide t#e +orrespondin! type array as ar!("ent.
Example:
+lass Test
7

7
Cyste".o(t.printlnBNvar4ar! "et#odN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
"et#odIneBnew intD>71)-2)-3)=/9JJvar4ar! "et#od
=

35

=
*ase :
+lass Test
7
p(bli+ void "et#odIneBintD> i/7=
p(bli+ void "et#odIneBint... i/7=
=
!utput:
'o"pile ti"e error.
'annot de+lare bot# "et#odIneBint.../ and "et#odIneBintD>/ in Test
2ingle 'imensional 7rra( -s -ar<7rg =et#od:
*ase 1: @#erever sin!le di"ensional array present we +an repla+e wit# var4ar! para"eter.

Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!... ar!s/
7
Cyste".o(t.printlnBNvar4ar! "ain "et#odN/9JJvar4ar! "ain "et#od
=
=
*ase 2: @#erever var4ar! para"eter present we +anAt repla+e wit# sin!le di"ensional array.

Example:
+lass Test
7
p(bli+ stati+ void "et#odIneBintD>... E/
7
forBintD> a.E/
7
Cyste".o(t.printlnBaD)>/9
=
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
intD> l871)-2)-3)=9

36

intD> "874)-5)=9
"et#odIneBl-"/9

=
=
!utput:
1)
4)
7nal(sis:



=ain =et#od
@#et#er t#e +lass +ontains "ainB/ "et#od or not and w#et#er it is properly de+lared or
not t#ese +#e+?in!As are not responsibilities of t#e +o"piler- at r(nti"e *% is
responsible for t#is. If ,v" (nable to find t#e reV(ired "ainB/ "et#od t#en we will !et
r(nti"e eE+eption sayin! :oC(+#%et#od<rror. "ain.
Example:
+lass Test
7=
!utput:
,ava+ Test.,ava
,ava Test R9E: /o2u$#=et#odError: main
*% always sear+#es for t#e "ainB/ "et#od wit# t#e followin! si!nat(re.

If we are perfor"in! any +#an!es to t#e above si!nat(re t#en t#e +ode wonAt r(n and
will !et R(nti"e eE+eption sayin! :oC(+#%et#od<rror. Anyway t#e followin! +#an!es
are a++eptable to "ainB/ "et#od.

37

1/ T#e order of "odifiers is not i"portant t#at is instead of p(bli+ stati+ we +an ta?e stati+
p(bli+.
2/ @e +an de+lare strin!D> in any a++eptable for"
1/ Ctrin!D> ar!s
2/ Ctrin! D>ar!s
3/ Ctrin! ar!sD>
3/ Instead of ar!s we +an (se any valid ,ava identifier.
4/ @e +an repla+e strin!D> wit# var4ar! para"eter.
Example:
"ainBCtrin!... ar!s/
5/ "ainB/ "et#od +an be de+lared wit# t#e followin! "odifiers.
final- syn+#roni0ed- stri+tfp.
"#i$# of t#e follo%ing main:; met#od de$larations are valid&
1/ p(bli+ stati+ void "ainBCtrin! ar!s/7=Binvalid/
2/ p(bli+ syn+#roni0ed final stri+tfp void "ainBCtrin!D> ar!s/7= Binvalid/
3/ p(bli+ stati+ void %ainBCtrin!... ar!s/7= Binvalid/
4/ p(bli+ stati+ int "ainBCtrin!D> ar!s/7=JJint ret(rn type we +anQt ta?eJJBinvalid/
5/ p(bli+ stati+ syn+#roni0ed final stri+tfp void "ainBCtrin!... ar!s/7=Bvalid/
In %#i$# of t#e a,ove $ases %e %ill get $ompile time error&
:o +ase- in all t#e +ases we will !et r(nti"e eE+eption.
Iverloadin! of t#e "ainB/ "et#od is possible b(t *% always +alls strin!D> ar!("ent
"ainB/ "et#od only.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBNCtrin!D> array "ain "et#odN/9 overloaded met#ods
=
p(bli+ stati+ void "ainBintD> ar!s/
7
Cyste".o(t.printlnBNintD> array "ain "et#odN/9
=
=
!utput:
Ctrin!D> array "ain "et#od
T#e ot#er overloaded "et#od we #ave to +all eEpli+itly t#en only it will be eEe+(ted.

3$

In#eritan+e +on+ept is appli+able for stati+ "et#ods in+l(din! "ainB/ "et#od #en+e
w#ile eEe+(tin! +#ild +lass if t#e +#ild +lass doesnAt +ontain "ainB/ "et#od t#en t#e
parent +lass "ainB/ "et#od will be eEe+(ted.
Example 1:
+lass \arent
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBNparent "ainN/9 3arent9java
=
=
+lass '#ild eEtends \arent
7=
7nal(sis:


Example 2:
+lass \arent
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBNparent "ainN/9
=
=
+lass '#ild eEtends \arent 3arent9java
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBN'#ild "ainN/9
=
=
7nal(sis:

3&


It see"s to be overridin! +on+ept is appli+able for stati+ "et#ods b(t it is not overridin!
it is "et#od #idin!.

*ommand line arguments:
T#e ar!("ents w#i+# are passin! fro" +o""and pro"pt are +alled +o""and line
ar!("ents. T#e "ain ob,e+tive of +o""and line ar!("ents are we +an +(sto"i0e t#e
be#avior of t#e "ainB/ "et#od.

Example 1:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
forBint i8)9iZ8ar!s.len!t#9iFF/
7
Cyste".o(t.printlnBar!sDi>/9
=
=
=
!utput:
,ava Test E y 0
ArrayIndeEI(tIf6o(nds<E+eption. 3
Example 2:
Repla+e iZ8ar!s.len!t# wit# iZar!s.len!t# t#en it will r(n s(++essf(lly.
@it#in t#e "ainB/ "et#od +o""and line ar!("ents are available in t#e for" of Ctrin!
#en+e >?@ operator a+ts as strin! +on+atenation b(t not arit#"eti+ addition.
Example:
+lass Test

4)

7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBar!sD)>Far!sD1>/9
=
=
!utput:
<.YC'*\T,ava+ Test.,ava
<.YC'*\T,ava Test 1) 2)
1)2)
Cpa+e is t#e separator between 2 +o""and line ar!("ents and if o(r +o""and line
ar!("ent itself +ontains spa+e t#en we s#o(ld en+lose wit# in do(ble V(otes.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBar!sD)>/9
=
=
!utput:
<.YC'*\T,ava+ Test.,ava
<.YC'*\T,ava Test Nvi,aya b#as?arN
i,aya b#as?ar
0ava $oding standards
It is #i!#ly re+o""ended to follow +odin! standards.
@#enever we are writin! any +o"ponent t#e na"e of t#e +o"ponent s#o(ld refle+t t#e
p(rpose or f(n+tionality.
Example:

*oding standards for $lasses:

41

;s(ally +lass na"es are no(ns.
C#o(ld starts wit# (pper+ase letter and if it +ontains "(ltiple words every inner word
s#o(ld starts wit# (pper +ase letter.
Example:

*oding standards for interfa$es:
;s(ally interfa+e na"es are ad,e+tives.
C#o(ld starts wit# (pper +ase letter and if it +ontains "(ltiple words every inner word
s#o(ld starts wit# (pper +ase letter.
Example:
1/ Ceriali0able
2; R(nnable adje$tives
3/ 'loneable
*oding standards for met#ods:
;s(ally "et#od na"es are eit#er verbs or verb no(n +o"bination.
C#o(ld starts wit# lower+ase +#ara+ter and if it +ontains "(ltiple words every inner
word s#o(ld starts wit# (pper +ase letter.
Example:

*oding standards for varia,les:
;s(ally variable na"es are no(ns.
C#o(ld starts wit# lower+ase alp#abet sy"bol and if it +ontains "(ltiple words every
inner word s#o(ld starts wit# (pper +ase +#ara+ter.
Example:
len!t#
na"e
salary nouns
a!e
"obile:("ber
*oding standards for $onstants:
;s(ally +onstants are no(ns.
C#o(ld +ontain only (pper+ase +#ara+ters and if it +ontains "(ltiple words t#en t#ese
words are separated wit# (nders+ore sy"bol.

42

;s(ally we +an de+lare +onstants by (sin! pu,li$ stati$ final modifiers9
Example:
%AP2AL;< nouns
%I:2AL;<
0ava ,ean $oding standards:
A ,ava bean is a si"ple ,ava +lass wit# private properties and p(bli+ !etter and setter
"et#ods.



Example:

2(ntax for setter met#od:
1/ %et#od na"e s#o(ld be prefiEed wit# set.
2/ It s#o(ld be p(bli+.
3/ Ret(rn type s#o(ld be void.
4/ 'o"p(lsory it s#o(ld ta?e so"e ar!("ent.
2(ntax for getter met#od:
1/ T#e "et#od na"e s#o(ld be prefiEed wit# !et.
2/ It s#o(ld be p(bli+.
3/ Ret(rn type s#o(ld not be void.
4/ It is always no ar!("ent "et#od.
/ote: Hor t#e boolean properties t#e !etter "et#od +an be prefiEed wit# eit#er !et or is.
Example:


43


*oding standards for listeners:
8o register a listener:
%et#od na"e s#o(ld be prefiEed wit# add.
1/ p(bli+ void add%yA+tionListenerB%yA+tionListener l/Bvalid/
2/ p(bli+ void re!ister%yA+tionListenerB%yA+tionListener l/Binvalid/
3/ p(bli+ void add%yA+tionListenerBA+tionListener l/Binvalid/
8o unregister a listener:
T#e "et#od na"e s#o(ld be prefiEed wit# re"ove.
1/ p(bli+ void re"ove%yA+tionListenerB%yA+tionListener l/Bvalid/
2/ p(bl+ void (nre!ister%yA+tionListenerB%yA+tionListener l/Binvalid/
3/ p(bli+ void re"ove%yA+tionListenerBA+tionListener l/Binvalid/
4/ p(bli+ void delete %yA+tionListenerB%yA+tionListener l/Binvalid/
















44











'e$laration and 7$$ess =odifiers
1/ *ava so(r+e file str(+t(re
2/ 'lass "odifiers
3/ %e"ber "odifiers
4/ Interfa+es
0ava sour$e file stru$ture:
A ,ava pro!ra" +an +ontain any no. If +lasses b(t at "ot one +lass +an be de+lared as
p(bli+. KIf t#ere is a p(bli+ +lass t#e na"e of t#e pro!ra" and na"e of t#e p(bli+ +lass
"(st be "at+#ed ot#erwise we will !et +o"pile ti"e errorL.
If t#ere is no p(bli+ +lass t#en any na"e we !ives for ,ava so(r+e file.
Example:

*ase1:
If t#ere is no p(bli+ +lass t#en we +an (se any na"e for ,ava so(r+e file t#ere are no
restri+tions.
Example:
A.,ava
6.,ava
'.,ava

45

6#as?ar.,ava
$ase2:
If +lass 6 de+lared as p(bli+ t#en t#e na"e of t#e pro!ra" s#o(ld be 6.,ava ot#erwise
we will !et +o"pile ti"e error sayin! K+lass 6 is p(bli+- s#o(ld be de+lared in a file
na"ed 6.,avaL.
*ae3:
If bot# 6 and ' +lasses are de+lared as p(bli+ and na"e of t#e file is 6.,ava t#en we will
!et +o"pile ti"e error sayin! K+lass ' is p(bli+- s#o(ld be de+lared in a file na"ed
'.,avaL.
It is #i!#ly re+o""ended to ta?e only one +lass for so(r+e file and na"e of t#e pro!ra"
Bfile/ "(st be sa"e as +lass na"e. T#is approa+# i"proves readability and
(nderstandability of t#e +ode.

Example:
+lass A
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnBNA +lass "ain "et#od is eEe+(tedN/9
=
=
+lass 6
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnBN6 +lass "ain "et#od is eEe+(tedN/9
=
=
+lass '
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnBN' +lass "ain "et#od is eEe+(tedN/9
=
=
+lass D
7
=
!utput:

46


D.Y*avaT,ava A
A +lass "ain "et#od is eEe+(ted
D.Y*avaT,ava 6
6 +lass "ain "et#od is eEe+(ted
D.Y*avaT,ava '
' +lass "ain "et#od is eEe+(ted
D.Y*avaT,ava D
<E+eption in t#read N"ainN ,ava.lan!.:oC(+#%et#od<rror. "ain
D.Y*avaT,ava 6#as?ar
<E+eption in t#read N"ainN ,ava.lan!.:o'lassDefHo(nd<rror. 6#as?ar
@e +an +o"pile a ,ava pro!ra" b(t not ,ava +lass in t#at pro!ra" for every +lass one
dot +lass file will be +reated.
@e +an r(n a ,ava +lass b(t not ,ava so(r+e file w#enever we are tryin! to r(n a +lass t#e
+orrespondin! +lass "ain "et#od will be eEe+(ted.
If t#e +lass wonAt +ontain "ain "et#od t#en we will !et r(nti"e eE+eption sayin!
K:oC(+#%et#od<rror. "ainL.
If we are tryin! to eEe+(te a ,ava +lass and if t#e +orrespondin! .+lass file is not available
t#en we will !et r(nti"e eEe+(tion sayin! K:o'lassDefHo(nd<rror. 6#as?arL.
Import statement:
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
ArrayList l8new ArrayListB/9
=
=
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.3. +annot find sy"bol
sy"bol . +lass ArrayList
lo+ation. +lass Test
ArrayList l8new ArrayListB/9
Test.,ava.3. +annot find sy"bol
sy"bol . +lass ArrayList
lo+ation. +lass Test

47

ArrayList l8new ArrayListB/9
@e +an resolve t#is proble" by (sin! f(lly V(alified na"e K,ava.(til.ArrayList l8new
,ava.(til.ArrayListB/9L. 6(t proble" wit# (sin! f(lly V(alified na"e every ti"e is it
in+reases len!t# of t#e +ode and red(+es readability.
@e +an resolve t#is proble" by (sin! i"port state"ents.
Example:
i"port ,ava.(til.ArrayList9
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
ArrayList l8new ArrayListB/9
=
=
!utput:
D.Y*avaT,ava+ Test.,ava
Sen+e w#enever we are (sin! i"port state"ent it is not reV(ire to (se f(lly V(alified
na"es we +an (se s#ort na"es dire+tly. T#is approa+# de+reases len!t# of t#e +ode and
i"proves readability.
*ase 1: 8(pes of Import 2tatements:
T#ere are 2 types of i"port state"ents.
1/ <Epli+it +lass i"port
2/ I"pli+it +lass i"port.
Expli$it $lass import:
Example: I"port ,ava.(til.ArrayList
T#is type of i"port is #i!#ly re+o""ended to (se be+a(se it i"proves readability of t#e
+ode.
6est s(itable for Si4Te+# +ity w#ere readability is i"portant.
Impli$it $lass import:
Example. i"port ,ava.(til.U9
It is never re+o""ended to (se be+a(se it red(+es readability of t#e +ode.
6et s(itable for A"eerpet w#ere typin! is i"portant.
*ase2:
"#i$# of t#e follo%ing import statements are valid&

*ase3:
+onsider t#e followin! +ode.

4$

+lass %yArrayList eEtends ,ava.(til.ArrayList
7
=
T#e +ode +o"piles fine even t#o(!# we are not (sin! i"port state"ents be+a(se we
(sed f(lly V(alified na"e.
@#enever we are (sin! f(lly V(alified na"e it is not reV(ired to (se i"port state"ent.
Ci"ilarly w#enever we are (sin! i"port state"ents it is not reV(ire to (se f(lly V(alified
na"e.
*ase4:
Example:
i"port ,ava.(til.U9
i"port ,ava.sVl.U9
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/
7
Date d8new DateB/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.7. referen+e to Date is a"bi!(o(s- bot# +lass ,ava.sVl.Date in ,ava.sVl and +lass
,ava.(til.Date in ,ava.(til "at+#
Date d8new DateB/9
/ote: <ven in t#e List +ase also we "ay !et t#e sa"e a"bi!(ity proble" be+a(se it is available
in bot# ;TIL and A@T pa+?a!es.
*ase5:
@#ile resolvin! +lass na"es +o"piler will always !ives t#e i"portan+e in t#e followin!
order.
1/ <Epli+it +lass i"port
2/ 'lasses present in +(rrent wor?in! dire+tory.
3/ I"pli+it +lass i"port.
Example:
i"port ,ava.(til.Date9
i"port ,ava.sVl.U9
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7

4&

Date d8new DateB/9
==
T#e +ode +o"piles fine and in t#is +ase (til pa+?a!e Date will be +onsidered.
*ase6:
@#enever we are i"portin! a pa+?a!e all +lasses and interfa+es present in t#at pa+?a!e
are by defa(lt available b(t not s(b pa+?a!e +lasses.
Example:




8o use pattern $lass in our program dire$tl( %#i$# import statement is reAuired&


*ase:
In any ,ava pro!ra" t#e followin! 2 pa+?a!es are not reV(ire to i"port be+a(se t#ese
are available by defa(lt to every ,ava pro!ra".
1. ,ava.lan! pa+?a!e
2. defa(lt pa+?a!eB+(rrent wor?in! dire+tory/
*aseB:
KI"port state"ent is totally +o"pile ti"e +on+eptL if "ore no of i"ports are t#ere t#en
"ore will be t#e +o"pile ti"e b(t t#ere is Kno +#an!e in eEe+(tion ti"eL.
'ifferen$e ,et%een * language Cin$lude and java language import9
In t#e +ase of ' lan!(a!e 5in+l(de all t#e #eader files will be loaded at t#e ti"e of
in+l(de state"ent #en+e it follows stati+ loadin!.
6(t in ,ava i"port state"ent no K.+lassL will be loaded at t#e ti"e of i"port state"ents
in t#e neEt lines of t#e +ode w#enever we are (sin! a parti+(lar +lass t#en only
+orrespondin! K.+lassL file will be loaded. Sen+e it follows Kdyna"i+ loadin!L or Kload4
on Mde"andL or Kload4on4flyL.
2tati$ import:
T#is +on+ept introd(+ed in 1.5 versions. A++ordin! to s(n stati+ i"port i"proves
readability of t#e +ode b(t a++ordin! to worldwide pro!ra""in! eEports Bli?e (s/ stati+

5)

i"ports +reates +onf(sion and red(+es readability of t#e +ode. Sen+e if t#ere is no
spe+ifi+ reV(ire"ent never re+o""ended to (se a stati+ i"port.
195 versions ne% features
1/ Hor4<a+#
2/ ar4ar!
3/ _(e(e
4/ ^eneri+s
5/ A(to boEin! and A(to (nboEin!
6/ 'o4varient ret(rn types
7/ Annotations
$/ <n("
&/ Ctati+ i"port
1)/ Ctrin! b(ilder
;s(ally we +an a++ess stati+ "e"bers by (sin! +lass na"e b(t w#enever we are (sin!
stati+ i"port it is not reV(ire to (se +lass na"e we +an a++ess dire+tly.
"it#out stati$ import:
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnB%at#.sVrtB4//9
Cyste".o(t.printlnB%at#."aEB1)-2)//9
Cyste".o(t.printlnB%at#.rando"B//9
==
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
2.)
2)
).$413)6154315576
"it# stati$ import:
i"port stati+ ,ava.lan!.%at#.sVrt9
i"port stati+ ,ava.lan!.%at#.U9
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnBsVrtB4//9
Cyste".o(t.printlnB"aEB1)-2)//9
Cyste".o(t.printlnBrando"B//9

51

==
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
2.)
2)
).43)2$53$47363$&1
Explain a,out 2(stem9out9println statement&
Example 1 and example 2:




Example 3:
i"port stati+ ,ava.lan!.Cyste".o(t9
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
o(t.printlnBN#elloN/9
o(t.printlnBN#iN/9
==
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
#ello
#i
Example 4:
i"port stati+ ,ava.lan!.Inte!er.U9

52

i"port stati+ ,ava.lan!.6yte.U9
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnB%AP2AL;</9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.6. referen+e to %AP2AL;< is a"bi!(o(s- bot# variable %AP2AL;< in
,ava.lan!.Inte!er and variable %AP2AL;< in ,ava.lan!.6yte "at+#
Cyste".o(t.printlnB%AP2AL;</9
/ote: Two pa+?a!es +ontain a +lass or interfa+e wit# t#e sa"e is very rare #en+e a"bi!(ity
proble" is very rare in nor"al i"port.
6(t 2 +lasses or interfa+es +an +ontain a "et#od or variable wit# t#e sa"e na"e is very
+o""on #en+e a"bi!(ity proble" is also very +o""on in stati+ i"port.
@#ile resolvin! stati+ "e"bers +o"piler will !ive t#e pre+eden+e in t#e followin! order.
1. '(rrent +lass stati+ "e"bers
2. <Epli+it stati+ i"port
3. i"pli+t stati+ i"port.
Example:

If we +o"et line one t#en we will !et Inte!er +lass %AP2AL;< 21474$3647.
If we +o"et lines one and two t#en 6yte +lass %AP2AL;< will be +onsidered 127.
"#i$# of t#e follo%ing import statements are valid&


53

'iagram:

;sa!e of stati+ i"port red(+es readability and +reates +onf(sion #en+e if t#ere is no
spe+ifi+ reV(ire"ent never re+o""ended to (se stati+ i"port.
"#at is t#e differen$e ,et%een general import and stati$ import&
@e +an (se nor"al i"ports to i"port +lasses and interfa+es of a pa+?a!e. w#enever we
are (sin! nor"al i"port we +an a++ess +lass and interfa+es dire+tly by t#eir s#ort na"e
it is not reV(ire to (se f(lly V(alified na"es.
@e +an (se stati+ i"port to i"port stati+ "e"bers of a parti+(lar +lass. w#enever we
are (sin! stati+ i"port it is not reV(ire to (se +lass na"e we +an a++ess stati+ "e"bers
dire+tly.
3a$+age statement:
It is an en+aps(lation "e+#anis" to !ro(p related +lasses and interfa+es into a sin!le
"od(le.
8#e main o,je$tives of pa$+ages are:
To resolve na"e +onfe+ts.
To i"prove "od(larity of t#e appli+ation.
To provide se+(rity.
T#ere is one (niversally a++epted na"in! +onversion for pa+?a!es t#at is to (se internet
do"ain na"e in reverse.
Example:

6o% to $ompile pa$+age program:
Example:
pa+?a!e +o".d(r!a,obs.it,obs9
+lass Syd*obs
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnBNpa+?a!e de"oN/9

54

=
=
*ava+ Syd*obs.,ava !enerated +lass file will be pla+ed in +(rrent wor?in! dire+tory.
'iagram:

*ava+ Md . Syd*obs.,ava
4d "eans destination to pla+e !enerated +lass files K.L "eans +(rrent wor?in! dire+tory.
^enerated +lass file will be pla+ed into +orrespondin! pa+?a!e str(+t(re.



'iagram:


If t#e spe+ified pa+?a!e str(+t(re is not already available t#en t#is +o""and itself will
+reate t#e reV(ired pa+?a!e str(+t(re.
As t#e destination we +an (se any valid dire+tory.
If t#e spe+ified destination is not available t#en we will !et +o"pile ti"e error.
Example:
D.Y*avaT,ava+ 4d +. Syd*obs.,ava
'iagram:

If t#e spe+ified destination is not available t#en we will !et +o"pile ti"e error.
Example:
D.Y*avaT,ava+ 4d 0. Syd*obs.,ava
If 1. is not available t#en we will !et +o"pile ti"e error.
6o% to exe$ute pa$+age program:
D.Y*avaT,ava +o".d(r!a,obs.it,obs.Syd*obs
At t#e ti"e of eEe+(tion +o"p(lsory we s#o(ld provide f(lly V(alified na"e.
*on$lusion 1:

55

In any ,ava pro!ra" t#ere s#o(ld be at "ost one pa+?a!e state"ent t#at is if we are
ta?in! "ore t#an one pa+?a!e state"ent we will !et +o"pile ti"e error.
Example:
pa+?a!e pa+?19
pa+?a!e pa+?29
+lass A
7
=
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ A.,ava
A.,ava.2. +lass- interfa+e- or en(" eEpe+ted
pa+?a!e pa+?29
*on$lusion 2:
In any ,ava pro!ra" t#e 1
st
non +e"ent state"ent s#o(ld be pa+?a!e state"ent Dif it is
available> ot#erwise we will !et +o"pile ti"e error.
Example:
i"port ,ava.(til.U9
pa+?a!e pa+?19
+lass A
7
=
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ A.,ava
A.,ava.2. +lass- interfa+e- or en(" eEpe+ted
pa+?a!e pa+?19
0ava sour$e file stru$ture:

All t#e followin! are valid ,ava pro!ra"s.

/ote: An e"pty so(r+e file is a valid ,ava pro!ra".
*lass =odifiers

56

@#enever we are writin! o(r own +lasses +o"p(lsory we #ave to provide so"e
infor"ation abo(t o(r +lass to t#e ,v". Li?e
1/ 6etter t#is +lass +an be a++essible fro" anyw#ere or not.
2/ 6etter +#ild +lass +reation is possible or not.
3/ @#et#er ob,e+t +reation is possible or not et+.
@e +an spe+ify t#is infor"ation by (sin! t#e +orrespondin! "odifiers.
T#e only appli+able "odifiers for 8op Level +lasses are.
1/ \(bli+
2/ Defa(lt
3/ Hinal
4/ Abstra+t
5/ Ctri+tfp
If we are (sin! any ot#er "odifier we will !et +o"pile ti"e error.
Example:
private +lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int i8)9
forBint ,8)9,Z39,FF/
7
i8iF,9
=
Cyste".o(t.printlnBi/9
==
!.83.8:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.1. "odifier private not allowed #ere
private +lass Test
6(t Hor t#e inner +lasses t#e followin! "odifiers are allowed.
'iagram:

"#at is t#e differen$e ,et%een a$$ess spe$ifier and a$$ess modifier&
In old lan!(a!es X'A Bor/ X'FFA pu,li$- private- prote$ted- default are +onsidered as
a++ess spe+ifiers and all t#e re"ainin! are +onsidered as a++ess "odifiers.

57

6(t in ,ava t#ere is no s(+# type of division all are +onsidered as a++ess "odifiers.
3u,li$ *lasses.
If a +lass de+lared as p(bli+ t#en we +an a++ess t#at +lass fro" anyw#ere.
ED7=3LE:
3rogram1:
pa+?a!e pa+?19
p(bli+ +lass Test
7
p(bli+ void "et#odIneB/7
Cyste".o(t.printlnBNtest +lass "et#odone is eEe+(tedN/9
==
*ompile t#e a,ove program:
D.Y*avaT,ava+ 4d . Test.,ava
3rogram2:
pa+?a!e pa+?29
i"port pa+?1.Test9
+lass Test1
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Test t8new TestB/9
t."et#odIneB/9
==
!.83.8:
D.Y*avaT,ava+ 4d . Test1.,ava
D.Y*avaT,ava pa+?2.Test1
Test +lass "et#odone is eEe+(ted.
If +lass Test is not p(bli+ t#en w#ile +o"pilin! Test1 +lass we will !et +o"pile ti"e error
sayin! pa$+198est is not pu,li$ in pa$+1E $annot ,e a$$essed from outside pa$+age.
'efault *lasses:
If a +lass de+lared as t#e default t#en we +an a++ess t#at +lass only %it#in t#e $urrent
pa$+age #en+e defa(lt a++ess is also ?nown as Kpa$+age level a$$essL.
Example:
3rogram 1:
pa+?a!e pa+?19
+lass Test
7
p(bli+ void "et#odIneB/7
Cyste".o(t.printlnBNtest +lass "et#odone is eEe+(tedN/9

5$

==
3rogram 2:
pa+?a!e pa+?19
i"port pa+?1.Test9
+lass Test1
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Test t8new TestB/9
t."et#odIneB/9
==
!.83.8:
D.Y*avaT,ava+ 4d . Test.,ava
D.Y*avaT,ava+ 4d . Test1.,ava
D.Y*avaT,ava pa+?1.Test1
Test +lass "et#odone is eEe+(ted
Final =odifier.
Hinal is t#e "odifier appli+able for +lasses- "et#ods and variables.
Final =et#ods:
@#atever t#e "et#ods parent #as by defa(lt available to t#e +#ild.
If t#e +#ild is not allowed to override any "et#od- t#at "et#od we #ave to de+lare wit#
final in parent +lass. T#at is final "et#ods +annot overridden.
Example:
3rogram 1:
+lass \arent
7
p(bli+ void propertyB/7
Cyste".o(t.printlnBN+as#F!oldFlandN/9
=
p(bli+ final void "arria!eB/7
Cyste".o(t.printlnBNs(bbala?s#"iN/9
==
3rogram 2:
+lass +#ild eEtends \arent
7
p(bli+ void "arria!eB/7
Cyste".o(t.printlnBNT#a"annaN/9
==
!.83.8:

5&

'o"pile ti"e error.
D.Y*avaT,ava+ \arent.,ava
D.Y*avaT,ava+ +#ild.,ava
$#ild9java:3: marriage:; in $#ild $annot override marriage:; in 3arentE overridden met#od is
final
pu,li$ void marriage:;F
Final *lass:
If a +lass de+lared as t#e final t#en we +annAt +reates t#e +#ild +lass t#at is in#eritan+e
+on+ept is not appli+able for final +lasses.
ED7=3LE:
3rogram 1:
final +lass \arent
7
=
3rogram 2:
+lass +#ild eEtends \arent
7
=
!.83.8:
'o"pile ti"e error.
D.Y*avaT,ava+ \arent.,ava
D.Y*avaT,ava+ +#ild.,ava
$#ild9java:1: $annot in#erit from final 3arent
+lass +#ild eEtends \arent
:ote. <very "et#od present inside a final +lass is always final by defa(lt w#et#er we are
de+larin! or not. 6(t every variable present inside a final +lass need not be final.
Example:
final +lass parent
7
stati+ int E81)9
stati+
7
E8&&&9
==
T#e "ain advanta!e of final ?eyword is we +an a+#ieve se+(rity. @#ereas t#e "ain
disadvanta!e is we are "issin! t#e ?ey benefits of oops. poly"orsi" Bbe+a(se of final
"et#ods/- in#eritan+e Bbe+a(se of final +lasses/ #en+e if t#ere is no spe+ifi+ reV(ire"ent
never re+o""ended to (se final ?eyboard.

6)

7,stra$t =odifier:
Abstra+t is t#e "odifier appli+able only for "et#ods and +lasses b(t not for variables.
7,stra$t =et#ods:
<ven t#o(!# we donAt #ave i"ple"entation still we +an de+lare a "et#od wit# abstra+t
"odifier. T#at is abstra+t "et#ods #ave only de+laration b(t not i"ple"entation. Sen+e
abstra+t "et#od de+laration s#o(ld +o"p(lsory ends wit# se"i+olon.
ED7=3LE:

'#ild +lasses are responsible to provide i"ple"entation for parent +lass abstra+t
"et#ods.
ED7=3LE:

3R!GR7=:



T#e "ain advanta!e of abstra+t "et#ods is - by de+larin! abstra+t "et#od in parent
+lass we +an provide !(ide lines to t#e +#ild +lass s(+# t#at w#i+# "et#ods t#ey s#o(ld
+o"p(lsory i"ple"ent.
Abstra+t "et#od never tal?s abo(t i"ple"entation w#ereas if any "odifier tal?s abo(t
i"ple"entation it is always ille!al +o"bination.
T#e followin! are t#e vario(s ille!al +o"binations for "et#ods.
'iagram:

61


All t#e 6 +o"binations are ille!al.
7,stra$t $lass:
Hor any ,ava +lass if we are not allow to +reate an ob,e+t s(+# type of +lass we #ave to
de+lare wit# abstra+t "odifier t#at is for abstra+t +lass instantiation is not possible.
Example:
abstra+t +lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Test t8new TestB/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.4. Test is abstra+t9 +annot be instantiated
Test t8new TestB/9
"#at is t#e differen$e ,et%een a,stra$t $lass and a,stra$t met#od&
If a +lass +ontain at least on abstra+t "et#od t#en +o"p(lsory t#e +orrespondin! +lass
s#o(ld be de+lare wit# abstra+t "odifier. 6e+a(se i"ple"entation is not +o"plete and
#en+e we +anAt +reate ob,e+t of t#at +lass.
<ven t#o(!# +lass doesnAt +ontain any abstra+t "et#ods still we +an de+lare t#e +lass as
abstra+t t#at is an abstra+t +lass +an +ontain 0ero no of abstra+t "et#ods also.
Example1: SttpCervlet +lass is abstra+t b(t it doesnAt +ontain any abstra+t "et#od.
Example2: <very adapter +lass is abstra+t b(t it doesnAt +ontain any abstra+t "et#od.
Example1:
+lass \arent
7
p(bli+ void "et#odIneB/9
=
!utput:

62

'o"pile ti"e error.
D.Y*avaT,ava+ \arent.,ava
\arent.,ava.3. "issin! "et#od body- or de+lare abstra+t
p(bli+ void "et#odIneB/9
Example2:
+lass \arent
7
p(bli+ abstra+t void "et#odIneB/7=
=
!utput:
'o"pile ti"e error.
\arent.,ava.3. abstra+t "et#ods +annot #ave a body
p(bli+ abstra+t void "et#odIneB/7=
Example3:
+lass \arent
7
p(bli+ abstra+t void "et#odIneB/9
=
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ \arent.,ava
\arent.,ava.1. \arent is not abstra+t and does not override abstra+t "et#od "et#odIneB/ in
\arent
+lass \arent
If a +lass eEtends any abstra+t +lass t#en +o"p(lsory we s#o(ld provide i"ple"entation
for every abstra+t "et#od of t#e parent +lass ot#erwise we #ave to de+lare +#ild +lass as
abstra+t.
Example:
abstra+t +lass \arent
7
p(bli+ abstra+t void "et#odIneB/9
p(bli+ abstra+t void "et#odTwoB/9
=
+lass +#ild eEtends \arent
7
p(bli+ void "et#odIneB/7=
=
!utput:

63

'o"pile ti"e error.
D.Y*avaT,ava+ \arent.,ava
\arent.,ava.6. +#ild is not abstra+t and does not override abstra+t "et#od "et#odTwoB/ in
\arent
+lass +#ild eEtends \arent
If we de+lare +lass +#ild as abstra+t t#en t#e +ode +o"piles fine b(t +#ild of +#ild is
responsible to provide i"ple"entation for "et#odTwoB/.
"#at is t#e differen$e ,et%een final and a,stra$t&
Hor abstra+t "et#ods +o"p(lsory we s#o(ld override in t#e +#ild +lass to provide
i"ple"entation. @#ereas for final "et#ods we +anAt override #en+e abstra+t final
+o"bination is ille!al for "et#ods.
Hor abstra+t +lasses we s#o(ld +o"p(lsory +reate +#ild +lass to provide i"ple"entation
w#ereas for final +lass we +anAt +reate +#ild +lass. Sen+e final abstra+t +o"bination is
ille!al for +lasses.
Hinal +lass +annot +ontain abstra+t "et#ods w#ereas abstra+t +lass +an +ontain final
"et#od.


Example:

/ote:
;sa!e of abstra+t "et#ods- abstra+t +lasses and interfa+es is always !ood pro!ra""in!
pra+ti+e.
2tri$tfp:
stri+tfp is t#e "odifier appli+able for "et#ods and +lasses b(t not for variables.
Ctri+tfp "odifier introd(+ed in 1.2 versions.
If a "et#od de+lare as t#e Ctri+tfp t#en all t#e floatin! point +al+(lations in t#at "et#od
#as to follow I<<<754 standard. Co t#at we will !et flat fro" independent res(lts.
Example:


64

If a +lass de+lares as t#e Ctri+tfp t#en every +on+rete "et#odBw#i+# #as body/ of t#at
+lass #as to follow I<<<754 standard for floatin! point arit#"eti+.
"#at is t#e differen$e ,et%een a,stra$t and stri$tfp&
Ctri+tfp "et#od tal?s abo(t i"ple"entation w#ere as abstra+t "et#od never tal?s
abo(t i"ple"entation #en+e a,stra$tH stri$tfp +o"bination is ille!al for "et#ods.
6(t we +an de+lare a +lass wit# abstra+t and stri+tfp "odifier si"(ltaneo(sly. T#at is
abstra+t stri+tfp +o"bination is le!al for +lasses b(t ille!al for "et#ods.
Example:

=em,er modifiers:
3u,li$ mem,ers:
If a "e"ber de+lared as t#e p(bli+ t#en we +an a++ess t#at "e"ber fro" anyw#ere
Kb(t t#e +orrespondin! +lass "(st be visibleL #en+e before +#e+?in! "e"ber visibility
we #ave to +#e+? +lass visibility.
Example:

3rogram 1:
pa+?a!e pa+?19
+lass A
7
p(bli+ void "et#odIneB/7
Cyste".o(t.printlnBNa +lass "et#odN/9
==
D.Y*avaT,ava+ 4d . A.,ava
3rogram 2:
pa+?a!e pa+?29
i"port pa+?1.A9
+lass 6
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
A a8new AB/9
a."et#odIneB/9
==
!utput:
'o"pile ti"e error.

65

D.Y*avaT,ava+ 4d . 6.,ava
6.,ava.2. pa+?1.A is not p(bli+ in pa+?19 +annot be a++essed fro" o(tside pa+?a!e
i"port pa+?1.A9
In t#e above pro!ra" even t#o(!# "et#odIneB/ "et#od is p(bli+ we +anAt a++ess fro"
+lass 6 be+a(se t#e +orrespondin! +lass A is not p(bli+ t#at is bot# +lasses and "et#ods
are p(bli+ t#en only we +an a++ess.
'efault mem,er:
If a "e"ber de+lared as t#e defa(lt t#en we +an a++ess t#at "e"ber only wit#in t#e
+(rrent pa+?a!e #en+e defa(lt "e"ber is also ?nown as pa+?a!e level a++ess.
Example 1:
3rogram 1:
pa+?a!e pa+?19
+lass A
7
void "et#odIneB/7
Cyste".o(t.printlnBN"et#odIne is eEe+(tedN/9
==
3rogram 2:
pa+?a!e pa+?19
i"port pa+?1.A9
+lass 6
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
A a8new AB/9
a."et#odIneB/9
==
!utput:
D.Y*avaT,ava+ 4d . A.,ava
D.Y*avaT,ava+ 4d . 6.,ava
D.Y*avaT,ava pa+?1.6
"et#odIne is eEe+(ted
Example 2:
3rogram 1:
pa+?a!e pa+?19
+lass A
7
void "et#odIneB/7
Cyste".o(t.printlnBN"et#odIne is eEe+(tedN/9

66

==
3rogram 2:
pa+?a!e pa+?29
i"port pa+?1.A9
+lass 6
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
A a8new AB/9
a."et#odIneB/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ 4d . A.,ava
D.Y*avaT,ava+ 4d . 6.,ava
6.,ava.2. pa+?1.A is not p(bli+ in pa+?19 +annot be a++essed fro" o(tside pa+?a!e
i"port pa+?1.A9
3rivate mem,ers:
If a "e"ber de+lared as t#e private t#en we +an a++ess t#at "e"ber only wit# in t#e
+(rrent +lass.
\rivate "et#ods are not visible in +#ild +lasses w#ere as abstra+t "et#ods s#o(ld be
visible in +#ild +lasses to provide i"ple"entation #en+e private- a,stra$t +o"bination is
ille!al for "et#ods.
3rote$ted mem,ers:
If a "e"ber de+lared as t#e prote+ted t#en we +an a++ess t#at "e"ber wit#in t#e
+(rrent pa+?a!e anyw#ere b(t o(tside pa+?a!e only in +#ild +lasses.
\rote+ted8defa(ltF?ids.
@e +an a++ess prote+ted "e"bers wit#in t#e +(rrent pa+?a!e anyw#ere eit#er by +#ild
referen+e or by parent referen+e b(t fro" o(tside pa+?a!e we +an a++ess prote+ted
"e"bers only in +#ild +lasses and s#o(ld be by +#ild referen+e only t#at is we +anAt (se
parent referen+e to +all prote+ted "e"bers fro" o(tside lan!(a!e.
Example:
3rogram 1:
pa+?a!e pa+?19
p(bli+ +lass A
7
prote+ted void "et#odIneB/7
Cyste".o(t.printlnBN"et#odIne is eEe+(tedN/9
==

67

3rogram 2:
pa+?a!e pa+?19
+lass 6 eEtends A
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
A a8new AB/9
a."et#odIneB/9
6 b8new 6B/9
b."et#odIneB/9
A a18new 6B/9
a1."et#odIneB/9
==
!utput:
D.Y*avaT,ava+ 4d . A.,ava
D.Y*avaT,ava+ 4d . 6.,ava
D.Y*avaT,ava pa+?1.6
"et#odIne is eEe+(ted
"et#odIne is eEe+(ted
"et#odIne is eEe+(ted
Example 2:

*ompression of privateH defaultH prote$ted and pu,li$:
visi,ilit( private default prote$ted pu,li$
1;"it# in t#e
same $lass

2;From $#ild
$lass of same
pa$+age

3;From non<
$#ild $lass of


6$

same pa$+age
4;From $#ild
$lass of
outside
pa$+age




5;From non<
$#ild $lass of
outside
pa$+age

T#e least a++essible "odifier is private.
T#e "ost a++essible "odifier is p(bli+.
\rivateZdefa(ltZprote+tedZp(bli+.
Re+o""ended "odifier for variables is private w#ere as re+o""ended "odifier for
"et#ods is p(bli+.
Final varia,les:
Final instan$e varia,les:
If t#e val(e of a variable is varied fro" ob,e+t to ob,e+t s(+# type of variables are +alled
instan+e variables.
Hor every ob,e+t a separate +opy of instan+e variables will be +reated.
'I7GR7=:

Hor t#e instan+e variables it is not reV(ired to perfor" initiali0ation eEpli+itly ,v" will
always provide defa(lt val(es.
Example:
+lass Test
7
int i9
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Test t8new TestB/9
Cyste".o(t.printlnBt.i/9
==
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test

6&

)
If t#e instan+e variable de+lared as t#e final +o"p(lsory we s#o(ld perfor" initiali0ation
w#et#er we are (sin! or not ot#erwise we will !et +o"pile ti"e error.
Example:
3rogram 1:
+lass Test
7
int i9
=
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT
3rogram 2:
+lass Test
7
final int i9
=
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.1. variable i "i!#t not #ave been initiali0ed
+lass Test
Rule:
Hor t#e final instan+e variables we s#o(ld perfor" initiali0ation before +onstr(+tor
+o"pletion. T#at is t#e followin! are vario(s possible pla+es for t#is.
1; 7t t#e time of de$laration:
Example:
+lass Test
7
final int i81)9
=
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT
2; Inside instan$e ,lo$+:
Example:
+lass Test
7

7)

final int i9
7
i81)9
==
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT
3; Inside $onstru$tor:
Example:
+lass Test
7
final int i9
TestB/
7
i81)9
==
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT
If we are perfor"in! initiali0ation anyw#ere else we will !et +o"pile ti"e error.
Example:
+lass Test
7
final int i9
p(bli+ void "et#odIneB/7
i81)9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.5. +annot assi!n a val(e to final variable i
i81)9
Final stati$ varia,les:
If t#e val(e of a variable is not varied fro" ob,e+t to ob,e+t s(+# type of variables is not
re+o""ended to de+lare as t#e instan+e variables. "e #ave to de$lare t#ose varia,les
at $lass level ,( using stati$ modifier9
Hor t#e stati+ variables it is not reV(ired to perfor" initiali0ation eEpli+itly ,v" will
always provide defa(lt val(es.

71

Example:
+lass Test
7
stati+ int i9
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnBNval(e of i is .NFi/9
==
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
al(e of i is. )
If t#e stati+ variable de+lare as final t#en +o"p(lsory we s#o(ld perfor" initiali0ation
eEpli+itly w#et#er we are (sin! or not ot#erwise we will !et +o"pile ti"e error.
Example:

Rule:
Hor t#e final stati+ variables we s#o(ld perfor" initiali0ation before +lass loadin!
+o"pletion ot#erwise we will !et +o"pile ti"e error. T#at is t#e followin! are possible
pla+es.
1; 7t t#e time of de$laration:
Example:
+lass Test
7
final stati+ int i81)9
=
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT
2; Inside stati$ ,lo$+:
Example:
+lass Test
7
final stati+ int i9

72

stati+
7
i81)9
==
!utput:
'o"pile s(++essf(lly.
If we are perfor"in! initiali0ation anyw#ere else we will !et +o"pile ti"e error.
Example:
+lass Test
7
final stati+ int i9
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
i81)9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.5. +annot assi!n a val(e to final variable i
i81)9

Final lo$al varia,les:
To "eet te"porary reV(ire"ent of t#e pro!ra""er so"eti"e we +an de+lare t#e
variable inside a "et#od or blo+? or +onstr(+tor s(+# type of variables are +alled lo+al
variables.
Hor t#e lo+al variables ,v" wonAt provide any defa(lt val(e +o"p(lsory we s#o(ld
perfor" initiali0ation eEpli+itly before (sin! t#at variable.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int i9
Cyste".o(t.printlnBN#elloN/9
==
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
Sello
Example:

73

+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int i9
Cyste".o(t.printlnBi/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.5. variable i "i!#t not #ave been initiali0ed
Cyste".o(t.printlnBi/9
<ven t#o(!# lo+al variable de+lared as t#e final before (sin! only we s#o(ld perfor"
initiali0ation.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
final int i9
Cyste".o(t.printlnBN#elloN/9
==
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
#ello
/ote: 8#e onl( appli$a,le modifier for lo$al varia,les is final if %e are using an( ot#er
modifier %e %ill get $ompile time error9
Example:

!utput:
'o"pile ti"e error.

74

D.Y*avaT,ava+ Test.,ava
Test.,ava.5. ille!al start of eEpression
private int E81)9
Formal parameters:
T#e for"al para"eters of a "et#od are si"ply a++ess lo+al variables of t#at "et#od
#en+e it is possible to de+lare for"al para"eters as final.
If we de+lare for"al para"eters as final t#en we +anAt +#an!e its val(e wit#in t#e
"et#od.
Example:

2tati$ modifier:
Ctati+ is t#e "odifier appli+able for "et#ods- variables and blo+?s.
@e +anAt de+lare a +lass wit# stati+ ,ut inner $lasses $an ,e de$laring as t#e stati$.
In t#e +ase of instan+e variables for every ob,e+t a separate +opy will be +reated b(t in
t#e +ase of stati+ variables a sin!le +opy will be +reated at +lass level and s#ared by all
ob,e+ts of t#at +lass.
Example:

!utput:

75

D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
$$$.....2)
Instan+e variables +an be a++essed only fro" instan$e area dire$tl( and %e $anIt a$$ess
from stati$ area dire$tl(.
6(t stati+ variables +an be a++essed fro" ,ot# instan$e and stati$ areas dire$tl(.
1/ Int E81)9
2/ Ctati+ int E81)9
3/ \(bli+ void "et#odIneB/7
Cyste".o(t.printlnBE/9
=
4/ \(bli+ stati+ void "et#odIneB/7
Cyste".o(t.printlnBE/9
=
"#i$# are t#e follo%ing de$larations are allo% %it#in t#e same $lass simultaneousl(&
a; 1 and 3
Example:
+lass Test
7
int E81)9
p(bli+ void "et#odIneB/7
Cyste".o(t.printlnBE/9
==
!utput:
'o"pile s(++essf(lly.
,; 1 and 4
Example:
+lass Test
7
int E81)9
p(bli+ stati+ void "et#odIneB/7
Cyste".o(t.printlnBE/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.5. non4stati+ variable E +annot be referen+ed fro" a stati+ +onteEt
Cyste".o(t.printlnBE/9
$; 2 and 3
Example:
+lass Test

76

7
stati+ int E81)9
p(bli+ void "et#odIneB/7
Cyste".o(t.printlnBE/9
==
!utput:
'o"pile s(++essf(lly.
d; 2 and 4

Example:
+lass Test
7
stati+ int E81)9
p(bli+ stati+ void "et#odIneB/7
Cyste".o(t.printlnBE/9
==
!utput:
'o"pile s(++essf(lly.
e; 1 and 2
Example:
+lass Test
7
int E81)9
stati+ int E81)9
=
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.4. E is already defined in Test
stati+ int E81)9
f; 3 and 4
Example:
+lass Test7
p(bli+ void "et#odIneB/7
Cyste".o(t.printlnBE/9
=
p(bli+ stati+ void "et#odIneB/7
Cyste".o(t.printlnBE/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava

77

Test.,ava.5. "et#odIneB/ is already defined in Test
p(bli+ stati+ void "et#odIneB/7
Iverloadin! +on+ept is appli+able for stati+ "et#od in+l(din! "ain "et#od also.
Example:

In#eritan+e +on+ept is appli+able for stati+ "et#ods in+l(din! "ainB/ "et#od #en+e w#ile
eEe+(tin! +#ild +lass- if t#e +#ild doesnAt +ontain "ainB/ "et#od t#en t#e parent +lass "ain
"et#od will be eEe+(ted.
Example:
+lass \arent7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnBNparent "ainB/ "et#od +alledN/9
=
=
+lass +#ild eEtends \arent7
=
!utput:

Example:

!utput:

7$


It see"s to be overridin! +on+ept is appli+able for stati+ "et#ods b(t it is not overridin! it is
"et#od #idin!.
Hor stati+ "et#ods +o"p(lsory i"ple"entation s#o(ld be available w#ere as for abstra+t
"et#ods i"ple"entation s#o(ld be available #en$e a,stra$t stati$ $om,ination is illegal for
met#ods9
/ative modifier:
:ative is a "odifier appli+able only for "et#ods b(t not for variables and +lasses.
T#e "et#ods w#i+# are i"ple"ented in non ,ava are +alled native "et#ods or forei!n "et#ods.
8#e main o,je$tives of native +e(%ord are:
To i"prove perfor"an+e of t#e syste".
To (se already eEistin! le!a+y non ,ava +ode.
8o use native +e(%ord:



3seudo $ode:

Hor native "et#ods i"ple"entation is already available and we are not responsible to
provide i"ple"entation #en+e native "et#od de+laration s#o(ld +o"p(lsory ends wit#
se"i+olon.
\(bli+ native void "et#odIneB/4444invalid
\(bli+ native void "et#odIneB/9444valid

7&

Hor native "et#ods i"ple"entation is already available w#ere as for abstra+t "et#ods
i"ple"entation s#o(ld not be available +#ild +lass is responsible to provide t#at- #en+e
abstra+t native +o"bination is ille!al for "et#ods.
@e +anAt de+lare a native "et#od as stri+tfp be+a(se t#ere is no !(aranty w#et#er t#e
old lan!(a!e s(pports I<<<754 standard or not. T#at is native stri+tfp +o"bination is
ille!al for "et#ods.
Hor native "et#ods in#eritan+e- overridin! and overloadin! +on+epts are appli+able.
T#e "ain disadvanta!e of native ?eyword is (sa!e of native ?eyword in ,ava brea?s
platfor" independent nat(re of ,ava lan!(a!e.
2(n$#roni4ed:
Cyn+#roni0ed is t#e "odifier appli+able for "et#ods and blo+?s b(t not for variables and
+lasses.
If a "et#od or blo+? de+lared wit# syn+#roni0ed ?eyword t#en at a ti"e only one t#read
is allow to eEe+(te t#at "et#od or blo+? on t#e !iven ob,e+t.
T#e "ain advanta!e of syn+#roni0ed ?eyword is we +an resolve data in+onsisten+y
proble"s- b(t t#e "ain disadvanta!e is it in+reases waitin! ti"e of t#e t#reads and
effe+ts perfor"an+e of t#e syste". Sen+e if t#ere is no spe+ifi+ reV(ire"ent never
re+o""ended to (se syn+#roni0ed ?eyword.
8ransient modifier:
Transient is t#e "odifier appli+able only for variables b(t not for "et#ods and +lasses.
At t#e ti"e of seriali0ation if we donAt want to seriali0e t#e val(e of a parti+(lar variable
to "eet t#e se+(rity +onstraints t#en we s#o(ld de+lare t#at variable wit# transient
"odifier.
At t#e ti"e of seriali0ation ,v" i!nores t#e ori!inal val(e of t#e transient variable and
save defa(lt val(e t#at is transient "eans Knot to seriali0eL.
Ctati+ variables are not part of ob,e+t state #en+e seriali0ation +on+ept is not appli+able
for stati+ variables d(o to t#is de+larin! a stati+ variable as transient t#ere is no (se.
Hinal variables will be parti+ipated into seriali0ation dire+tly by t#eir val(es d(e to t#is
de+larin! a final variable as transient t#ere is no i"pa+t.
-olatile modifier:
olatile is t#e "odifier appli+able only for variables b(t not for +lasses and "et#ods.
If t#e val(e of variable ?eeps on +#an!in! s(+# type of variables we #ave to de+lare wit#
volatile "odifier.
If a variable de+lared as volatile t#en for every t#read a separate lo+al +opy will be
+reated by t#e ,v"- all inter"ediate "odifi+ations perfor"ed by t#e t#read will ta?es
pla+e in t#e lo+al +opy instead of "aster +opy.

$)

In+e t#e val(e !ot finali0ed before ter"inatin! t#e t#read t#at final val(e will be
(pdated in "aster +opy.
T#e "ain advanta!e of volatile "odifier is we +an resolve data in+onsisten+y proble"s-
b(t +reatin! and "aintainin! a separate +opy for every t#read in+reases +o"pleEity of
t#e pro!ra""in! and effe+ts perfor"an+e of t#e syste". Sen+e if t#ere is no spe+ifi+
reV(ire"ent never re+o""ended to (se volatile "odifier and itAs al"ost o(tdated.
olatile "eans t#e val(e ?eep on +#an!in! w#ere as final "eans t#e val(e never
+#an!es #en+e final volatile +o"bination is ille!al for variables.
%odifier 'lasses
I(ter Inner
%et#ods ariables 6lo+?s Interfa+es <n(" 'onstr(+tors
\(bli+

\rivate

\rote+ted

Defa(lt

Hinal

Abstra+t

Ctri+tfp

Ctati+

Cyn+#roni0ed

:ative

Transient

olatile

2ummar( of modifier:
T#e "odifiers w#i+# are appli+able for inner +lasses b(t not for o(ter +lasses are
privateH prote$tedH stati$.
T#e "odifiers w#i+# are appli+able only for "et#ods native.
T#e "odifiers w#i+# are appli+able only for variables transient and volatile.
T#e "odifiers w#i+# are appli+able for +onstr(+tor p(bli+- private- prote+ted- defa(lt.
T#e only appli+able "odifier for lo+al variables is final.
Interfa$es:
1/ Introd(+tion
2/ Interfa+e de+larations and i"ple"entations.
3/ <Etends vs i"ple"ents
4/ Interfa+e "et#ods
5/ Interfa+e variables
6/ Interfa+e na"in! +onfli+ts
a/ %et#od na"in! +onfli+ts

$1

b/ ariable na"in! +onfli+ts
7/ %ar?er interfa+e
$/ Adapter +lass
&/ Interfa+e vs abstra+t +lass vs +on+rete +lass.
1)/ Differen+e between interfa+e and abstra+t +lassW
11/ 'on+l(sions
'ef1: Any servi+e reV(ire"ent spe+ifi+ation Bsrs/ is +alled an interfa+e.
Example1: C(n people responsible to define *D6' A\I and database vendor will provide
i"ple"entation for t#at.
'iagram:

Example2: C(n people define C<RL<T A\I to develop web appli+ations web server vendor is
responsible to provide i"ple"entation.




'iagram:

'ef2: Hro" t#e +lient point of view an interfa+e define t#e set of servi+es w#at #is eE+eptin!.
Hro" t#e servi+e provider point of view an interfa+e defines t#e set of servi+es w#at is offerin!.
Sen+e an interfa+e is +onsidered as a +ontra+t between +lient and servi+e provider.
Example: AT% ^;I s+reen des+ribes t#e set of servi+es w#at ban? people offerin!- at t#e sa"e
ti"e t#e sa"e ^;I s+reen t#e set of servi+es w#at +(sto"er #is eE+eptin! #en+e t#is ^;I s+reen
a+ts as a +ontra+t between ban? and +(sto"er.
'ef3: Inside interfa+e every "et#od is always abstra+t w#et#er we are de+larin! or not #en+e
interfa+e is +onsidered as 1))` p(re abstra+t +lass.

$2

2ummer( def: Any servi+e reV(ire"ent spe+ifi+ation BCRC/ or any +ontra+t between +lient and
servi+e provider or 1))` p(re abstra+t +lasses is +onsidered as an interfa+e.
'e$laration and implementation of an interfa$e:
:ote1. @#enever we are i"ple"entin! an interfa+e $ompulsor( for ever( met#od of t#at
interfa$e %e s#ould provide implementation ot#er%ise %e #ave to de$lare $lass as a,stra$t in
t#at +ase $#ild $lass is responsi,le to provide implementation for remaining met#ods.
:ote2. @#enever we are i"ple"entin! an interfa+e "et#od $ompulsor( it s#ould ,e de$lared
as pu,li$ ot#er%ise %e %ill get $ompile time error.
Example:
interfa+e Interf
7
void "et#odIneB/9
void "et#odTwoB/9
=

+lass C(bCervi+e\rovider eEtends Cervi+e\rovider
7
=

!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ C(bCervi+e\rovider.,ava
C(bCervi+e\rovider.,ava.1. C(bCervi+e\rovider is not abstra+t and does not override abstra+t
"et#od "et#odTwoB/ in Interf
+lass C(bCervi+e\rovider eEtends Cervi+e\rovider
Extends vs implements:
A +lass +an eEtend only one +lass at a ti"e.
Example:
+lass Ine7
p(bli+ void "et#odIneB/7
=
=
+lass Two eEtends Ine7
=
A +lass +an i"ple"ents any no. If interfa+es at a ti"e.

$3

Example:
interfa+e Ine7
p(bli+ void "et#odIneB/9
=
interfa+e Two7
p(bli+ void "et#odTwoB/9
=
+lass T#ree i"ple"ents Ine-Two7
p(bli+ void "et#odIneB/7
=
p(bli+ void "et#odTwoB/7
=
=
A +lass +an eEtend a +lass and +an i"ple"ent an interfa+e si"(ltaneo(sly.
interfa+e Ine7
void "et#odIneB/9
=
+lass Two
7
p(bli+ void "et#odTwoB/7
=
=
+lass T#ree eEtends Two i"ple"ents Ine7
p(bli+ void "et#odIneB/7
=
=
An interfa+e +an eEtend any no. If interfa+es at a ti"e.
Example:
interfa+e Ine7
void "et#odIneB/9
=
interfa+e Two7
void "et#odTwoB/9
=
interfa+e T#ree eEtends Ine-Two
7
=
1; "#i$# of t#e follo%ing is true&

$4

1. A +lass +an eEtend any no. If +lasses at a ti"e.
2. An interfa+e +an eEtend only one interfa+e at a ti"e.
3. A +lass +an i"ple"ent only one interfa+e at a ti"e.
4. A +lass +an eEtend a +lass and +an i"ple"ent an interfa+e b(t not bot#
si"(ltaneo(sly.
5. :one of t#e above.
Ans. 5
2/ 'onsider t#e eEpression D extends J for w#i+# of t#e possibility of P and a t#is
eEpression is tr(eW
1. 6ot# E and y s#o(ld be +lasses.
2. 6ot# E and y s#o(ld be interfa+es.
3. 6ot# E and y +an be +lasses or +an be interfa+es.
4. :o restri+tion.
Ans. 3
3; D extends JH K&
P- a- 1 s#o(ld be interfa+es.
4; D extends J implements K&
P- a s#o(ld be +lasses.
1 s#o(ld be interfa+e.
5; D implements JH K&
P s#o(ld be +lass.
a- 1 s#o(ld be interfa+es.
6; D implements J extend K&
Example:
interfa+e Ine7
=
+lass Two 7
=
+lass T#ree i"ple"ents Ine eEtends Two7
=
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ T#ree.,ava
T#ree.,ava.5. Q7Q eEpe+ted
+lass T#ree i"ple"ents Ine eEtends Two7
<very "et#od present inside interfa+e is always pu,li$ and a,stra$t w#et#er we are
de+larin! or not. Sen+e inside interfa+e t#e followin! "et#od de+larations are eV(al.
void "et#odIneB/9

$5

p(bli+ oid "et#odIneB/9
abstra+t oid "et#odIneB/9 EAual
p(bli+ abstra+t oid "et#odIneB/9
As every interfa+e "et#od is always p(bli+ and abstra+t we +anAt (se t#e followin!
"odifiers for interfa+e "et#ods.
3rivateH prote$tedH finalH stati$H s(n$#roni4edH nativeH stri$tfp9
Inside interfa$e %#i$# met#od de$larations are valid&
1. p(bli+ void "et#odIneB/7=
2. private void "et#odIneB/9
3. p(bli+ final void "et#odIneB/9
4. p(bli+ stati+ void "et#odIneB/9
5. p(bli+ abstra+t void "et#odIneB/9
Ans. 5
Interfa$e varia,les:
An interfa+e +an +ontain variables to define reV(ire"ent level +onstants.
<very interfa+e variable is always pu,li$ stati$ and final w#et#er we are de+larin! or
not.
Example:
interfa+e interf
7
int E81)9
=
3u,li$: To "a?e it available for every i"ple"entation +lass.
2tati$: @it#o(t eEistin! ob,e+t also we #ave to a++ess t#is variable.
Final: I"ple"entation +lass +an a++ess t#is val(e b(t +annot "odify.
Sen+e inside interfa+e t#e followin! de+larations are eV(al.
int E81)9
p(bli+ int E81)9
stati+ int E81)9
final int E81)9 EAual
p(bli+ stati+ int E81)9
p(bli+ final int E81)9
stati+ final int E81)9
p(bli+ stati+ final int E81)9
As every interfa+e variable by defa(lt pu,li$ stati$ final we +anAt de+lare wit# t#e
followin! "odifiers.
\rivate
\rote+ted

$6

Transient
olatile
Hor t#e interfa+e variables +o"p(lsory we s#o(ld perfor" initiali0ation at t#e ti"e of
de+laration only ot#erwise we will !et +o"pile ti"e error.
Example:
interfa+e Interf
7
int E9
=
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Interf.,ava
Interf.,ava.3. 8 eEpe+ted
int E9
"#i$# of t#e follo%ing de$larations are valid inside interfa$e&
1. int E9
2. private int E81)9
3. p(bli+ volatile int E81)9
4. p(bli+ transient int E81)9
5. p(bli+ stati+ final int E81)9
Ans. 5
Interfa+e variables +an be a++ess fro" i"ple"entation +lass b(t +annot be "odified.
Example:
interfa+e Interf
7
int E81)9
=
Example 1:



$7

Example 2:
+lass Test i"ple"ents Interf
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E82)9
JJ#ere we de+larin! t#e variable E.
Cyste".o(t.printlnBE/9
=
=
!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
2)
Interfa$e naming $onfli$ts:
=et#od naming $onfli$ts:
*ase 1:
If two interfa+es +ontain a "et#od wit# sa"e si!nat(re and sa"e ret(rn type in t#e
i"ple"entation +lass only one "et#od i"ple"entation is eno(!#.
Example 1:
interfa+e Left
7
p(bli+ void "et#odIneB/9
=
Example 2:
interfa+e Ri!#t
7
p(bli+ void "et#odIneB/9
=
Example 3:
+lass Test i"ple"ents Left-Ri!#t
7
p(bli+ void "et#odIneB/
7
==
!utput:
D.Y*avaT,ava+ Left.,ava
D.Y*avaT,ava+ Ri!#t.,ava
D.Y*avaT,ava+ Test.,ava

$$

*ase 2:
if two interfa+es +ontain a "et#od wit# sa"e na"e b(t different ar!("ents in t#e
i"ple"entation +lass we #ave to provide i"ple"entation for bot# "et#ods and t#ese
"et#ods a+ts as a overloaded "et#ods
Example 1:
interfa+e Left
7
p(bli+ void "et#odIneB/9
=
Example 2:
interfa+e Ri!#t
7
p(bli+ void "et#odIneBint i/9
=
Example 3:
+lass Test i"ple"ents Left-Ri!#t
7
p(bli+ void "et#odIneB/
7
=
p(bli+ void "et#odIneBint i/
7
==
!utput:
D.Y*avaT,ava+ Left.,ava
D.Y*avaT,ava+ Ri!#t.,ava
D.Y*avaT,ava+ Test.,ava
*ase 3:
If two interfa+es +ontain a "et#od wit# sa"e si!nat(re b(t different ret(rn types t#en
it is not possible to i"ple"ent bot# interfa+es si"(ltaneo(sly.
Example 1:
interfa+e Left
7
p(bli+ void "et#odIneB/9
=
Example 2:
interfa+e Ri!#t
7

$&

p(bli+ int "et#odIneBint i/9
=
@e +anAt write any ,ava +lass t#at i"ple"ents bot# interfa+es si"(ltaneo(sly.
Is a ,ava +lass +an i"ple"ent any no. If interfa+es si"(ltaneo(slyW
aes- eE+ept if two interfa+es +ontains a "et#od wit# sa"e si!nat(re b(t different ret(rn
types.
-aria,le naming $onfli$ts:
Two interfa+es +an +ontain a variable wit# t#e sa"e na"e and t#ere "ay be a +#an+e
variable na"in! +onfli+ts b(t we +an resolve variable na"in! +onfli+ts by (sin! interfa+e
na"es.
Example 1:
interfa+e Left
7
int E8$$$9
=
Example 2:
interfa+e Ri!#t
7
int E8&&&9
=
Example 3:
+lass Test i"ple"ents Left-Ri!#t
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
JJCyste".o(t.printlnBE/9
Cyste".o(t.printlnBLeft.E/9
Cyste".o(t.printlnBRi!#t.E/9
=
=
!utput:
D.Y*avaT,ava+ Left.,ava
D.Y*avaT,ava+ Ri!#t.,ava
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
$$$
&&&

&)

=ar+er interfa$e: if an interfa+e doesnAt +ontain any "et#ods and by i"ple"entin! t#at
interfa+e if o(r ob,e+t !ets so"e ability s(+# type of interfa+es are +alled %ar?er interfa+e Bor/
Ta! interfa+e Bor/ Ability interfa+e.
Example:
Cerili0able
+loneable
Rando"A++ess T#ese are "ar?ed for so"e ability
Cin!leT#read%odel
.
.
.
.
Example 1: 6y i"ple"entin! Cerili0able interfa+e we +an send t#at ob,e+t a+ross t#e networ?
and we +an save state of an ob,e+t into a file.
Example 2: 6y i"ple"entin! Cin!leT#read%odel interfa+e Cervlet +an pro+ess only one +lient
reV(est at a ti"e so t#at we +an !et KT#read CafetyL.
Example 3: 6y i"ple"entin! 'loneable interfa+e o(r ob,e+t is in a position to provide eEa+tly
d(pli+ate +loned ob,e+t.
"it#out #aving an( met#ods in mar+er interfa$e #o% o,je$ts %ill get a,ilit(&
Internally *% will provide reV(ired ability.
"#( 0-= is providing t#e reAuired a,ilit(&
To red(+e +o"pleEity of t#e pro!ra""in!.
Is it possi,le to $reate our o%n mar+er interfa$e&
aes- b(t +(sto"i0ation of *% is reV(ired.
7dapter $lass:
Adapter +lass is a si"ple ,ava +lass t#at i"ple"ents an interfa+e only wit# e"pty
i"ple"entation for every "et#od.
If we i"ple"ent an interfa+e dire+tly for ea+# and every "et#od +o"p(lsory we s#o(ld
provide i"ple"entation w#et#er it is reV(ired or not. T#is approa+# in+reases len!t# of
t#e +ode and red(+es readability.
Example 1:
interfa+e P7
void "1B/9
void "2B/9
void "3B/9
void "4B/9
JJ.
JJ.

&1

JJ.
JJ.
void "5B/9
=
Example 2:
+lass Test i"ple"ents P7
p(bli+ void "3B/7
Cyste".o(t.printlnBN"3B/ "et#od is +alledN/9
=
p(bli+ void "1B/7=
p(bli+ void "2B/7=
p(bli+ void "4B/7=
p(bli+ void "5B/7=
=
@e +an resolve t#is proble" by (sin! adapter +lass.
Instead of i"ple"entin! an interfa+e if we +an eEtend adapter +lass we #ave to provide
i"ple"entation only for reV(ired "et#ods b(t not for all "et#ods of t#at interfa+e.
T#is approa+# de$reases lengt# of t#e $ode and i"proves readability.
Example 1:
abstra+t +lass AdapterP i"ple"ents P7
p(bli+ void "1B/7=
p(bli+ void "2B/7=
p(bli+ void "3B/7=
p(bli+ void "4B/7=
JJ.
JJ.
JJ.
p(bli+ void "1)))B/7=
=
Example 2:
p(bli+ +lass Test eEtend AdapterP77
p(bli+ void "3B/7
==
Example:

&2


^eneri+ Cervlet si"ply a+ts as an adapter +lass for Cervlet interfa+e.
"#at is t#e differen$e ,et%een interfa$eH a,stra$t $lass and $on$rete $lass&
"#en %e s#ould go for interfa$eH a,stra$t $lass and $on$rete $lass&
If we donAt ?now anyt#in! abo(t i"ple"entation ,(st we #ave reV(ire"ent
spe+ifi+ation t#en we s#o(ld !o for interfa+e.
If we are tal?in! abo(t i"ple"entation b(t not +o"pletely Bpartial i"ple"entation/
t#en we s#o(ld !o for abstra+t +lass.
If we are tal?in! abo(t i"ple"entation +o"pletely and ready to provide servi+e t#en we
s#o(ld !o for +on+rete +lass.
Example:

"#at is t#e 'ifferen$e ,et%een interfa$e and a,stra$t $lass&
interfa+e Abstra+t +lass
1/ If we donAtA ?now anyt#in! abo(t
i"ple"entation ,(st we #ave
reV(ire"ent spe+ifi+ation t#en we
s#o(ld !o for interfa+e.
1/ If we are tal?in! abo(t i"ple"entation
b(t not +o"pletely Bpartial
i"ple"entation/ t#en we s#o(ld !o for
abstra+t +lass.

2/ <very "et#od present inside interfa+e
is always pu,li$ and a,stra$t w#et#er
we are de+larin! or not.
2/ <very "et#od present inside abstra+t
+lass need not ,e pu,li$ and a,stra$t.
3/ @e +anAt de+lare interfa+e "et#ods 3/ T#ere are no restri+tions on abstra+t

&3

wit# t#e "odifiers private- prote$ted-
final- stati$- s(n$#roni4ed- native-
stri$tfp.
+lass "et#od "odifiers.
4/ <very interfa+e variable is always
pu,li$ stati$ final w#et#er we are
de+larin! or not.
4/ <very abstra+t +lass variable need not
be p(bli+ stati+ final.
5/ <very interfa+e variable is always
pu,li$ stati$ final we +anAt de+lare wit#
t#e followin! "odifiers. 3rivateH
prote$tedH transientH volatile9
5/ T#ere are no restri+tions on abstra+t
+lass variable "odifiers.
6/ Hor t#e interfa+e variables +o"p(lsory
we s#o(ld perfor" initiali0ation at t#e
ti"e of de+laration ot#erwise we will
!et +o"pile ti"e error.
6/ It is not reV(ire to perfor"
initiali0ation for abstra+t +lass variables
at t#e ti"e of de+laration.
7/ Inside interfa+e we +anAt ta?e stati+
and instan+e blo+?s.
7/ Inside abstra+t +lass we +an ta?e bot#
stati+ and instan+e blo+?s.
$/ Inside interfa+e we +anAt ta?e
+onstr(+tor.
$/ Inside abstra+t +lass we +an ta?e
+onstr(+tor.
"e $anIt $reate o,je$t for a,stra$t $lass ,ut a,stra$t $lass $an $ontain $onstru$tor %#at is t#e
need&
T#is +onstr(+tor will be eEe+(ted for t#e initiali0ation of +#ild ob,e+t.
Example:
+lass \arent7
\arentB/
7
Cyste".o(t.printlnBt#is.#as#'odeB//9
=
=
+lass +#ild eEtends \arent7
+#ildB/7
Cyste".o(t.printlnBt#is.#as#'odeB//9
=
=
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
+#ild +8new +#ildB/9
Cyste".o(t.printlnB+.#as#'odeB//9
=
=

&4

Ever( met#od present inside interfa$e is a,stra$t ,ut in a,stra$t $lass also %e $an ta+e onl(
a,stra$t met#ods t#en %#at is t#e need of interfa$e $on$ept&
@e +an repla+e interfa+e +on+ept wit# abstra+t +lass. 6(t it is not a !ood pro!ra""in!
pra+ti+e. @e are "is(sin! t#e roll of abstra+t +lass.

















!perator and assignments
1/ In+re"ent and de+re"ent operator
2/ Arit#"eti+ operators
3/ Ctrin! +on+atenation operator
4/ Relational operators
5/ <V(ality operator
6/ Instan+eof operator
7/ 6itwise operators
$/ C#ort +ir+(it operators

&5

&/ Type +ast operator
1)/ Assi!n"ent operator
11/ 'onditional operator
12/ new operator
13/ D> operator
14/ *ava operator pre+eden+e
15/ <val(ation order of ,ava operands
In$rement and de$rement operator:
'iagram 1:

'iagram 2:

Example:
Expression Initial value of x Final value of x Final value of (
a8FFE9 1) 11 11
a8EFF9 1) 11 1)
a844E9 1) & &
a8E449 1) & 1)
@e +an apply in+re"ent or de+re"ent operator only for variables b(t not for +onstant
val(es.

Example:

&6


:estin! of in+re"ent or de+re"ent operators is not allowed.
Example:

@e +anAt apply in+re"ent or de+re"ent operator for final variables.
Example:

@e +an apply in+re"ent or de+re"ent operator for any pri"itive type eE+ept 6oolean.

Example:

&7



If we apply any arit#"eti+ operator between two variables KaL and KbL t#e res(lt type is
always.
max:intHt(peof aHt(peof ,;
Example 1:

Example 2:

In t#e +ase of in+re"ent or de+re"ent operator t#e reV(ired type4+astin! will be
perfor"ed a(to"ati+ally by t#e +o"piler.

Example:
byte b81)9
bFF9
Cyste".o(t.printlnBb/9JJ11
7rit#meti$ operators: BF-4-U- J- `/

&$

If we apply any arit#"eti+ operation between two variables KaL and KbL. T#e res(lt type
is always.
max:intH t(pe of aH t(pe ,;

Example:
Cyste".o(t.printlnBQaQF1/9JJ&$
Cyste".o(t.printlnBQaQFQbQ/9JJ1&5
Cyste".o(t.printlnB1)F).5/9JJ1).5
Cyste".o(t.printlnBQaQF3.5/9JJ1)).5
Infinit(:
In t#e +ase of inte!ral arit#"eti+ Bbyte- s#ort- int- lon!/ t#ere is no way to represent
infinity.
Sen+e if infinity is t#e res(lt t#en we will !et Arit#"eti+<E+eption.
Example:

6(t in floatin! point arit#"eti+Bfloat- do(ble/- t#ere is a way to represent infinit(. Hor
t#is Hloat and Do(ble +lasses +ontains t#e followin! two +onstants.
3!2I8I-E<I/FI/I8I-EE
/EGI8I-E<I/FI/I8I-EE
Sen+e if infinity is t#e res(lt we wonAt !et any r(nti"e eE+eption in floatin! point
arit#"eti+.
Example:
Cyste".o(t.printlnB1)J).)/9JJFInfinity
Cyste".o(t.printlnB41)J).)/9JJ4Infinity
/a/:/ot a /um,er;:
In t#e +ase of inte!ral arit#"eti+ t#ere is no way to represent K(ndefined res(ltsL.
Sen+e if t#e res(lt is (ndefined we will !et r(nti"e eE+eption sayin!
Arit#"eti+<E+eption.
Example:

6(t in floatin! point arit#"eti+ Bfloat- do(ble/- t#ere is a way to represent (ndefined
res(lt for t#is Hloat and Do(ble +lasses +ontain K/a/L.

&&

Sen+e if t#e res(lt is (ndefined- we wonAt !et any r(nti"e eE+eption in floatin! point
arit#"eti+.
Example:
Cyste".o(t.printlnB).)J)/9JJ:a:
Cyste".o(t.printlnB4).)J)/9JJ:a:
Cyste".o(t.printlnB)J).)/9JJ:a:
Hor any x val(e in+l(din! /a/ t#e followin! eEpressions ret(rn false.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E81)9
Cyste".o(t.printlnBETHloat.:a:/9JJfalse
Cyste".o(t.printlnBEZHloat.:a:/9JJfalse
Cyste".o(t.printlnBET8Hloat.:a:/9JJfalse
Cyste".o(t.printlnBEZ8Hloat.:a:/9JJfalse
Cyste".o(t.printlnBE88Hloat.:a:/9JJfalse
=
=
Hor any x val(e in+l(din! /a/ t#e followin! eEpression ret(rn tr(e.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E81)9
Cyste".o(t.printlnBEb8Hloat.:a:/9JJtr(e
Cyste".o(t.printlnBHloat.:a:b8Hloat.:a:/9JJtr(e
=
=
2ummar(:


1))

2tring $on$atenation operator:
T#e only operator w#i+# is overloaded in ,ava is K?L operator. Co"eti"e it a+ts as
arit#"eti+ addition operator and so"e ti"e +on+atenation operator.
If at least one ar!("ent is strin! type t#en K?L operator a+ts as +on+atenation and if
bot# ar!("ents are n("ber type t#en it a+ts as arit#"eti+ addition operator.
Example 1:
Ctrin! a8Nb#as?arN9
int b81)-+82)-d83)9
Cyste".o(t.printlnBaFbF+Fd/9JJb#as?ar1)2)3)
Cyste".o(t.printlnBbF+FdFa/9JJ6)b#as?ar
Cyste".o(t.printlnBbF+FaFd/9JJ3)b#as?ar3)
Cyste".o(t.printlnBbFaF+Fd/9JJ1)b#as?ar2)3)
Example 2:

Example 3:

Relational operator: :LH LMH NH NM;
@e +an apply relational operators for every pri"itive type eE+ept boolean.
Example:

@e +anAt apply relational operators for t#e ob,e+t types.
Example:


1)1

@e +anAt perfor" nestin! of relational operators.
Example:

EAualit( operator :B88-b8/
@e +an apply eV(ality operators for every pri"itive type in+l(din! boolean type also.
Example:
Cyste".o(t.printlnB1)881).)/9JJtr(e
Cyste".o(t.printlnBQaQ88&7.)/9JJtr(e
Cyste".o(t.printlnBtr(e88tr(e/9JJtr(e
Cyste".o(t.printlnBQaQb8QbQ/9JJtr(e
@e +an apply eV(ality operator even for ob,e+t referen+e
also.
In t#e +ase of ob,e+t referen+es 88 Bdo(ble eV(al operator/ is always "eant for
referen+e +o"parison only Baddress +o"parison/.
i.e. r188r2 ret(rn tr(e if and only if bot# r1 and r2 point to t#e sa"e ob,e+t.
Example:
T#read t18new T#readB/9
T#read t28new T#readB/9
T#read t38t19
Cyste".o(t.printlnBt188t2/9JJfalse
Cyste".o(t.printlnBt188t3/9JJtr(e
'iagram:

To (se eV(ality operator +o"p(lsory t#ere s#o(ld be so"e relations#ip between
ar!("ent typeBeit#er parent4+#ild Bor/+#ild4parent Bor/ sa"e type/ot#erwise we will !et
+o"pile ti"e error sayin! L in+o"parable typesL.
Example:
Ib,e+t o8new Ib,e+tB/9
Ctrin! s8new Ctrin!BNb#as?arN/9
Ctrin!6(ffer sb8new Ctrin!6(fferB/9
Cyste".o(t.printlnBo88s/9JJfalse
Cyste".o(t.printlnBo88sb/9JJfalse

1)2


'iagram:

Hor any ob,e+t referen+e of- r88n(ll is always false. 6(t n(ll88n(ll is tr(e.
MM -s 9eAuals:;:
88operator is always "eant for referen+e +o"parison w#ereas .eV(alsB/ "et#od "ostly
"eant for +ontent +o"parison.
Example:
Ctrin! s18new Ctrin!BNb#as?arN/9
Ctrin! s28new Ctrin!BNb#as?arN/9
Cyste".o(t.printlnBs188s2/9JJfalse
Cyste".o(t.printlnBs1.eV(alsBs2//9JJtr(e
'iagram:


Instan$eof operator:
@e +an (se t#is operator to +#e+? w#et#er t#e !iven ob,e+t is of parti+(lar type Bor/ not.
2(ntax:

Example:
T#read t8new T#readB/9
Cyste".o(t.printlnBt instan+eof T#read/9JJtr(e
Cyste".o(t.printlnBt instan+eof Ib,e+t/9JJtr(e
Cyste".o(t.printlnBt instan+eof R(nnable/9JJtr(e
'iagram:

/ote:

1)3

To (se Kinstan+eofL operator +o"p(lsory t#ere s#o(ld be so"e relations#ip between
ar!("ent types Beit#er parent4+#ild Bor/ +#ild4parent Bor/ sa"e type/ ot#erwise we will
!et +o"pile ti"e error sayin! Kin+onvertible typesL.
Example:

@#enever we are +o"parin! parent ob,e+t is +#ild type or not by (sin! instan+eof
operator t#en we will !et KfalseL as o(tp(t.
Example:
Ib,e+t o8new Ib,e+tB/9
Cyste".o(t.printlnBo instan+eof Ctrin!/9JJfalse
Hor any +lass or interfa+e E
null instan$eof x t#e res(lt is always KfalseL.
Example:
Cyste".o(t.printlnBn(ll instan+eof Ctrin!/9JJfalse
1it%ise operators:
O :7/';: If bot# ar!("ents are tr(e t#en res(lt is tr(e.
P :!R;: if at least one ar!("ent is tr(e. T#en t#e res(lt is tr(e.
Q :D<!R;: if bot# are different ar!("ents. T#en t#e res(lt is tr(e.
Example:
Cyste".o(t.printlnBtr(ecfalse/9JJfalse
Cyste".o(t.printlnBtr(eOfalse/9JJtr(e
Cyste".o(t.printlnBtr(eRfalse/9JJtr(e
@e +an apply bitwise operators even for inte!ral types also.
Example:

1it%ise $omplement :R; :tilde s(m,ol; operator:
@e +an apply t#is operator only for inte!ral types b(t not for boolean types.
Example 1:

Example 2:

1)4

Cyste".o(t.printlnBd4/9JJ5


'iagram:

1oolean $omplement :S; operator:
T#is operator is appli+able only for boolean types b(t not for inte!ral types.
Example:

Cyste".o(t.printlnBbtr(e/9JJfalse
Cyste".o(t.printlnBbfalse/9JJtr(e
2ummar(:
c
O Appli+able for bot# boolean and inte!ral types.
R
d44444444 Appli+able for inte!ral types only.
b 44444444Appli+able for boolean types only.
2#ort $ir$uit :OOH PP; operators:
T#ese operators are eEa+tly sa"e as nor"al bitwise operators c- O eE+ept t#e followin!
differen+es.
OHP OOHPP
1/ 6ot# ar!("ents s#o(ld be eval(ated
always.
1/ Ce+ond ar!("ent eval(ation is
optional.
2/ Relatively perfor"an+e is low. 2/ Relatively perfor"an+e is #i!#.
3/ Appli+able for bot# inte!ral and
boolean types.
3/ Appli+able only for boolean types b(t
not for inte!ral types.
1; r1OOr2
r2 will be eval(ated if and only if r1 is tr(e.
2; r1PPr2
r2 will be eval(ated if and only if r1 is false.
Example 1:
+lass IperatorsDe"o

1)5

7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E81)- y8159
ifBFFET1)Boperator/FFyZ15/
7
FFE9
=
else
7
FFy9
=
Cyste".o(t.printlnBEFN444444444444NFy/9
=
=
!utput:
operator x (
c 11 17
O 12 16
cc 11 17
OO 12 15
Example 2:
+lass IperatorsDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E81)9
ifBFFEZ1)Boperator/EJ)T1)/
7
Cyste".o(t.printlnBN#elloN/9
=
else
7
Cyste".o(t.printlnBN#iN/9
=
=
=
OO !utput: Si
O !utput: R.<. <E+eption in t#read N"ainN

1)6

,ava.lan!.Arit#"eti+<E+eption. J by 0ero
8(pe<$ast operator :primitive t(pe $asting;:
T#ere are two types of pri"itive type +astin!.
1; Impli$it t(pe $asting9
2; Expli$it t(pe $asting9
Impli$it t(pe $asting:
'o"piler is t#e responsible for t#is type+astin!.
@#enever we are assi!nin! s"aller data type val(e to t#e bi!!er data type variable t#is
type +astin! will be perfor"ed.
Also ?nown as widenin! or (p +astin!.
T#ere is no lose of infor"ation in t#is type +astin!.
T#e followin! are vario(s possible i"pli+it type +astin!.
'iagram:

Example 1:
int E8QaQ9
Cyste".o(t.printlnBE/9JJ&7
/ote: 'o"piler +onverts +#ar to int type a(to"ati+ally by i"pli+it type +astin!.
Example 2:
do(ble d81)9
Cyste".o(t.printlnBd/9JJ1).)
/ote: 'o"piler +onverts int to do(ble type a(to"ati+ally by i"pli+it type +astin!.
Expli$it t(pe $asting:
\ro!ra""er is responsible for t#is type +astin!.
@#enever we are assi!nin! bi!!er data type val(e to t#e s"aller data type variable t#en
eEpli+it type +astin! is reV(ired.
Also ?nown as :arrowin! or down +astin!.
T#ere "ay be a +#an+e of lose of infor"ation in t#is type +astin!.
T#e followin! are vario(s possible +onversions w#ere eEpli+it type +astin! is reV(ired.
'iagram:

Example 1:

1)7


Example 2:
int E813)9
byte b8Bbyte/E9
Cyste".o(t.printlnBb/9JJ4126
7nal(sis:

@#enever we are assi!nin! bi!!er data type val(e to t#e s"aller data type variable by
eEpli+it type +astin! t#e "ost si!nifi+ant bitB%C6/will be lost.
Example:
int E815)9
s#ort s8Bs#ort/E9
Cyste".o(t.printlnBs/9JJ15)
byte b8Bbyte/E9
Cyste".o(t.printlnBb/9JJ41)6
@#enever we are assi!nin! floatin! point data types to t#e inte!er data type by eEpli+it
type +astin! t#e di!its after t#e de+i"al point will be loosed.
Example:

7ssignment operators:
T#ey are t#ree types of assi!n"ent operators.
2imple assignment:

1)$

Example: int E81)9
*#ained assignment:
Example:
int a-b-+-d9
a8b8+8d82)9
Cyste".o(t.printlnBaFN444NFbFN444NF+FN444NFd/9JJ2)4442)4442)4442)
@e +anAt perfor" +#ained assi!n"ent dire+tly at t#e ti"e of de+laration.
Example 1:

Example 2:
int a-b-+-d9
a8b8+8d83)9
*ompound assignment:
Co"eti"es we +an "iE assi!n"ent operator wit# so"e ot#er operator to for"
+o"po(nd assi!n"ent operator.
T#e followin! is t#e list of all possible +o"po(nd assi!n"ent operators in ,ava.
Example 1:

In t#e +ase of +o"po(nd assi!n"ent operator t#e reV(ired type +astin! will be
perfor"ed a(to"ati+ally by t#e +o"piler si"ilar to in+re"ent and de+re"ent
operators.
Example 2:


Example 3:

1)&


*onditional operator:
T#e only ternary operator w#i+# is available in ,ava is +onditional operator.

Example 1:
int E8B1)T2)/W3).4)9
Cyste".o(t.printlnBE/9JJ4)
@e +an perfor" nestin! of +onditional operator also.
Example 2:

Example 5:

Example 6:
final int a81)-b82)9
byte +18BaTb/W3).4)9
byte +28BaZb/W3).4)9
Cyste".o(t.printlnB+1/9JJ4)
Cyste".o(t.printlnB+2/9JJ3)
ne% operator:
@e +an (se KnewL operator to +reate an ob,e+t.
T#ere is no KdeleteL operator in ,ava be+a(se destr(+tion of ob,e+ts is t#e responsibility
of !arba!e +olle+tor.
TU operator:
@e +an (se t#is operator to de+lare and +onstr(+t arrays.
0ava operator pre$eden$e:
.nar( operators:

11)

D>- EFF- P44-
FFE-44E- d-b-
new- ZtypeT.
7rit#meti$ operators:
U-J-`-
F-4.
2#ift operators:
TT-TTT-ZZ.
*ompression operators:
Z- Z8-T-T8- instan+eof.
EAualit( operators:
88-b8
1it%ise operators:
c-R-O.
2#ort $ir$uit operators:
cc-OO.
*onditional operator:
BW./
7ssignment operators:
F8-48-U8-J8-`8.
Evaluation order of java operands:
T#ere is no pre+eden+e for operands before applyin! any operator all operands will be
eval(ated fro" left to ri!#t.
Example:
+lass IperatorsDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnB"1B1/F"1B2/U"1B3/J"1B4/U"1B5/F"1B6//9
=
p(bli+ stati+ int "1Bint i/
7
Cyste".o(t.printlnBi/9
ret(rn i9
=
=


111






Example 1:

Example 2:
int i819
iF8FFi F iFF F FFi F iFF9
Cyste".o(t.printlnBi/9JJ13Analysis.
i8iF FFi F iFF F FFi F iFF9
i81F2F2F4F49
i8139



112

Flo% *ontrol
Hlow +ontrol des+ribes t#e order in w#i+# all t#e state"ents will be eEe+(ted at r(n
ti"e.
'iagram:

2ele$tion statements:
19 if<else:
2(ntax:

T#e ar!("ent to t#e if state"ent s#o(ld be 6oolean if we are providin! any ot#er type
we will !et K+o"pile ti"e errorL.
ED7=3LE 1:
p(bli+ +lass <Ea"pleIf7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E8)9
ifBE/
7
Cyste".o(t.printlnBN#elloN/9
=else7
Cyste".o(t.printlnBN#iN/9
===
!.83.8:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"pleIf.,ava
<Ea"pleIf.,ava.4. in+o"patible types
fo(nd . int
reV(ired. boolean
ifBE/
ED7=3LE 2:
p(bli+ +lass <Ea"pleIf7

113

p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E81)9
ifBE82)/
7
Cyste".o(t.printlnBN#elloN/9
=else7
Cyste".o(t.printlnBN#iN/9
===
!.83.8:
'o"pile ti"e error
D.Y*avaT,ava+ <Ea"pleIf.,ava
<Ea"pleIf.,ava.4. in+o"patible types
fo(nd . int
reV(ired. boolean
ifBE82)/
ED7=3LE 3:
p(bli+ +lass <Ea"pleIf7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E81)9
ifBE882)/
7
Cyste".o(t.printlnBN#elloN/9
=else7
Cyste".o(t.printlnBN#iN/9
===
!.83.8:
Si
ED7=3LE 4:
p(bli+ +lass <Ea"pleIf7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
boolean b8false9
ifBb8tr(e/
7
Cyste".o(t.printlnBN#elloN/9
=else7
Cyste".o(t.printlnBN#iN/9
===
!.83.8:
Sello
ED7=3LE 5:
p(bli+ +lass <Ea"pleIf7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
boolean b8false9
ifBb88tr(e/

114

7
Cyste".o(t.printlnBN#elloN/9
=else7
Cyste".o(t.printlnBN#iN/9
===
!.83.8:
Si
6ot# else and $url( ,ra$es are optional.
@it#o(t +(rly bra+es we +an ta?e only one state"ent (nder if- b(t it s#o(ld not be
de+larative state"ent.
ED7=3LE 6:
p(bli+ +lass <Ea"pleIf7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
ifBtr(e/
Cyste".o(t.printlnBN#elloN/9
==
!.83.8:
Sello
ED7=3LE :
p(bli+ +lass <Ea"pleIf7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
ifBtr(e/9
==
!.83.8:
:o o(tp(t
ED7=3LE B:
p(bli+ +lass <Ea"pleIf7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
ifBtr(e/
int E81)9
==
!.83.8:
'o"pile ti"e error
D.Y*avaT,ava+ <Ea"pleIf.,ava
<Ea"pleIf.,ava.4. Q.+lassQ eEpe+ted
int E81)9
<Ea"pleIf.,ava.4. not a state"ent
int E81)9
ED7=3LE V:
p(bli+ +lass <Ea"pleIf7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
ifBtr(e/7
int E81)9
===

115

!.83.8:
D.Y*avaT,ava+ <Ea"pleIf.,ava
D.Y*avaT,ava <Ea"pleIf
ED7=3LE 15:

!.83.8:
Sello
Si
Ce"i+olon is a valid ,ava state"ent w#i+# is +all e"pty state"ent and it wonAt prod(+e
any o(tp(t.
If several options are available t#en it is not re+o""ended to (se if<else we s#o(ld !o
for s%it$# statement.
2%it$#:
2(ntax:
swit+#BE/
7
+ase 1.
a+tion1
+ase 2.
a+tion2
.
.
.
defa(lt.
defa(lt a+tion
=
*url( ,ra$es are mandator(.
6ot# $ase and default are optional.
<very state"ent inside swit+# "(st be (nder so"e +ase Bor/ defa(lt. Independent
state"ents are not allowed.
ED7=3LE 1:
p(bli+ +lass <Ea"pleCwit+#7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
swit+#BE/
7
Cyste".o(t.printlnBN#elloN/9
===

116

!.83.8:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"pleCwit+#.,ava
<Ea"pleCwit+#.,ava.5. +ase- defa(lt- or Q=Q eEpe+ted
Cyste".o(t.printlnBN#elloN/9
;ntil 1.4 version t#e allow types for t#e swit+# ar!("ent are byte- s#ort- +#ar- int b(t
fro" 1.5 version on wards t#e +orrespondin! wrapper +lasses B6yte- C#ort- '#ara+ter-
Inte!er/ and KenumL types are allowed.
'I7GR7=:

<very +ase label s#o(ld be K+o"pile ti"e +onstantL ot#erwise we will !et +o"pile ti"e
error.
ED7=3LE 2:
p(bli+ +lass <Ea"pleCwit+#7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E81)9
int y82)9
swit+#BE/
7
+ase 1).
Cyste".o(t.printlnBN1)N/9
+ase y.
Cyste".o(t.printlnBN2)N/9
===
!.83.8:
'o"pile ti"e error
D.Y*avaT,ava+ <Ea"pleCwit+#.,ava
<Ea"pleCwit+#.,ava.&. +onstant eEpression reV(ired
+ase y.
If we de+lare y as final we wonAt !et any +o"pile ti"e error.
ED7=3LE 3:
p(bli+ +lass <Ea"pleCwit+#7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E81)9

117

final int y82)9
swit+#BE/
7
+ase 1).
Cyste".o(t.printlnBN1)N/9
+ase y.
Cyste".o(t.printlnBN2)N/9
===
!.83.8:
1)
2)
Cwit+# ar!("ent and +ase label +an be eEpressions also- ,ut $ase s#ould ,e $onstant
expression9
ED7=3LE 4:
p(bli+ +lass <Ea"pleCwit+#7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E81)9
swit+#BEF1/
7
+ase 1).
+ase 1)F2).
+ase 1)F2)F3).
===
!.83.8:
:o o(tp(t.
<very +ase label s#o(ld be wit#in t#e ran!e of swit+# ar!("ent type.
ED7=3LE 5:
p(bli+ +lass <Ea"pleCwit+#7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
byte b81)9
swit+#Bb/
7
+ase 1).
Cyste".o(t.printlnBN1)N/9
+ase 1)).
Cyste".o(t.printlnBN1))N/9
+ase 1))).
Cyste".o(t.printlnBN1)))N/9
===
!.83.8:
'o"pile ti"e error
D.Y*avaT,ava+ <Ea"pleCwit+#.,ava
<Ea"pleCwit+#.,ava.1). possible loss of pre+ision
fo(nd . int

11$

reV(ired. byte
+ase 1))).
D(pli+ate +ase labels are not allowed.
ED7=3LE 6:
p(bli+ +lass <Ea"pleCwit+#7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E81)9
swit+#BE/
7
+ase &7.
Cyste".o(t.printlnBN&7N/9
+ase &&.
Cyste".o(t.printlnBN&&N/9
+ase QaQ.
Cyste".o(t.printlnBN1))N/9
===
!.83.8:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"pleCwit+#.,ava
<Ea"pleCwit+#.,ava.1). d(pli+ate +ase label
+ase QaQ.
*72E 2.==7RJ:
'I7GR7=:

F7LL<86R!.G6 I/2I'E 86E 2"I8*6:
@it#in t#e swit+# state"ent if any +ase is "at+#ed fro" t#at +ase onwards all
state"ents will be eEe+(ted (ntil end of t#e swit+# Bor/ brea?. T#is is +all Kfall4t#ro(!#L
inside t#e swit+# .
ED7=3LE :
p(bli+ +lass <Ea"pleCwit+#7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E8)9
swit+#BE/
7
+ase ).

11&

Cyste".o(t.printlnBN)N/9
+ase 1.
Cyste".o(t.printlnBN1N/9
brea?9
+ase 2.
Cyste".o(t.printlnBN2N/9
defa(lt.
Cyste".o(t.printlnBNdefa(ltN/9
===
!.83.8:
DM5 xM1 xM2 xM3
) 1 2 defa(lt
1 defa(lt
'EF7.L8 *72E:
@it#in t#e swit+# we +an ta?e t#e default anyw#ere- b(t at "ost on+e it is +onvention
to ta?e defa(lt as last +ase.
ED7=3LE B:
p(bli+ +lass <Ea"pleCwit+#7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E8)9
swit+#BE/
7
defa(lt.
Cyste".o(t.printlnBNdefa(ltN/9
+ase ).
Cyste".o(t.printlnBN)N/9
brea?9
+ase 1.
Cyste".o(t.printlnBN1N/9
+ase 2.
Cyste".o(t.printlnBN2N/9
===
!.83.8:
DM5 xM1 xM2 xM3
) 1 2 defa(lt
2 )
I8ER78I-E 2878E=E/82:
"#ile loop. if we donAt ?now t#e no of iterations in advan+e t#en best loop is w#ile loop.
ED7=3LE 1:
w#ileBrs.neEtB//
7
=

12)

ED7=3LE 2:
w#ileBe.#as%oreel<"entsB//
7
4444444444
4444444444
4444444444
=
ED7=3LE 3:
w#ileBitr.#as:eEtB//
7
4444444444
4444444444
4444444444
=
T#e ar!("ent to t#e w#ile state"ent s#o(ld be 6oolean type. If we are (sin! any ot#er
type we will !et +o"pile ti"e error.
ED7=3LE 1:
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
w#ileB1/
7
Cyste".o(t.printlnBN#elloN/9
===
!.83.8:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"ple@#ile.,ava
<Ea"ple@#ile.,ava.3. in+o"patible types
fo(nd . int
reV(ired. boolean
w#ileB1/
'(rly bra+es are optional and wit#o(t +(rly bra+es we +an ta?e only one state"ent
w#i+# s#o(ld not be de+larative state"ent.
ED7=3LE 2:
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
w#ileBtr(e/
Cyste".o(t.printlnBN#elloN/9
==
!.83.8:
Sello Binfinite ti"es/.

121

ED7=3LE 3:
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
w#ileBtr(e/9
==
!.83.8:
:o o(tp(t.
ED7=3LE 4:
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
w#ileBtr(e/
int E81)9
==
!.83.8:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"ple@#ile.,ava
<Ea"ple@#ile.,ava.4. Q.+lassQ eEpe+ted
int E81)9
<Ea"ple@#ile.,ava.4. not a state"ent
int E81)9
ED7=3LE 5:
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
w#ileBtr(e/
7
int E81)9
===
!.83.8:
:o o(tp(t.
;nrea+#able state"ent in w#ile.
ED7=3LE 6:
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
w#ileBtr(e/
7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9

122

==
!.83.8:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"ple@#ile.,ava
<Ea"ple@#ile.,ava.7. (nrea+#able state"ent
Cyste".o(t.printlnBN#iN/9
ED7=3LE :
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
w#ileBfalse/
7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9
==
!.83.8:
D.Y*avaT,ava+ <Ea"ple@#ile.,ava
<Ea"ple@#ile.,ava.4. (nrea+#able state"ent
7
ED7=3LE B:
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int a81)-b82)9
w#ileBaZb/
7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9
==
!.83.8:
Sello Binfinite ti"es/.
ED7=3LE V:
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
final int a81)-b82)9
w#ileBaZb/
7
Cyste".o(t.printlnBN#elloN/9

123

=
Cyste".o(t.printlnBN#iN/9
==
!.83.8:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"ple@#ile.,ava
<Ea"ple@#ile.,ava.$. (nrea+#able state"ent
Cyste".o(t.printlnBN#iN/9
ED7=3LE 15:
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
final int a81)9
w#ileBaZ2)/
7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9
==
!.83.8:
D.Y*avaT,ava+ <Ea"ple@#ile.,ava
<Ea"ple@#ile.,ava.$. (nrea+#able state"ent
Cyste".o(t.printlnBN#iN/9
:ote.
<very final variable will be repla+ed wit# t#e +orrespondin! val(e by +o"piler.
If any operation involves only +onstants t#en +o"piler is responsible to perfor" t#at
operation.
If any operation involves at least one variable +o"piler wonAt perfor" t#at operation. At
r(nti"e ,v" is responsible to perfor" t#at operation.
ED7=3LE 11:
p(bli+ +lass <Ea"ple@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int a81)9
w#ileBaZ2)/
7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9
==

124

!.83.8:
Sello Binfinite ti"es/.
'o<%#ile:
If we want to eEe+(te loop body at least on+e t#en we s#o(ld !o for do4w#ile.
2(ntax:

'(rly bra+es are optional.
@it#o(t +(rly bra+es we +an ta?e only one state"ent between do and w#ile and it
s#o(ld not be de+larative state"ent.
Example 1:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do
Cyste".o(t.printlnBN#elloN/9
w#ileBtr(e/9
==
!utput:
Sello Binfinite ti"es/.
Example 2:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do9
w#ileBtr(e/9
==
!utput:
'o"pile s(++essf(l.
Example 3:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do
int E81)9
w#ileBtr(e/9
==


125

!utput:
D.Y*avaT,ava+ <Ea"pleDo@#ile.,ava
<Ea"pleDo@#ile.,ava.4. Q.+lassQ eEpe+ted
int E81)9
<Ea"pleDo@#ile.,ava.4. not a state"ent
int E81)9
<Ea"pleDo@#ile.,ava.4. Q/Q eEpe+ted
int E81)9
Example 4:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do
7
int E81)9
=w#ileBtr(e/9
==
!utput:
'o"pile s(++essf(l.
Example 5:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do w#ileBtr(e/
Cyste".o(t.printlnBN#elloN/9
w#ileBtr(e/9
==
!utput:
Sello Binfinite ti"es/.
Rearrange t#e a,ove example:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do
w#ileBtr(e/
Cyste".o(t.printlnBN#elloN/9
w#ileBtr(e/9
==
!utput:
Sello Binfinite ti"es/.


126

Example 6:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do
w#ileBtr(e/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"pleDo@#ile.,ava
<Ea"pleDo@#ile.,ava.4. w#ile eEpe+ted
w#ileBtr(e/9
<Ea"pleDo@#ile.,ava.5. ille!al start of eEpression
=
.nrea$#a,le statement in do %#ile:
Example :
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do
7
Cyste".o(t.printlnBN#elloN/9
=
w#ileBtr(e/9
Cyste".o(t.printlnBN#iN/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"pleDo@#ile.,ava
<Ea"pleDo@#ile.,ava.$. (nrea+#able state"ent
Cyste".o(t.printlnBN#iN/9
Example B:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do
7
Cyste".o(t.printlnBN#elloN/9
=
w#ileBfalse/9
Cyste".o(t.printlnBN#iN/9

127

==
!utput:
Sello
Si
Example V:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int a81)-b82)9
do
7
Cyste".o(t.printlnBN#elloN/9
=
w#ileBaZb/9
Cyste".o(t.printlnBN#iN/9
==
!utput:
Sello Binfinite ti"es/.
Example 15:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int a81)-b82)9
do
7
Cyste".o(t.printlnBN#elloN/9
=
w#ileBaTb/9
Cyste".o(t.printlnBN#iN/9
==
!utput:
Sello
Si
Example 11:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
final int a81)-b82)9
do
7
Cyste".o(t.printlnBN#elloN/9

12$

=
w#ileBaZb/9
Cyste".o(t.printlnBN#iN/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"pleDo@#ile.,ava
<Ea"pleDo@#ile.,ava.&. (nrea+#able state"ent
Cyste".o(t.printlnBN#iN/9
Example 12:
p(bli+ +lass <Ea"pleDo@#ile7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
final int a81)-b82)9
do
7
Cyste".o(t.printlnBN#elloN/9
=
w#ileBaTb/9
Cyste".o(t.printlnBN#iN/9
==
!utput:
D.Y*avaT,ava+ <Ea"pleDo@#ile.,ava
D.Y*avaT,ava <Ea"pleDo@#ile
Sello
Si
For Loop:
T#is is t#e "ost +o""only (sed loop and best s(itable if we ?now t#e no of iterations in
advan+e.
2(ntax:


1; Initili4ationse$tion:
T#is se+tion will be eEe+(ted only on+e.
Sere (s(ally we +an de+lare loop variables and we will perfor" initiali0ation.

12&

@e +an de+lare "(ltiple variables b(t s#o(ld be of t#e sa"e type and we +anAt de+lare
different type of variables.
Example:
1/ Int i8)-,8)9 valid
2; Int i8)-6oolean b8tr(e9 invalid
3/ Int i8)-int ,8)9 invalid
In initiali0ation se+tion we +an ta?e any valid ,ava state"ent in+l(din! Ks.o.pL also.
Example 1:
p(bli+ +lass <Ea"pleHor7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int i8)9
forBCyste".o(t.printlnBN#ello ( r sleepin!N/9iZ39iFF/7
Cyste".o(t.printlnBNno boss- ( only sleepin!N/9
===
!utput:
D.Y*avaT,ava+ <Ea"pleHor.,ava
D.Y*avaT,ava <Ea"pleHor
Sello ( r sleepin!
:o boss- ( only sleepin!
:o boss- ( only sleepin!
:o boss- ( only sleepin!
2; *onditional $#e$+:
@e +an ta?e any ,ava eEpression b(t s#o(ld be of t#e type 6oolean.
'onditional eEpression is optional and if we are not ta?in! any eEpression +o"piler will
pla+e tr(e.
3; In$rement and de$rement se$tion:
Sere we +an ta?e any ,ava state"ent in+l(din! s.o.p also.
Example:
p(bli+ +lass <Ea"pleHor7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int i8)9
forBCyste".o(t.printlnBN#elloN/9iZ39Cyste".o(t.printlnBN#iN//7
iFF9
===
!utput:
D.Y*avaT,ava+ <Ea"pleHor.,ava
D.Y*avaT,ava <Ea"pleHor
Sello

13)

Si
Si
Si
All 3 parts of for loop are independent of ea+# ot#er and all optional.
Example:
p(bli+ +lass <Ea"pleHor7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
forB99/7
Cyste".o(t.printlnBN#elloN/9
===
!utput:
Sello Binfinite ti"es/.
'(rly bra+es are optional and wit#o(t +(rly bra+es we +an ta?e eEa+tly one state"ent
and it s#o(ld not be de+larative state"ent.
.nrea$#a,le statement in for loop:
Example 1:
p(bli+ +lass <Ea"pleHor7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
forBint i8)9tr(e9iFF/7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"pleHor.,ava
<Ea"pleHor.,ava.6. (nrea+#able state"ent
Cyste".o(t.printlnBN#iN/9
Example 2:
p(bli+ +lass <Ea"pleHor7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
forBint i8)9false9iFF/7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9
==
!utput:
'o"pile ti"e error.

131

D.Y*avaT,ava+ <Ea"pleHor.,ava
<Ea"pleHor.,ava.3. (nrea+#able state"ent
forBint i8)9false9iFF/7
Example 3:
p(bli+ +lass <Ea"pleHor7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
forBint i8)99iFF/7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ <Ea"pleHor.,ava
<Ea"pleHor.,ava.6. (nrea+#able state"ent
Cyste".o(t.printlnBN#iN/9
Example 4:
p(bli+ +lass <Ea"pleHor7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int a81)-b82)9
forBint i8)9aZb9iFF/7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9
==
!utput:
Sello Binfinite ti"es/.
Example 5:
p(bli+ +lass <Ea"pleHor7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
final int a81)-b82)9
forBint i8)9aZb9iFF/7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9
==
!utput:
D.Y*avaT,ava+ <Ea"pleHor.,ava

132

<Ea"pleHor.,ava.7. (nrea+#able state"ent
Cyste".o(t.printlnBN#iN/9
For ea$#:
Hor ea+# Introd(+ed in 1.5version.
1est suita,le to retrieve t#e elements of arra(s and $olle$tions.
Example 1: @rite +ode to print t#e ele"ents of sin!le di"ensional array by nor"al for loop and
en#an+ed for loop.
Example:

!utput:
D.Y*avaT,ava+ <Ea"pleHor.,ava
D.Y*avaT,ava <Ea"pleHor
1)
2)
3)
4)
5)
Example 2: @rite +ode to print t#e ele"ents of 2 di"ensional arrays by (sin! nor"al for loop and
en#an+ed for loop.

Example 3: @rite eV(ivalent +ode by Hor <a+# loop for t#e followin! for loop.
p(bli+ +lass <Ea"pleHor7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7

133

forBint i8)9iZ1)9iFF/
7
Cyste".o(t.printlnBN#elloN/9
===
!utput:
D.Y*avaT,ava+ <Ea"pleHor1.,ava
D.Y*avaT,ava <Ea"pleHor1
Sello
Sello
Sello
Sello
Sello
Sello
Sello
Sello
Sello
Sello
@e +anAt write eV(ivalent for ea+# loop.
Hor ea+# loop is t#e "ore +onvenient loop to retrieve t#e ele"ents of arrays and +olle+tions- b(t
its "ain li"itation is it is not a !eneral p(rpose loop.
8ransfer statements:
1rea+ statement:
@e +an (se brea? state"ent in t#e followin! +ases.
1/ Inside swit+# to stop fall4t#ro(!#.
2/ Inside loops to brea? t#e loop based on so"e +ondition.
3/ Inside label blo+?s to brea? blo+? eEe+(tion based on so"e +ondition.
Example 1:
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E81)9
l1.
7
Cyste".o(t.printlnBN#elloN/9
ifBE881)/
brea? l19
Cyste".o(t.printlnBN#iN/9
=
Cyste".o(t.printlnBNendN/9
==


134

!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
Sello
<nd
T#ese are t#e only pla+es w#ere we +an (se brea? state"ent. If we are (sin! anyw#ere
else we will !et +o"pile ti"e error.
Example:
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E81)9
ifBE881)/
brea?9
Cyste".o(t.printlnBN#elloN/9
==
!utput:
'o"pile ti"e error.
D.Y*avaT,ava+ Test.,ava
Test.,ava.5. brea? o(tside swit+# or loop
brea?9
*ontinue statement:
@e +an (se +ontin(e state"ent to s?ip +(rrent iteration and +ontin(e for t#e neEt
iteration.
Example:

!utput:
D.Y*avaT,ava+ Test.,ava
D.Y*avaT,ava Test
1
3
5
7
&

135

@e +an (se +ontin(e only inside loops if we are (sin! anyw#ere else we will !et +o"pile
ti"e error sayin! K+ontin(e o(tside of loopL.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
int E81)9
ifBE881)/9
+ontin(e9
Cyste".o(t.printlnBN#elloN/9
=
=
!utput:
'o"pile ti"e error.
D.Y<n("T,ava+ Test.,ava
Test.,ava.6. +ontin(e o(tside of loop
+ontin(e9
La,eled ,rea+ and $ontinue statements:
In t#e nested loops to brea? Bor/ +ontin(e a parti+(lar loop we s#o(ld !o for labeled
brea? and +ontin(e state"ents.
2(ntax:

Example:
+lass Test
7

136

p(bli+ stati+ void "ainBCtrin! ar!sD>/7
l1.
forBint i8)9iZ39iFF/
7
forBint ,8)9,Z39,FF/
7
ifBi88,/
brea?9
Cyste".o(t.printlnBiFN.........NF,/9
====
1rea+:
1.........)
2.........)
2.........1
1rea+ l1:
:o o(tp(t.
*ontinue:
).........1
).........2
1.........)
1.........2
2.........)
2.........1
*ontinue l1:
1.........)
2.........)
2.........1
'o<%#ile vs $ontinue :8#e most dangerous $om,ination;:


137

!utput:
1
4
6
$
1)
'o"piler wonAt +#e+? (nrea+#ability in t#e +ase of if4else it will +#e+? only in loops.
Example 1:
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
w#ileBtr(e/
7
Cyste".o(t.printlnBN#elloN/9
=
Cyste".o(t.printlnBN#iN/9
=
=
!utput:
'o"pile ti"e error.
D.Y<n("T,ava+ Test.,ava
Test.,ava.$. (nrea+#able state"ent
Cyste".o(t.printlnBN#iN/9
Example 2:
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
ifBtr(e/
7
Cyste".o(t.printlnBN#elloN/9
=
else
7
Cyste".o(t.printlnBN#iN/9
===
!utput:
Sello


13$

Exception Handling
1. Introd(+tion
2. R(nti"e sta+? "e+#anis"
3. Defa(lt eE+eption #andlin! in ,ava
4. <E+eption #ierar+#y
5. '(sto"i0ed eE+eption #andlin! by try +at+#
6. 'ontrol flow in try +at+#
7. %et#ods to print eE+eption infor"ation
$. Try wit# "(ltiple +at+# blo+?s
&. Hinally
1). Differen+e between final- finally- finali0e
11. 'ontrol flow in try +at+# finally
12. 'ontrol flow in nested try +at+# finally
13. ario(s possible +o"binations of try +at+# finally
14. t#row ?eyword
15. t#rows ?eyword
16. <E+eption #andlin! ?eywords s(""ary
17. ario(s possible +o"pile ti"e errors in eE+eption #andlin!
1$. '(sto"i0ed eE+eptions
1&. Top41) eE+eptions
Ex$eption. An (nwanted (neEpe+ted event t#at dist(rbs nor"al flow of t#e pro!ra" is +alled
eE+eption.
Example:
Cleepin!<E+eption
Tyre\(n+#(red<E+eption
Hile:otHo(nd<E+eptione..et+
It is #i!#ly re+o""ended to #andle eE+eptions. T#e "ain ob,e+tive of eE+eption
#andlin! is !ra+ef(l Bnor"al/ ter"ination of t#e pro!ra".
"#at is t#e meaning of ex$eption #andling&
<E+eption #andlin! doesnAt "ean repairin! an eE+eption. @e #ave to define alternative
way to +ontin(e rest of t#e pro!ra" nor"ally t#is way of Kdefinin! alternative is not#in!
b(t eE+eption #andlin!L.
Example: C(ppose o(r pro!ra""in! reV(ire"ent is to read data fro" London file at r(nti"e if
London file is not available o(r pro!ra" s#o(ld not be ter"inated abnor"ally. @e #ave to
provide a lo+al file to +ontin(e rest of t#e pro!ra" nor"ally. T#is way of definin! alternative is
not#in! b(t eE+eption #andlin!.


13&

Example:
try
7
read data fro" london file
=
+at+#BHile:otHo(nd<E+eption e/
7
(se lo+al file and +ontin(e rest of t#e pro!ra" nor"ally
=
=
.
.
.
Runtime sta$+ me$#anism: Hor every t#read *% will +reate a separate sta+? all "et#od +alls
perfor"ed by t#e t#read will be stored in t#at sta+?. <a+# entry in t#e sta+? is +alled Kone
a+tivation re+ordL Bor/ Ksta+? fra"eL. After +o"pletin! every "et#od +all *% re"oves t#e
+orrespondin! entry fro" t#e sta+?. After +o"pletin! all "et#od +alls *% destroys t#e e"pty
sta+? and ter"inates t#e pro!ra" nor"ally.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
doCt(ffB/9
=
p(bli+ stati+ void doCt(ffB/7
do%oreCt(ffB/9
=
p(bli+ stati+ void do%oreCt(ffB/7
Cyste".o(t.printlnBNSelloN/9
==
!utput:
Sello
'iagram:




14)

'efault ex$eption #andling in java:
1/ If an eE+eption raised inside any "et#od t#en t#e "et#od is responsible to +reate
<E+eption ob,e+t wit# t#e followin! infor"ation.
1/ :a"e of t#e eE+eption.
2/ Des+ription of t#e eE+eption.
3/ Lo+ation of t#e eE+eption.
2/ After +reatin! t#at <E+eption ob,e+t t#e "et#od #andovers t#at ob,e+t to t#e *%.
3/ *% +#e+?s w#et#er t#e "et#od +ontains any eE+eption #andlin! +ode or not. If
"et#od wonAt +ontain any #andlin! +ode t#en *% ter"inates t#at "et#od abnor"ally
and re"oves +orrespondin! entry for" t#e sta+?.
4/ *% identifies t#e +aller "et#od and +#e+?s w#et#er t#e +aller "et#od +ontain any
#andlin! +ode or not. If t#e +aller "et#od also does not +ontain #andlin! +ode t#en *%
ter"inates t#at +aller also abnor"ally and t#e re"oves +orrespondin! entry fro" t#e
sta+?.
5/ T#is pro+ess will be +ontin(ed (ntil "ainB/ "et#od and if t#e "ainB/ "et#od also
doesnAt +ontain any eE+eption #andlin! +ode t#en *% ter"inates "ainB/ "et#od and
re"oves +orrespondin! entry fro" t#e sta+?.
6/ T#en *% #andovers t#e responsibility of eE+eption #andlin! to t#e defa(lt eE+eption
#andler.
7/ Defa(lt eE+eption #andler ,(st print eE+eption infor"ation to t#e +onsole in t#e
followin! for"ats and ter"inates t#e pro!ra" abnor"ally.
:a"e of eE+eption. des+ription
Lo+ation of eE+eption Bsta+? tra+e/
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
doCt(ffB/9
=
p(bli+ stati+ void doCt(ffB/7
do%oreCt(ffB/9
=
p(bli+ stati+ void do%oreCt(ffB/7
Cyste".o(t.printlnB1)J)/9
==
!utput:
R(nti"e error
<E+eption in t#read N"ainN ,ava.lan!.Arit#"eti+<E+eption. J by 0ero

141

at Test.do%oreCt(ffBTest.,ava.1)/
at Test.doCt(ffBTest.,ava.7/
at Test."ainBTest.,ava.4/
'iagram.

Ex$eption #ierar$#(:

T#rowable a+ts as a root for eE+eption #ierar+#y.
T#rowable +lass +ontains t#e followin! two +#ild +lasses.

Ex$eption. %ost of t#e +ases eE+eptions are +a(sed by o(r pro!ra" and t#ese are re+overable.
Error: %ost of t#e +ases errors are not +a(sed by o(r pro!ra" t#ese are d(e to la+? of syste"
reso(r+es and t#ese are non re+overable.
*#e$+ed -s .n$#e$+ed Ex$eptions:
T#e eE+eptions w#i+# are +#e+?ed by t#e +o"piler for s"oot# eEe+(tion of t#e pro!ra"
at r(nti"e are +alled +#e+?ed eE+eptions.
1/ SallTi+?et%issin!<E+eption
2/ \en:ot@or?in!<E+eption
3/ Hile:otHo(nd<E+eption
T#e eE+eptions w#i+# are not +#e+?ed by t#e +o"piler are +alled (n+#e+?ed eE+eptions.
1/ 6o"b6la(st<E+eption
2/ Arit#"eti+<E+eption
3/ :(ll\ointer<E+eption
/ote: R(nti"e<E+eption and its +#ild +lasses- <rror and its +#ild +lasses are (n+#e+?ed and all
t#e re"ainin! are +onsidered as +#e+?ed eE+eptions.
/ote: @#et#er eE+eption is +#e+?ed or (n+#e+?ed +o"p(lsory it s#o(ld o++(r at r(nti"e only
t#ere is no +#an+e of o++(rrin! any eE+eption at +o"pile ti"e.



142

3artiall( $#e$+ed -s full( $#e$+ed:
A +#e+?ed eE+eption is said to be f(lly +#e+?ed if and only if all its +#ild +lasses are also
+#e+?ed.
Example:
1/ II<E+eption
2/ Interr(pted<E+eption
A +#e+?ed eE+eption is said to be partially +#e+?ed if and only if so"e of its +#ild +lasses
are (n+#e+?ed.
Example: <E+eption
T#e only partially +#e+?ed eE+eptions available in ,ava are.
1. T#rowable.
2. <E+eption.
"#i$# of t#e follo%ing are $#e$+ed&
1. R(nti"e<E+eption44444(n+#e+?ed
2. <rror44444(n+#e+?ed
3. II<E+eption44444f(lly +#e+?ed
4. <E+eption44444partially +#e+?ed
5. Interr(pted<E+eption44444f(lly +#e+?ed
6. T#rowable444444partially +#e+?ed
'iagram:



143

*ustomi4ed ex$eption #andling ,( tr( $at$#:
It is #i!#ly re+o""ended to #andle eE+eptions.
In o(r pro!ra" t#e +ode w#i+# "ay +a(se an eE+eption is +alled ris?y +ode we #ave to
pla+e ris?y +ode inside try blo+? and t#e +orrespondin! #andlin! +ode inside +at+# blo+?.
Example:
try
7
ris?y +ode
=
+at+#B<E+eption e/
7
#andlin! +ode
=

"it#out tr( $at$# "it# tr( $at$#
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Cyste".o(t.printlnBNstate"ent1N/9
Cyste".o(t.printlnB1)J)/9
Cyste".o(t.printlnBNstate"ent3N/9
=
=
7,normal termination9

+lass Test7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Cyste".o(t.printlnBNstate"ent1N/9
try7
Cyste".o(t.printlnB1)J)/9
=
+at+#BArit#"eti+<E+eption e/7
Cyste".o(t.printlnB1)J2/9
=
Cyste".o(t.printlnBNstate"ent3N/9
==
!utput:
state"ent1
5
state"ent3
/ormal termination9
*ontrol flo% in tr( $at$#:
*ase 1: T#ere is no eE+eption.
1- 2- 3- 5 nor"al ter"ination.
*ase 2: if an eE+eption raised at state"ent 2 and +orrespondin! +at+# blo+? "at+#ed 1- 4- 5
nor"al ter"ination.
*ase 3: if an eE+eption raised at state"ent 2 b(t t#e +orrespondin! +at+# blo+? not "at+#ed 1
followed by abnor"al ter"ination.
*ase 4: if an eE+eption raised at state"ent 4 or state"ent 5 t#en itAs always abnor"al
ter"ination of t#e pro!ra".


144

/ote:
1. @it#in t#e try blo+? if anyw#ere an eE+eption raised t#en rest of t#e try blo+? wonAt
be eEe+(ted even t#o(!# we #andled t#at eE+eption. Sen+e we #ave to pla+eJta?e
only ris? +ode inside try and lengt# of t#e try blo+? s#o(ld be as less as possible.
2. If any state"ent w#i+# raises an eE+eption and it is not part of any try blo+? t#en it is
always abnor"al ter"ination of t#e pro!ra".
39 T#ere "ay be a +#an+e of raisin! an eE+eption inside +at+# and finally blo+?s also in
addition to try blo+?.
-arious met#ods to print ex$eption information:
T#rowable +lass defines t#e followin! "et#ods to print eE+eption infor"ation to t#e
+onsole.
print2ta$+8ra$e:;: T#is "et#od prints eE+eption infor"ation in t#e followin! for"at.
:a"e of t#e eE+eption. des+ription of eE+eption
Cta+? tra+e
to2tring:;: T#is "et#od prints eE+eption infor"ation in t#e followin! for"at.
:a"e of t#e eE+eption. des+ription of eE+eption
get=essage:;: T#is "et#od ret(rns only des+ription of t#e eE+eption.
Des+ription.
Example:

/ote: Defa(lt eE+eption #andler internally (ses printCta+?Tra+eB/ "et#od to print eE+eption
infor"ation to t#e +onsole.
8r( %it# multiple $at$# ,lo$+s: T#e way of #andlin! an eE+eption is varied fro" eE+eption to
eE+eption #en+e for every eE+eption raise a separate +at+# blo+? is reV(ired t#at is try wit#
"(ltiple +at+# blo+?s is possible and re+o""ended to (se.
Example:
try
7
.
try
7
.

145

.
.
.
=
+at+#B<E+eption e/
7
defa(lt #andler
=
T#is approa+# is not re+o""ended
be+a(se for any type of <E+eption
we are (sin! t#e sa"e +at+# blo+?.
.
.
.
+at+#BHile:otHo(nd<E+eption e/
7
(se lo+al file
=
+at+#BArit#"eti+<E+eption e/
7
perfor" t#ese Arit#"eti+ operations
=
+at+#BC_L<E+eption e/
7
donQt (se ora+le db- (se "ysVl db
=
+at+#B<E+eption e/
7
defa(lt #andler
=
T#is approa+# is #i!#ly re+o""ended
be+a(se for any eE+eption raise we are
definin! a separate +at+# blo+?.
If try wit# "(ltiple +at+# blo+?s presents t#en order of +at+# blo+?s is very i"portant it
s#o(ld be fro" +#ild to parent by "ista?e if we are ta?in! fro" parent to +#ild t#en we
will !et 'o"pile ti"e error sayin! KeE+eption EEE #as already been +a(!#tL.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
try
7
Cyste".o(t.printlnB1)J)/9
=
+at+#B<E+eption e/
7
e.printCta+?Tra+eB/9
=
+at+#BArit#"eti+<E+eption e/
7
e.printCta+?Tra+eB/9
===
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
try
7
Cyste".o(t.printlnB1)J)/9
=
+at+#BArit#"eti+<E+eption e/
7
e.printCta+?Tra+eB/9
=
+at+#B<E+eption e/
7
e.printCta+?Tra+eB/9
===

146

!utput:
'o"pile ti"e error.
Test.,ava.13. eE+eption
,ava.lan!.Arit#"eti+<E+eption #as already been
+a(!#t
+at+#BArit#"eti+<E+eption e/
!utput:
'o"pile s(++essf(lly.

Finall( ,lo$+:
It is never re+o""ended to ta?e +lean (p +ode inside try blo+? be+a(se t#ere is no
!(arantee for t#e eEe+(tion of every state"ent inside a try.
It is never re+o""ended to pla+e +lean (p +ode inside +at+# blo+? be+a(se if t#ere is no
eE+eption t#en +at+# blo+? wonAt be eEe+(ted.
@e reV(ire so"e pla+e to "aintain +lean (p +ode w#i+# s#o(ld be eEe+(ted always
irrespe+tive of w#et#er eE+eption raised or not raised and w#et#er #andled or not
#andled s(+# type of pla+e is not#in! b(t finally blo+?.
Sen+e t#e "ain ob,e+tive of finally blo+? is to "aintain +lean(p +ode.
Example:
try
7
ris?y +ode
=
+at+#BE e/
7
#andlin! +ode
=
finally
7
+lean(p +ode
=
T#e spe+ialty of finally blo+? is it will be eEe+(ted always irrespe+tive of w#et#er t#e
eE+eption raised or not raised and w#et#er #andled or not #andled.
Example 1:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
try
7
Cyste".o(t.printlnBNtry blo+? eEe+(tedN/9
=
+at+#BArit#"eti+<E+eption e/

147

7
Cyste".o(t.printlnBN+at+# blo+? eEe+(tedN/9
=
finally
7
Cyste".o(t.printlnBNfinally blo+? eEe+(tedN/9
===
!utput:
Try blo+? eEe+(ted
Hinally blo+? eEe+(ted
Example 2:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
try
7
Cyste".o(t.printlnBNtry blo+? eEe+(tedN/9
Cyste".o(t.printlnB1)J)/9
=
+at+#BArit#"eti+<E+eption e/
7
Cyste".o(t.printlnBN+at+# blo+? eEe+(tedN/9
=
finally
7
Cyste".o(t.printlnBNfinally blo+? eEe+(tedN/9
===
!utput:
Try blo+? eEe+(ted
'at+# blo+? eEe+(ted
Hinally blo+? eEe+(ted
Example 3:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
try

14$

7
Cyste".o(t.printlnBNtry blo+? eEe+(tedN/9
Cyste".o(t.printlnB1)J)/9
=
+at+#B:(ll\ointer<E+eption e/
7
Cyste".o(t.printlnBN+at+# blo+? eEe+(tedN/9
=
finally
7
Cyste".o(t.printlnBNfinally blo+? eEe+(tedN/9
===
!utput:
Try blo+? eEe+(ted
Hinally blo+? eEe+(ted
<E+eption in t#read N"ainN ,ava.lan!.Arit#"eti+<E+eption. J by 0ero
at Test."ainBTest.,ava.$/
Return -s Finall(:
<ven t#o(!# ret(rn present in try or +at+# blo+?s first finally will be eEe+(ted and after
t#at only ret(rn state"ent will be +onsidered t#at is finally blo+? do"inates ret(rn
state"ent.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
try
7
Cyste".o(t.printlnBNtry blo+? eEe+(tedN/9
ret(rn9
=
+at+#BArit#"eti+<E+eption e/
7
Cyste".o(t.printlnBN+at+# blo+? eEe+(tedN/9
=
finally
7
Cyste".o(t.printlnBNfinally blo+? eEe+(tedN/9

14&

===
!utput:
Try blo+? eEe+(ted
Hinally blo+? eEe+(ted
If ret(rn state"ent present try +at+# and finally blo+?s t#en finally blo+? ret(rn
state"ent will be +onsidered.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnB"et#odIneB//9
=
p(bli+ stati+ int "et#odIneB/7
try
7
Cyste".o(t.printlnB1)J)/9
ret(rn 7779
=
+at+#BArit#"eti+<E+eption e/
7
ret(rn $$$9
=
finally7
ret(rn &&&9
===
!utput:
&&&
T#ere is only one sit(ation w#ere t#e finally blo+? wonAt be eEe+(ted is w#enever we
are (sin! Cyste".eEitB)/ "et#od.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
try
7
Cyste".o(t.printlnBNtryN/9

15)

Cyste".eEitB)/9
=
+at+#BArit#"eti+<E+eption e/
7
Cyste".o(t.printlnBN+at+# blo+? eEe+(tedN/9
=
finally
7
Cyste".o(t.printlnBNfinally blo+? eEe+(tedN/9
===
!utput:
Try
'ifferen$e ,et%een finalH finall(H and finali4e.
Final:
Hinal is t#e "odifier appli+able for +lass- "et#ods and variables.
If a +lass de+lared as t#e final t#en +#ild +lass +reation is not possible.
If a "et#od de+lared as t#e final t#en overridin! of t#at "et#od is not possible.
If a variable de+lared as t#e final t#en reassi!n"ent is not possible.
Finall(:
It is t#e blo+? always asso+iated wit# try +at+# to "aintain +lean (p +ode w#i+# s#o(ld
be eEe+(ted always irrespe+tive of w#et#er eE+eption raised or not raised and w#et#er
#andled or not #andled.
Finali4e:
It is a "et#od w#i+# s#o(ld be +alled by !arba!e +olle+tor always ,(st before destroyin!
an ob,e+t to perfor" +lean(p a+tivities.
/ote:
To "aintain +lean (p +ode fa(nally blo+? is re+o""ended over finali0eB/ "et#od
be+a(se we +anAt eEpert eEa+t be#avior of ^'.
*ontrol flo% in tr( $at$# finall(:
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try7
Cyste".o(t.printlnBNstate"ent1N/9
Cyste".o(t.printlnBNstate"ent2N/9
Cyste".o(t.printlnBNstate"ent3N/9
=

151

+at+#B<E+eption e/7
Cyste".o(t.printlnBNstate"ent4N/9
=
finally
7
Cyste".o(t.printlnBNstate"ent5N/9
=
Cyste".o(t.printlnBNstate"ent6N/9
=
=
*ase 1: If t#ere is no eE+eption. 1- 2- 3- 5- 6 nor"al ter"ination.
*ase 2: if an eE+eption raised at state"ent 2 and +orrespondin! +at+# blo+? "at+#ed. 1-4-5-6
nor"al ter"inations.
*ase 3: if an eE+eption raised at state"ent 2 and +orrespondin! +at+# blo+? is not "at+#ed. 1-5
abnor"al ter"ination.
*ase 4: if an eE+eption raised at state"ent 4 t#en itAs always abnor"al ter"ination b(t before
t#e finally blo+? will be eEe+(ted.
*ase 5: if an eE+eption raised at state"ent 5 or state"ent 6 its always abnor"al ter"ination.
*ontrol flo% in nested tr( $at$# finall(:
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try7
Cyste".o(t.printlnBNstate"ent1N/9
Cyste".o(t.printlnBNstate"ent2N/9
Cyste".o(t.printlnBNstate"ent3N/9
try7
Cyste".o(t.printlnBNstate"ent4N/9
Cyste".o(t.printlnBNstate"ent5N/9
Cyste".o(t.printlnBNstate"ent6N/9
=
+at+#BArit#"eti+<E+eption e/7
Cyste".o(t.printlnBNstate"ent7N/9
=
finally
7
Cyste".o(t.printlnBNstate"ent$N/9

152

=
Cyste".o(t.printlnBNstate"ent&N/9
=
+at+#B<E+eption e/
7
Cyste".o(t.printlnBNstate"ent1)N/9
=
finally
7
Cyste".o(t.printlnBNstate"ent11N/9
=
Cyste".o(t.printlnBNstate"ent12N/9
=
=
*ase 1: if t#ere is no eE+eption. 1- 2- 3- 4- 5- 6- $- &- 11- 12 nor"al ter"ination.
*ase 2: if an eE+eption raised at state"ent 2 and +orrespondin! +at+# blo+? "at+#ed
1-1)-11-12 nor"al ter"inations.
*ase 3: if an eE+eption raised at state"ent 2 and +orrespondin! +at+# blo+? is not "at+#ed 1-
11 abnor"al ter"ination.
*ase 4: if an eE+eption raised at state"ent 5 and +orrespondin! inner +at+# #as "at+#ed 1- 2-
3- 4- 7- $- &- 11- 12 nor"al ter"ination.
*ase 5: if an eE+eption raised at state"ent 5 and inner +at+# #as not "at+#ed b(t o(ter +at+#
blo+? #as "at+#ed. 1- 2- 3- 4- $- 1)- 11- 12 nor"al ter"ination.
*ase 6: if an eE+eption raised at state"ent 5 and bot# inner and o(ter +at+# blo+?s are not
"at+#ed. 1- 2- 3- 4- $- 11 abnor"al ter"ination.
*ase : if an eE+eption raised at state"ent 7 and t#e +orrespondin! +at+# blo+? "at+#ed 1- 2-
3-.-.-.- $- 1)- 11- 12 nor"al ter"ination.
*ase B: if an eE+eption raised at state"ent 7 and t#e +orrespondin! +at+# blo+? not "at+#ed 1-
2- 3-.-.-.-$-11 abnor"al ter"inations.
*ase V: if an eE+eption raised at state"ent $ and t#e +orrespondin! +at+# blo+? #as "at+#ed 1-
2- 3-.-.-.-.- 1)- 11-12 nor"al ter"ination.
*ase 15. if an eE+eption raised at state"ent $ and t#e +orrespondin! +at+# blo+? not "at+#ed
1- 2- 3-.-.-.-.- 11 abnor"al ter"inations.
*ase 11: if an eE+eption raised at state"ent & and +orrespondin! +at+# blo+? "at+#ed 1- 2-
3-.-.-.-.- $-1)-11-12 nor"al ter"ination.
*ase 12: if an eE+eption raised at state"ent & and +orrespondin! +at+# blo+? not "at+#ed 1- 2-
3-.-.-.-.- $- 11 abnor"al ter"ination.

153

*ase 13: if an eE+eption raised at state"ent 1) is always abnor"al ter"ination b(t before t#at
finally blo+? 11 will be eEe+(ted.
*ase 14: if an eE+eption raised at state"ent 11 or 12 is always abnor"al ter"ination.
/ote: if we are not enterin! into t#e try blo+? t#en t#e finally blo+? wonAt be eEe+(ted. In+e
we entered into t#e try blo+? wit#o(t eEe+(tin! finally blo+? we +anAt +o"e o(t.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try7
Cyste".o(t.printlnB1)J)/9
=
+at+#BArit#"eti+<E+eption e/
7
Cyste".o(t.printlnB1)J)/9
=
finally7
Ctrin! s8n(ll9
Cyste".o(t.printlnBs.len!t#B//9
===
/ote: Defa(lt eE+eption #andler +an #andle only one eE+eption at a ti"e and t#at is t#e "ost
re+ently raised eE+eption.
-arious possi,le $om,inations of tr( $at$# finall(:
Example 1:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7=
+at+#BArit#"eti+<E+eption e/
7=
==
!utput:
'o"pile and r(nnin! s(++essf(lly.
Example 2:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7=

154

+at+#BArit#"eti+<E+eption e/
7=
+at+#B:(ll\ointer<E+eption e/
7=
=
=
!utput:
'o"pile and r(nnin! s(++essf(lly.
Example 3:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7=
+at+#BArit#"eti+<E+eption e/
7=
+at+#BArit#"eti+<E+eption e/
7=
=
=
!utput:
'o"pile ti"e error.
Test1.,ava.7. eE+eption ,ava.lan!.Arit#"eti+<E+eption #as already been +a(!#t
+at+#BArit#"eti+<E+eption e/
Example 4:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7=
=
=
!utput:
'o"pile ti"e error
Test1.,ava.3. QtryQ wit#o(t Q+at+#Q or QfinallyQ
try
Example 5:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
+at+#B<E+eption e/

155

7=
=
=
!utput:
'o"pile ti"e error.
Test1.,ava.3. Q+at+#Q wit#o(t QtryQ
+at+#B<E+eption e/
Example 6:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7=
Cyste".o(t.printlnBN#elloN/9
+at+#B<E+eption e/
7=
=
=
!utput:
'o"pile ti"e error.
Test1.,ava.3. QtryQ wit#o(t Q+at+#Q or QfinallyQ
Try
Example :
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7=
+at+#B<E+eption e/
7=
finally
7=
=
=
!utput:
'o"pile and r(nnin! s(++essf(lly.
Example B:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try

156

7=
finally
7=
=
=
!utput:
'o"pile and r(nnin! s(++essf(lly.
Example V:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7=
finally
7=
finally
7=
=
=
!utput:
'o"pile ti"e error.
Test1.,ava.7. QfinallyQ wit#o(t QtryQ
Hinally
Example 15:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7=
+at+#B<E+eption e/
7=
Cyste".o(t.printlnBN#elloN/9
finally
7=
=
=
!utput:
'o"pile ti"e error.
Test1.,ava.$. QfinallyQ wit#o(t QtryQ
Hinally

157

Example 11:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7=
finally
7=
+at+#B<E+eption e/
7=
=
=
!utput:
'o"pile ti"e error.
Test1.,ava.7. Q+at+#Q wit#o(t QtryQ
+at+#B<E+eption e/
Example 12:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
finally
7=
=
=
!utput:
Test1.,ava.3. QfinallyQ wit#o(t QtryQ
Hinally
Example 13:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7 try7=
+at+#B<E+eption e/7=
=
+at+#B<E+eption e/
7=
=
=
!utput:
'o"pile and r(nnin! s(++essf(lly.

15$

Example 14:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7 =
+at+#B<E+eption e/
7
try7=
finally7=
=
=
=
!utput:
'o"pile and r(nnin! s(++essf(lly.
Example 15:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try
7 =
+at+#B<E+eption e/
7
try7=
+at+#B<E+eption e/7=
=
finally7
finally7=
=
=
=
!utput:
'o"pile ti"e error.
Test1.,ava.11. QfinallyQ wit#o(t QtryQ
finally7=
Example 16:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
finally7=
try7 =

15&

+at+#B<E+eption e/7=
=
=
!utput:
'o"pile ti"e error.
Test1.,ava.3. QfinallyQ wit#o(t QtryQ
finally7=
Example 1:
+lass Test17
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try7 =
+at+#B<E+eption e/7=
finally
7
try7=
+at+#B<E+eption e/7=
finally7=
=
=
=
!utput:
'o"pile and r(nnin! s(++essf(lly.
8#ro% statement: 2o"eti"e we +an +reate eE+eption ob,e+t eEpli+itly and we +an #and over to
t#e *% "an(ally by (sin! t#row ?eyword.
Example:

T#e res(lt of followin! 2 pro!ra"s is eEa+tly sa"e.
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Cyste".o(t.printlnB1)J)/9
==
In t#is +ase +reation of
Arit#"eti+<E+eption ob,e+t and
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
t#row new Arit#"eti+<E+eptionBNJ by 0eroN/9
==
In t#is +ase we are +reatin! eE+eption

16)

#andover to t#e ,v" will be perfor"ed
a(to"ati+ally by t#e "ainB/ "et#od.
ob,e+t eEpli+itly and #andover to t#e
*% "an(ally.
/ote: In !eneral we +an (se t#row ?eyword for +(sto"i0ed eE+eptions b(t not for predefined
eE+eptions.
*ase 1: t#row e9
If e refers n(ll t#en we will !et :(ll\ointer<E+eption.
Example:
+lass Test3
7
stati+ Arit#"eti+<E+eption e8new
Arit#"eti+<E+eptionB/9
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
t#row e9
=
=
!utput:
R(nti"e eE+eption. <E+eption in t#read
N"ainN ,ava.lan!.Arit#"eti+<E+eption
+lass Test
7
stati+ Arit#"eti+<E+eption e9
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
t#row e9
=
=
!utput:
<E+eption in t#read N"ainN
,ava.lan!.:(ll\ointer<E+eption
at Test3."ainBTest3.,ava.5/
*ase 2: After t#row state"ent we +anAt ta?e any state"ent dire+tly ot#erwise we will !et
+o"pile ti"e error sayin! (nrea+#able state"ent.
Example:
+lass Test3
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Cyste".o(t.printlnB1)J)/9
Cyste".o(t.printlnBN#elloN/9
=
=
!utput:
Runtime error: <E+eption in t#read N"ainN
,ava.lan!.Arit#"eti+<E+eption. J by 0ero
at Test3."ainBTest3.,ava.4/
+lass Test3
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
t#row new Arit#"eti+<E+eptionBNJ by 0eroN/9
Cyste".o(t.printlnBN#elloN/9
=
=
!utput:
'o"pile ti"e error.
Test3.,ava.5. (nrea+#able state"ent
Cyste".o(t.printlnBN#elloN/9
*ase 3: @e +an (se t#row ?eyword only for T#rowable types ot#erwise we will !et +o"pile
ti"e error sayin! in+o"p(table types.
Example:
+lass Test3
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
t#row new Test3B/9
=
=!utput:
'o"pile ti"e error.
+lass Test3 eEtends R(nti"e<E+eption
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
t#row new Test3B/9
=
=
!utput:

161

Test3.,ava.4. in+o"patible types
fo(nd . Test3
reV(ired. ,ava.lan!.T#rowable
t#row new Test3B/9
R(nti"e error. <E+eption in t#read N"ainN
Test3
at Test3."ainBTest3.,ava.4/
8#ro%s statement: in o(r pro!ra" if t#ere is any +#an+e of raisin! +#e+?ed eE+eption
+o"p(lsory we s#o(ld #andle eit#er by try +at+# or by t#rows ?eyword ot#erwise t#e +ode
wonAt +o"pile.
Example:
+lass Test3
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
T#read.sleepB5)))/9
=
=
;nreported eE+eption ,ava.lan!.Interr(pted<E+eption9 "(st be +a(!#t or de+lared to be
t#rown. @e +an #andle t#is +o"pile ti"e error by (sin! t#e followin! 2 ways.
Example:
1( using tr( $at$# 1( using t#ro%s +e(%ord
+lass Test3
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
try7
T#read.sleepB5)))/9
=
+at+#BInterr(pted<E+eption e/7=
=
=
!utput:
'o"pile and r(nnin! s(++essf(lly
@e +an (se t#rows ?eyword to
deli+ate t#e responsibility of
eE+eption #andlin! to t#e +aller
"et#od. T#en +aller "et#od is
responsible to #andle t#at
eE+eption.
+lass Test3
7
p(bli+ stati+ void "ainBCtrin!D>
ar!s/t#rows Interr(pted<E+eption7
T#read.sleepB5)))/9
=
=
!utput:
'o"pile and r(nnin! s(++essf(lly
Sen+e t#e "ain ob,e+tive of Kt#rowsL ?eyword is to deli+ate t#e responsibility of
eE+eption #andlin! to t#e +aller "et#od.
Kt#rowsL ?eyword reV(ired only +#e+?ed eE+eptions. ;sa!e of t#rows for (n+#e+?ed
eE+eption t#ere is no (se.
Kt#rowsL ?eyword reV(ired only to +onvenes +o"plier. ;sa!e of t#rows ?eyword
doesnAt prevent abnor"al ter"ination of t#e pro!ra".


162

Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows Interr(pted<E+eption7
doCt(ffB/9
=
p(bli+ stati+ void doCt(ffB/t#rows Interr(pted<E+eption7
do%oreCt(ffB/9
=
p(bli+ stati+ void do%oreCt(ffB/t#rows Interr(pted<E+eption7
T#read.sleepB5)))/9
=
=
!utput:
'o"pile and r(nnin! s(++essf(lly.
In t#e above pro!ra" if we are re"ovin! at least one t#rows ?eyword t#en t#e pro!ra"
wonAt +o"pile.
*ase 1: we +an (se t#rows ?eyword only for T#rowable types ot#erwise we will !et +o"pile
ti"e error sayin! in+o"patible types.
Example:
+lass Test37
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows
Test3
7=
=
!utput:
'o"pile ti"e error
Test3.,ava.2. in+o"patible types
fo(nd . Test3
reV(ired. ,ava.lan!.T#rowable
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows
Test3
+lass Test3 eEtends R(nti"e<E+eption7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows
Test3
7=
=
!utput:
'o"pile and r(nnin! s(++essf(lly.

*ase 2:
Example:
+lass Test37
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
t#row new <E+eptionB/9
=
=
!utput:
+lass Test37
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
t#row new <rrorB/9
=
=
!utput:

163

'o"pile ti"e error.
Test3.,ava.3. (nreported eE+eption
,ava.lan!.<E+eption9 "(st be +a(!#t or
de+lared to be t#rown
R(nti"e error
<E+eption in t#read N"ainN ,ava.lan!.<rror
at Test3."ainBTest3.,ava.3/
*ase 3:
In o(r pro!ra" if t#ere is no +#an+e of risin! an eE+eption t#en we +anAt ri!#t +at+#
blo+? for t#at eE+eption ot#erwise we will !et +o"pile ti"e error sayin! eE+eption PPP
is never t#rown in body of +orrespondin! try state"ent. 6(t t#is r(le is appli+able only
for f(lly +#e+?ed eE+eption.
Example:


Ex$eption #andling +e(%ords summar(:
1/ tr(: To "aintain ris?y +ode.
2/ $at$#: To "aintain #andlin! +ode.
3/ finall(: To "aintain +lean(p +ode.
4/ t#ro%: To #andover o(r +reated eE+eption ob,e+t to t#e *% "an(ally.
5/ t#ro%s: To dele!ate responsibility of eE+eption #andlin! to t#e +aller "et#od.
-arious possi,le $ompile time errors in ex$eption #andling:
1/ <E+eption PPP #as already been +a(!#t.
2/ ;nreported eE+eption PPP "(st be +a(!#t or de+lared to be t#rown.
3/ <E+eption PPP is never t#rown in body of +orrespondin! try state"ent.
4/ Try wit#o(t +at+# or finally.
5/ 'at+# wit#o(t try.
6/ Hinally wit#o(t try.

164

7/ In+o"patible types.
Ho(nd.test
ReV(ried.,ava.lan!.T#rowable9
$/ ;nrea+#able state"ent.
*ustomi4ed Ex$eptions :.ser defined Ex$eptions;:
Co"eti"es we +an +reate o(r own eE+eption to "eet o(r pro!ra""in! reV(ire"ents.
C(+# type of eE+eptions are +alled +(sto"i0ed eE+eptions B(ser defined eE+eptions/.
Example:
1/ InC(ffi+ientH(nds<E+eption
2/ Tooao(n!<E+eption
3/ TooIld<E+eption
3rogram:
+lass Tooao(n!<E+eption eEtends R(nti"e<E+eption
7
Tooao(n!<E+eptionBCtrin! s/
7
s(perBs/9
=
=
+lass TooIld<E+eption eEtends R(nti"e<E+eption
7
TooIld<E+eptionBCtrin! s/
7
s(perBs/9
=
=
+lass '(sto"i0ed<E+eptionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
int a!e8Inte!er.parseIntBar!sD)>/9
ifBa!eT6)/
7
t#row new Tooao(n!<E+eptionBNplease wait so"e "ore ti"e.... ( will !et best "at+#N/9
=
else ifBa!eZ1$/
7
t#row new TooIld<E+eptionBN( r a!e already +rossed....no +#an+e of !ettin! "arriedN/9
=

165

else
7
Cyste".o(t.printlnBNyo( will !et "at+# details soon by e4"ailN/9
===
!utput:
1/ <.Ys+,pT,ava '(sto"i0ed<E+eptionDe"o 61
<E+eption in t#read N"ainN Tooao(n!<E+eption. please wait so"e "ore ti"e.... ( will !et
best "at+#
at '(sto"i0ed<E+eptionDe"o."ainB'(sto"i0ed<E+eptionDe"o.,ava.21/
2/ <.Ys+,pT,ava '(sto"i0ed<E+eptionDe"o 27
ao( will !et "at+# details soon by e4"ail
3/ <.Ys+,pT,ava '(sto"i0ed<E+eptionDe"o &
<E+eption in t#read N"ainN TooIld<E+eption. ( r a!e already +rossed....no +#an+e of !ettin!
"arried
at '(sto"i0ed<E+eptionDe"o."ainB'(sto"i0ed<E+eptionDe"o.,ava.25/
/ote: It is #i!#ly re+o""ended to "aintain o(r +(sto"i0ed eE+eptions as (n+#e+?ed by
eEtendin! R(nti"e<E+eption.
@e +an +at+# any T#rowable type in+l(din! <rrors also.
Example:

8op<15 Ex$eptions:
<E+eptions are divided into two types. T#ey are.
1/ *% <E+eptions.
2/ \ro!ra"ati+ eE+eptions.
0-= Ex$eptions:
T#e eE+eptions w#i+# are raised a(to"ati+ally by t#e ,v" w#enever a parti+(lar event
o++(rs.
Example:
1/ ArrayIndeEI(tIf6o(nds<E+eptionBAIII6</
2/ :(ll\ointer<E+eption B:\</.
3rogramati$ Ex$eptions:
T#e eE+eptions w#i+# are raised eEpli+itly by t#e pro!ra""er Bor/ by t#e A\I developer
are +alled pro!ra"ati+ eE+eptions.
Example:
1/ Ille!alAr!("ent<E+eptionBIA</.

166

1; 7rra(Index!ut!f1oundsEx$eption:
It is t#e +#ild +lass of R(nti"e<E+eption and #en+e it is (n+#e+?ed. Raised a(to"ati+ally
by t#e *% w#enever we are tryin! to a++ess array ele"ent wit# o(t of ran!e indeE.
Example:
+lass Test7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
intD> E8new intD1)>9
Cyste".o(t.printlnBED)>/9JJvalid
Cyste".o(t.printlnBED1))>/9JJAIII6<
Cyste".o(t.printlnBED41))>/9JJAIII6<
=
=
2; /ull3ointerEx$eption:
It is t#e +#ild +lass of R(nti"e<E+eption and #en+e it is (n+#e+?ed. Raised a(to"ati+ally
by t#e *%- w#enever we are tryin! to +all any "et#od on n(ll.
Example:
+lass Test7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Ctrin! s8n(ll9
Cyste".o(t.printlnBs.len!t#B//9R.<. :(ll\ointer<E+eption
=
=
3; 2ta$+!verFlo%Error:
It is t#e +#ild +lass of <rror and #en+e it is (n+#e+?ed. @#enever we are tryin! to invo?e
re+(rsive "et#od +all *% will raise Cta+?IverHloe<rror a(to"ati+ally.
Example:
+lass Test
7
p(bli+ stati+ void "et#odIneB/
7
"et#odTwoB/9
=
p(bli+ stati+ void "et#odTwoB/
7
"et#odIneB/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7

167

"et#odIneB/9
=
=
!utput:
R(n ti"e error. Cta+?IverHloe<rror
4; /o*lass'efFound:
It is t#e +#ild +lass of <rror and #en+e it is (n+#e+?ed. *% will raise t#is error
a(to"ati+ally w#enever it is (nable to find reV(ired .+lass file.
Example: ,ava Test
If Test.+lass is not available. T#en we will !et :o'lassDefHo(nd error.
5/ *lass*astEx$eption:
It is t#e +#ild +lass of R(nti"e<E+eption and #en+e it is (n+#e+?ed. Raised a(to"ati+ally
by t#e *% w#enever we are tryin! to type+ast parent ob,e+t to +#ild type.
Example:

6; Ex$eptionInInitiali4erError:
It is t#e +#ild +lass of <rror and it is (n+#e+?ed. Raised a(to"ati+ally by t#e *%- if any
eE+eption o++(rs w#ile perfor"in! stati+ variable initiali0ation and stati+ blo+?
eEe+(tion.
Example 1:
+lass Test7
stati+ int i81)J)9
=
!utput:
R(nti"e eE+eption.
<E+eption in t#read N"ainN ,ava.lan!.<E+eptionInInitiali0er<rror
Example 2:
+lass Test7
stati+ 7
Ctrin! s8n(ll9
Cyste".o(t.printlnBs.len!t#B//9
==


16$

!utput:
R(nti"e eE+eption. <E+eption in t#read N"ainN ,ava.lan!.<E+eptionInInitiali0er<rror
; Illegal7rgumentEx$eption:
It is t#e +#ild +lass of R(nti"e<E+eption and #en+e it is (n+#e+?ed. Raised eEpli+itly by
t#e pro!ra""er Bor/ by t#e A\I developer to indi+ate t#at a "et#od #as been invo?ed
wit# inappropriate ar!("ent.
Example:
+lass Test7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
T#read t8new T#readB/9
t.set\riorityB1)/9valid
t.set\riorityB1))/9invalid
==
!utput:
R(nti"e eE+eption
<E+eption in t#read N"ainN ,ava.lan!.Ille!alAr!("ent<E+eption.
B; /um,erFormatEx$eption:
It is t#e +#ild +lass of Ille!alAr!("ent<E+eption and #en+e is (n+#e+?ed. Raised eEpli+itly
by t#e pro!ra""er or by t#e A\I developer to indi+ate t#at we are atte"ptin! to
+onvert strin! to t#e n("ber. 6(t t#e strin! is not properly for"atted.
Example:
+lass Test7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
int i8Inte!er.parseIntBN1)N/9
int ,8Inte!er.parseIntBNtenN/9
==
!utput:
R(nti"e <E+eption
<E+eption in t#read N"ainN ,ava.lan!.:("berHor"at<E+eption. Hor inp(t strin!. NtenN
&/ Illegal2tateEx$eption:
It is t#e +#ild +lass of R(nti"e<E+eption and #en+e it is (n+#e+?ed. Raised eEpli+itly by
t#e pro!ra""er or by t#e A\I developer to indi+ate t#at a "et#od #as been invo?ed at
inappropriate ti"e.
Example:
In+e session eEpires we +anAt +all any "et#od on t#e session ob,e+t ot#erwise we will
!et Ille!alCtate<E+eption
SttpCession session8reV.!etCessionB/9
Cyste".o(t.printlnBsession.!etIdB//9

16&

session.invalidateB/9
Cyste".o(t.printlnBsession.!etIdB//9ill!alstate<E+eption
1)/ 7ssertionError:
It is t#e +#ild +lass of <rror and #en+e it is (n+#e+?ed. Raised eEpli+itly by t#e
pro!ra""er or by A\I developer to indi+ate t#at Assert state"ent fails.
Example:
assertBfalse/9
Ex$eptionWError Raised ,(
1/ AIII6<
2/ :\<B:(ll\ointer<E+eption/
3/ Cta+?IverHlow<rror
4/ :o'lassDefHo(nd<rror
5/ ''<B'lass'ast<E+eption/
6/ <E+eptionInInitiali0er<rror
7/ IA<BIlle!alAr!("ent<E+eption/
$/ :H<B:("berHor"at<E+eption/
&/ IC<BIlle!alCtate<E+eption/
1)/ A<BAssertion<rror/



Raised a(to"ati+ally by *%B*% <E+eptions/




Raised eEpli+itly eit#er by pro!ra""er or by
A\I developer B\ro!ra"ati+ <E+eptions/.










17)

!!32
1/ Data Sidin!
2/ Abstra+tion
3/ <n+aps(lation
4/ Ti!#tly <n+aps(lated 'lass
5/ IC4A Relations#ip
6/ SAC4A Relations#ip
7/ %et#od Ci!nat(re
$/ Iverloadin!
&/ Iverridin!
1)/ %et#od Sidin!
11/ Ctati+ 'ontrol Hlow
12/ Instan+e 'ontrol Hlow
13/ 'onstr(+tors
14/ 'o(plin!
15/ 'o#esion
16/ Ib,e+t Type 'astin!
'ata 6iding:
I(r internal data s#o(ld not !o o(t dire+tly t#at is o(tside person +anAt a++ess o(r
internal data dire+tly.
6y (sin! private "odifier we +an i"ple"ent data #idin!.
Example:
+lass A++o(nt
7
private do(ble balan+e9
......................9
......................9
=
T#e "ain advanta!e of data #idin! is se+(rity.
/ote: re+o""ended "odifier for data "e"bers is private.
7,stra$tion:
Side internal i"ple"entation and ,(st #i!#li!#t t#e set of servi+es- is +alled abstra+tion.
6y (sin! abstra+t +lasses and interfa+es we +an i"ple"ent abstra+tion.
Example:
6y (sin! AT% ^;I s+reen ban? people are #i!#li!#tin! t#e set of servi+es w#at t#ey are
offerin! wit#o(t #i!#li!#tin! internal i"ple"entation.
T#e "ain advanta!es of Abstra+tion are.

171

1/ @e +an a+#ieve se+(rity as we are not #i!#li!#tin! o(r internal i"ple"entation.
2/ <n#an+e"ent will be+o"e very easy be+a(se wit#o(t effe+tin! end (ser we +an able to
perfor" any type of +#an!es in o(r internal syste".
3/ It provides "ore fleEibility to t#e end (ser to (se syste" very easily.
4/ It i"proves "aintainability of t#e appli+ation.
En$apsulation:
It is t#e pro+ess of <n+aps(latin! data and +orrespondin! "et#ods into a sin!le "od(le.
If any ,ava +lass follows data #idin! and abstra+tion s(+# type of +lass is said to be
en+aps(lated +lass.
En$apsulationM'ata#iding?7,stra$tion
Example:

In en+aps(lated +lass we #ave to "aintain !etter and setter "et#ods for every data
"e"ber.
T#e "ain advanta!es of en+aps(lation are.
1/ @e +an a+#ieve se+(rity.
2/ <n#an+e"ent will be+o"e very easy.
3/ It i"proves "aintainability of t#e appli+ation.
4/ It provides fleEibility to t#e (ser to (se syste" very easily.
T#e "ain disadvanta!e of en+aps(lation is it in+reases len!t# of t#e +ode and slows
down eEe+(tion.
8ig#tl( en$apsulated $lass:
A +lass is said to be ti!#tly en+aps(lated if and only if every variable of t#at +lass
de+lared as private w#et#er t#e variable #as !etter and setter "et#ods are not and
w#et#er t#ese "et#ods de+lared as p(bli+ or not- not reV(ired to +#e+?.
Example:
+lass A++o(nt
7

172

private do(ble balan+e9
p(bli+ do(ble !et6alan+eB/
7
ret(rn balan+e9
=
=
"#i$# of t#e follo%ing $lasses are tig#tl( en$apsulated&

"#i$# of t#e follo%ing $lasses are tig#tl( en$apsulated&
+lass A
7
int E81)9
=
+lass 6 eEtends A
7
private int y82)9
=
+lass ' eEtends 6
7
private int 083)9
=
/ote: if t#e parent +lass is not ti!#tly en+aps(lated t#en no +#ild +lass is ti!#tly en+aps(lated.
I2<7 Relations#ip:in#eritan$e;:
1/ Also ?nown as in#eritan+e.
2/ 6y (sin! eEtends ?eywords we +an i"ple"ent IC4A relations#ip.
3/ T#e "ain advanta!e of IC4A relations#ip is re(sability.
Example:
+lass \arent
7
p(bli+ void "et#odIneB/

173

7=
=
+lass '#ild eEtends \arent
7
p(bli+ void "et#odTwoB/
7=
=

*on$lusion:
1/ @#atever t#e parent #as by defa(lt available to t#e +#ild b(t w#atever t#e +#ild #as by
defa(lt not available to t#e parent. Sen+e on t#e +#ild referen+e we +an +all bot# parent
and +#ild +lass "et#ods. 6(t on t#e parent referen+e we +an +all only "et#ods available
in t#e parent +lass and we +anAt +all +#ild spe+ifi+ "et#ods.
2/ \arent +lass referen+e +an be (sed to #old +#ild +lass ob,e+t b(t by (sin! t#at referen+e
we +an +all only "et#ods available in parent +lass and +#ild spe+ifi+ "et#ods we +anAt
+all.
3/ '#ild +lass referen+e +annot be (sed to #old parent +lass ob,e+t.
Example:
T#e +o""on "et#ods w#i+# are reV(ired for #o(sin! loan- ve#i+le loan- personal loan
and ed(+ation loan we +an define into a separate +lass in parent +lass loan. Co t#at
a(to"ati+ally t#ese "et#ods are available to every +#ild loan +lass.
Example:
+lass Loan
7
JJ+o""on "et#ods w#i+# are reV(ired for any type of loan.
=
+lass So(sin!Loan eEtends Loan

174

7
JJSo(sin! loan spe+ifi+ "et#ods.
=
+lass <d(+ationLoan eEtends Loan
7
JJ<d(+ation Loan spe+ifi+ "et#ods.
=
Hor all ,ava +lasses t#e "ost +o""only reV(ired f(n+tionality is define inside ob,e+t
+lass #en+e ob,e+t +lass a+ts as a root for all ,ava +lasses.
Hor all ,ava eE+eptions and errors t#e "ost +o""on reV(ired f(n+tionality defines
inside T#rowable +lass #en+e T#rowable +lass a+ts as a root for eE+eption #ierar+#y.
'iagram:

=ultiple in#eritan$e:
Savin! "ore t#an one \arent +lass at t#e sa"e level is +alled "(ltiple in#eritan+e.
Example:

Any +lass +an eEtends only one +lass at a ti"e and +anAt eEtends "ore t#an one +lass
si"(ltaneo(sly #en+e ,ava wonAt provide s(pport for "(ltiple in#eritan+e.
Example:

6(t an interfa+e +an eEtends any no. If interfa+es at a ti"e #en+e ,ava provides s(pport
for "(ltiple in#eritan+e t#ro(!# interfa+es.


175

Example:

If o(r +lass doesnAt eEtends any ot#er +lass t#en only o(r +lass is t#e dire+t +#ild +lass of
ob,e+t.
Example:

If o(r +lass eEtends any ot#er +lass t#en o(r +lass is not dire+t +#ild +lass of ob,e+t.
Example 1:

Example 2:

"#( java %onIt provide support for multiple in#eritan$e&
T#ere "ay be a +#an+e of raisin! a"bi!(ity proble"s.
Example:

"#( am,iguit( pro,lem %onIt ,e t#ere in interfa$es&
Interfa+es #avin! d(""y de+larations and t#ey wonAt #ave i"ple"entations #en+e no
a"bi!(ity proble".
Example:

176


*($li$ in#eritan$e:
'y+li+ in#eritan+e is not allowed in ,ava.
Example 1:

Example 2:

672<7 relations#ip:
1/ SAC4A relations#ip is also ?nown as +o"position Bor/ a!!re!ation.
2/ T#ere is no spe+ifi+ ?eyword to i"ple"ent #AC4A relations#ip b(t "ostly we +an (se
new operator.
3/ T#e "ain advanta!e of SAC4A relations#ip is re(sability.
Example:
+lass <n!ine
7
JJen!ine spe+ifi+ f(n+tionality
=
+lass 'ar
7
<n!ine e8new <n!ineB/9
JJ........................9
JJ........................9
JJ........................9
=

177

'lass 'ar SAC4A en!ine referen+e.
SAC4A relations#ip in+reases dependen+y between t#e +o"ponents and +reates
"aintains proble"s.
*omposition vs 7ggregation:
*omposition:
@it#o(t eEistin! +ontainer ob,e+t if t#ere is no +#an+e of eEistin! +ontained ob,e+ts t#en
t#e relations#ip between +ontainer ob,e+t and +ontained ob,e+t is +alled +o"position
w#i+# is a stron! asso+iation.
Example:
;niversity +onsists of several depart"ents w#enever (niversity ob,e+t destroys
a(to"ati+ally all t#e depart"ent ob,e+ts will be destroyed t#at is wit#o(t eEistin!
(niversity ob,e+t t#ere is no +#an+e of eEistin! dependent ob,e+t #en+e t#ese are
stron!ly asso+iated and t#is relations#ip is +alled +o"position.
Example:

7ggregation:
@it#o(t eEistin! +ontainer ob,e+t if t#ere is a +#an+e of eEistin! +ontained ob,e+ts s(+#
type of relations#ip is +alled a!!re!ation. In a!!re!ation ob,e+ts #ave wea? asso+iation.
Example:
@it#in a depart"ent t#ere "ay be a +#an+e of several professors will wor? w#enever
we are +losin! depart"ent still t#ere "ay be a +#an+e of eEistin! professor ob,e+t
wit#o(t eEistin! depart"ent ob,e+t t#e relations#ip between depart"ent and professor
is +alled a!!re!ation w#ere t#e ob,e+ts #avin! wea? asso+iation.
Example:


17$

=et#od signature: In ,ava "et#od si!nat(re +onsists of na"e of t#e "et#od followed by
ar!("ent types.
Example:

In ,ava ret(rn type is not part of t#e "et#od si!nat(re.
'o"piler will (se "et#od si!nat(re w#ile resolvin! "et#od +alls.
@it#in t#e sa"e +lass we +anAt ta?e 2 "et#ods wit# t#e sa"e si!nat(re ot#erwise we
will !et +o"pile ti"e error.
Example:
p(bli+ void "et#odIneB/
7=
p(bli+ int "et#odIneB/
7
ret(rn 1)9
=
!utput:
'o"pile ti"e error
"et#odIneB/ is already defined in Test
!verloading:
Two "et#ods are said to be overload if and only if bot# #avin! t#e sa"e na"e b(t
different ar!("ent types.
In X'A lan!(a!e we +anAt ta?e 2 "et#ods wit# t#e sa"e na"e and different types. If
t#ere is a +#an!e in ar!("ent type +o"p(lsory we s#o(ld !o for new "et#od na"e.
Example:

La+? of overloadin! in K'L in+reases +o"pleEity of t#e pro!ra""in!.
6(t in ,ava we +an ta?e "(ltiple "et#ods wit# t#e sa"e na"e and different ar!("ent
types.




17&

Example:

Savin! t#e sa"e na"e and different ar!("ent types is +alled "et#od overloadin!.
All t#ese "et#ods are +onsidered as overloaded "et#ods.
Savin! overloadin! +on+ept in ,ava red(+es +o"pleEity of t#e pro!ra""in!.
Example:
+lass Test
7
p(bli+ void "et#odIneB/
7
Cyste".o(t.printlnBNno4ar! "et#odN/9
=
p(bli+ void "et#odIneBint i/
7
Cyste".o(t.printlnBNint4ar! "et#odN/9 overloaded met#ods
=
p(bli+ void "et#odIneBdo(ble d/
7
Cyste".o(t.printlnBNdo(ble4ar! "et#odN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t8new TestB/9
t."et#odIneB/9JJno4ar! "et#od
t."et#odIneB1)/9JJint4ar! "et#od
t."et#odIneB1).5/9JJdo(ble4ar! "et#od
=
=
In overloadin! +o"piler is responsible to perfor" "et#od resol(tionBde+ision/ based on
t#e referen+e type. Sen+e overloadin! is also +onsidered as +o"pile ti"e
poly"orp#is"Bor/ stati+ B/early bidin!.
*ase 1: 7utomati$ promotion in overloading9
In overloadin! if +o"piler is (nable to find t#e "et#od wit# eEa+t "at+# we wonAt !et
any +o"pile ti"e error i""ediately.

1$)

1
st
+o"piler pro"otes t#e ar!("ent to t#e neEt level and +#e+?s w#et#er t#e "at+#ed
"et#od is available or not if it is available t#en t#at "et#od will be +onsidered if it is not
available t#en +o"piler pro"otes t#e ar!("ent on+e a!ain to t#e neEt level. T#is
pro+ess will be +ontin(ed (ntil all possible pro"otions still if t#e "at+#ed "et#od is not
available t#en we will !et +o"pile ti"e error. T#is pro+ess is +alled a(to"ati+ pro"otion
in overloadin!.
T#e followin! are vario(s possible a(to"ati+ pro"otions in overloadin!.
'iagram:

Example:
+lass Test
7
p(bli+ void "et#odIneBint i/
7
Cyste".o(t.printlnBNint4ar! "et#odN/9
=
p(bli+ void "et#odIneBfloat f/ overloaded met#ods
7
Cyste".o(t.printlnBNfloat4ar! "et#odN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t8new TestB/9
JJt."et#odIneBQaQ/9JJint4ar! "et#od
JJt."et#odIneB1)l/9JJfloat4ar! "et#od
t."et#odIneB1).5/9JJ'.<.+annot find sy"bol
=
=
*ase 2:
+lass Test
7
p(bli+ void "et#odIneBCtrin! s/
7
Cyste".o(t.printlnBNCtrin! versionN/9
=
p(bli+ void "et#odIneBIb,e+t o/ 1ot# met#ods are said to

1$1

,e overloaded met#ods9
7
Cyste".o(t.printlnBNIb,e+t versionN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t8new TestB/9
t."et#odIneBNb#as?arN/9JJCtrin! version
t."et#odIneBnew Ib,e+tB//9JJIb,e+t version
t."et#odIneBn(ll/9JJCtrin! version
=
=
In overloadin! '#ild will always !et #i!# priority t#en \arent.
*ase 3:
+lass Test
7
p(bli+ void "et#odIneBCtrin! s/
7
Cyste".o(t.printlnBNCtrin! versionN/9
=
p(bli+ void "et#odIneBCtrin!6(ffer s/
7
Cyste".o(t.printlnBNCtrin!6(ffer versionN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t8new TestB/9
t."et#odIneBNd(r!aN/9JJCtrin! version
t."et#odIneBnew Ctrin!6(fferBNb#as?arN//9JJCtrin!6(ffer version
=
=
!utput:




1$2

*ase 4:
+lass Test
7
p(bli+ void "et#odIneBint i-float f/
7
Cyste".o(t.printlnBNint4float "et#odN/9
=
p(bli+ void "et#odIneBfloat f-int i/
7
Cyste".o(t.printlnBNfloat4int "et#odN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t8new TestB/9
t."et#odIneB1)-1).5f/9JJint4float "et#od
t."et#odIneB1).5f-1)/9JJfloat4int "et#od
t."et#odIneB1)-1)/9JJ'.<.referen+e to "et#odIne is a"bi!(o(s- bot# "et#od
"et#odIneBint-float/ in Test and "et#od "et#odIneBfloat-int/ in Test "at+#
t."et#odIneB1).5f-1).5f/9JJ'.<.+annot find sy"bol
=
=
*ase 5:
+lass Test
7
p(bli+ void "et#odIneBint i/
7
Cyste".o(t.printlnBN!eneral "et#odN/9
=
p(bli+ void "et#odIneBint...i/
7
Cyste".o(t.printlnBNvar4ar! "et#odN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t8new TestB/9
t."et#odIneB/9JJvar4ar! "et#od
t."et#odIneB1)-2)/9JJvar4ar! "et#od
t."et#odIneB1)/9JJ!eneral "et#od

1$3

=
=
In !eneral var4ar! "et#od will !et less priority t#at is if no ot#er "et#od "at+#ed t#en
only var4ar! "et#od will !et +#an+e for eEe+(tion it is al"ost sa"e as defa(lt +ase
inside swit+#.
*ase 6:
+lass Ani"al7=
+lass %on?ey eEtends Ani"al7=
+lass Test
7
p(bli+ void "et#odIneBAni"al a/
7
Cyste".o(t.printlnBNAni"al versionN/9
=
p(bli+ void "et#odIneB%on?ey "/
7
Cyste".o(t.printlnBN%on?ey versionN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t8new TestB/9
Ani"al a8new Ani"alB/9
t."et#odIneBa/9JJAni"al version
%on?ey "8new %on?eyB/9
t."et#odIneB"/9JJ%on?ey version
Ani"al a18new %on?eyB/9
t."et#odIneBa1/9JJAni"al version
=
=
In overloadin! "et#od resol(tion is always based on referen+e type and r(nti"e ob,e+t
wonAt play any role in overloadin!.
!verriding:
@#atever t#e \arent #as by defa(lt available to t#e '#ild t#ro(!# in#eritan+e- if t#e
'#ild is not satisfied wit# \arent +lass "et#od i"ple"entation t#en '#ild is allow to
redefine t#at \arent +lass "et#od in '#ild +lass in its own way t#is pro+ess is +alled
overridin!.
T#e \arent +lass "et#od w#i+# is overridden is +alled overridden "et#od.
T#e '#ild +lass "et#od w#i+# is overridin! is +alled overridin! "et#od.

1$4

Example 1:
+lass \arent
7
p(bli+ void propertyB/
7
Cyste".o(t.printlnBN+as#FlandF!oldN/9
=
p(bli+ void "arryB/
7
Cyste".o(t.printlnBNs(bbala?s#"iN/9 overridden met#od
=
=
+lass '#ild eEtends \arent overriding
7
p(bli+ void "arryB/
7
Cyste".o(t.printlnBNTris#aJnayanataraJan(s#?aN/9 overriding met#od
=
=
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\arent p8new \arentB/9
p."arryB/9JJs(bbala?s#"iBparent "et#od/
'#ild +8new '#ildB/9
+."arryB/9JJTris#aJnayanataraJan(s#?aB+#ild "et#od/
\arent p18new '#ildB/9
p1."arryB/9JJTris#aJnayanataraJan(s#?aB+#ild "et#od/
=
=
In overridin! "et#od resol(tion is always ta?es +are by *% based on r(nti"e ob,e+t
#en+e overridin! is also +onsidered as r(nti"e poly"orp#is" or dyna"i+ poly"orp#is"
or late bindin!.
T#e pro+ess of overridin! "et#od resol(tion is also ?nown as dyna"i+ "et#od dispat+#.
/ote: In overridin! r(nti"e ob,e+t will play t#e role and referen+e type is d(""y.



1$5

Rules for overriding:
In overridin! "et#od na"es and ar!("ents "(st be sa"e. T#at is "et#od si!nat(re
"(st be sa"e.
;ntil 1.4 version t#e ret(rn types "(st be sa"e b(t fro" 1.5 version onwards +o4variant
ret(rn types are allowed.
A++ordin! to t#is '#ild +lass "et#od ret(rn type need not be sa"e as \arent +lass
"et#od ret(rn type its '#ild types also allowed.
Example:
+lass \arent
7
p(bli+ Ib,e+t "et#odIneB/
7
ret(rn n(ll9
=
=
+lass '#ild eEtends \arent
7
p(bli+ Ctrin! "et#odIneB/
7
ret(rn n(ll9
=
=
It is valid in K1.5L b(t invalid in K1.4L.
'iagram:

'o4variant ret(rn type +on+ept is appli+able only for ob,e+t types b(t not for pri"itives.
\rivate "et#ods are not visible in t#e '#ild +lasses #en+e overridin! +on+ept is not
appli+able for private "et#ods. 6ased on own reV(ire"ent we +an de+lare t#e sa"e
\arent +lass private "et#od in +#ild +lass also. It is valid b(t not overridin!.





1$6

Example:

\arent +lass final "et#ods we +anAt override in t#e '#ild +lass.
Example:
+lass \arent
7
p(bli+ final void "et#odIneB/
7=
=
+lass '#ild eEtends \arent
7
p(bli+ void "et#odIneB/
7=
=
!utput:
'o"pile ti"e error.
'#ild.,ava.$. "et#odIneB/ in '#ild +annot override "et#odIneB/ in \arent9 overridden "et#od
is final
\arent +lass non final "et#ods we +an override as final in +#ild +lass. @e +an override
native "et#ods in t#e +#ild +lasses.
@e s#o(ld override \arent +lass abstra+t "et#ods in '#ild +lasses to provide
i"ple"entation.
Example:
abstra+t +lass \arent
7
p(bli+ abstra+t void "et#odIneB/9
=
+lass '#ild eEtends \arent
7
p(bli+ void "et#odIneB/
7=

1$7

=
'iagram:

@e +an override \arent +lass non abstra+t "et#od as abstra+t to stop availability of
\arent +lass "et#od i"ple"entation to t#e '#ild +lasses.
Example:
+lass \arent
7
p(bli+ void "et#odIneB/
7=
=
abstra+t +lass '#ild eEtends \arent
7
p(bli+ abstra+t void "et#odIneB/9
=
Cyn+#roni0ed- stri+tfp- "odifiers wonAt ?eep any restri+tions on overridin!.
'iagram:

@#ile overridin! we +anAt red(+e t#e s+ope of a++ess "odifier.
Example:
+lass \arent
7
p(bli+ void "et#odIneB/
7=
=
+lass '#ild eEtends \arent
7
prote+ted void "et#odIneB/
7=
=


1$$

!utput:
'o"pile ti"e error
"et#odIneB/ in '#ild +annot override "et#odIneB/ in \arent9 atte"ptin! to assi!n wea?er
a++ess privile!es9 was p(bli+
'iagram:

*#e$+ed -s .n<$#e$+ed Ex$eptions:
T#e eE+eptions w#i+# are +#e+?ed by t#e +o"piler for s"oot# eEe+(tion of t#e pro!ra"
at r(nti"e are +alled +#e+?ed eE+eptions.
T#e eE+eptions w#i+# are not +#e+?ed by t#e +o"piler are +alled (n4+#e+?ed
eE+eptions.
R(nti"e<E+eption and its +#ild +lasses- <rror and its +#ild +lasses are (n+#e+?ed eE+ept
t#ese t#e re"ainin! are +#e+?ed eE+eptions.
'iagram:

Rule: "#ile overriding if t#e $#ild $lass met#od t#ro%s an( $#e$+ed ex$eption $ompulsor(
t#e parent $lass met#od s#ould t#ro% t#e same $#e$+ed ex$eption or its parent ot#er%ise
%e %ill get $ompile time error9

1$&

6(t t#ere are no restri+tions for (n4+#e+?ed eE+eptions.
Example:
+lass \arent
7
p(bli+ void "et#odIneB/
7=
=
+lass '#ild eEtends \arent
7
p(bli+ void "et#odIneB/t#rows <E+eption
7=
=
!utput:
'o"pile ti"e error
"et#odIneB/ in '#ild +annot override "et#odIneB/ in \arent9 overridden "et#od does not
t#row ,ava.lan!.<E+eption
Examples:
!verriding %it# respe$t to stati$ met#ods:
*ase 1:
@e +anAt override a stati+ "et#od as non stati+.

1&)

Example:
+lass \arent
7
p(bli+ stati+ void "et#odIneB/JJ#ere stati$ met#od!ne:; met#od is a $lass level
7=
=
+lass '#ild eEtends \arent
7
p(bli+ void "et#odIneB/JJ#ere met#od!ne:; met#od is a o,je$t level #en$e %e $anIt
override met#od!ne:; met#od
7=
=
*ase 2:
Ci"ilarly we +anAt override a non stati+ "et#od as stati+.
*ase 3:
+lass \arent
7
p(bli+ stati+ void "et#odIneB/
7=
=
+lass '#ild eEtends \arent
7
p(bli+ stati+ void "et#odIneB/
7=
=
It is valid. It see"s to be overridin! +on+ept is appli+able for stati+ "et#ods b(t it is not
overridin! it is "et1#od #idin!.
=E86!' 6I'I/G
All r(les of "et#od #idin! are eEa+tly sa"e as overridin! eE+ept t#e followin!
differen+es.
!verriding =et#od #iding
1. 6ot# \arent and '#ild +lass "et#ods s#o(ld
be non stati+.
1. 6ot# \arent and '#ild +lass "et#ods s#o(ld
be stati+.
2. %et#od resol(tion is always ta?es +are by
*% based on r(nti"e ob,e+t.
2. %et#od resol(tion is always ta?es +are by
+o"piler based on referen+e type.
3. Iverridin! is also +onsidered as r(nti"e
poly"orp#is" Bor/ dyna"i+ poly"orp#is"
Bor/ late bindin!.
3. %et#od #idin! is also +onsidered as +o"pile
ti"e poly"orp#is" Bor/ stati+ poly"orp#is"
Bor/ early bidin!.


1&1

Example:
+lass \arent
7
p(bli+ stati+ void "et#odIneB/
7
Cyste".o(t.printlnBNparent +lassN/9
=
=
+lass '#ild eEtends \arent
7
p(bli+ stati+ void "et#odIneB/
7
Cyste".o(t.printlnBN+#ild +lassN/9
=
=
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\arent p8new \arentB/9
p."et#odIneB/9JJparent +lass
'#ild +8new '#ildB/9
+."et#odIneB/9JJ+#ild +lass
\arent p18new '#ildB/9
p1."et#odIneB/9JJparent +lass
=
=
/ote: If bot# \arent and '#ild +lass "et#ods are non stati+ t#en it will be+o"e overridin! and
"et#od resol(tion is based on r(nti"e ob,e+t. In t#is +ase t#e o(tp(t is
\arent +lass
'#ild +lass
'#ild +lass
!verriding %it# respe$t to -ar arg met#ods:
A var ar! "et#od s#o(ld be overridden wit# var4ar! "et#od only. If we are tryin! to
override wit# nor"al "et#od t#en it will be+o"e overloadin! b(t not overridin!.
Example:
+lass \arent
7

1&2

p(bli+ void "et#odIneBint... i/
7
Cyste".o(t.printlnBNparent +lassN/9
=
=
+lass '#ild eEtends \arent overloading ,ut not overriding9
7
p(bli+ void "et#odIneBint i/
7
Cyste".o(t.printlnBN+#ild +lassN/9
=
=
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\arent p8new \arentB/9
p."et#odIneB1)/9JJparent +lass
'#ild +8new '#ildB/9
+."et#odIneB1)/9JJ+#ild +lass
\arent p18new '#ildB/9
p1."et#odIneB1)/9JJparent +lass
=
=
In t#e above pro!ra" if we repla+e +#ild +lass "et#od wit# var ar! t#en it will be+o"e
overridin!. In t#is +ase t#e o(tp(t is
\arent +lass
'#ild +lass
'#ild +lass
!verriding %it# respe$t to varia,les:
Iverridin! +on+ept is not appli+able for variables.
ariable resol(tion is always ta?es +are by +o"piler based on referen+e type.
Example:
+lass \arent
7
int E8$$$9
=
+lass '#ild eEtends \arent

1&3

7
int E8&&&9
=
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\arent p8new \arentB/9
Cyste".o(t.printlnBp.E/9JJ$$$
'#ild +8new '#ildB/9
Cyste".o(t.printlnB+.E/9JJ&&&
\arent p18new '#ildB/9
Cyste".o(t.printlnBp1.E/9JJ$$$
=
=
/ote: In t#e above pro!ra" \arent and '#ild +lass variables- w#et#er bot# are stati+ or non
stati+ w#et#er one is stati+ and t#e ot#er one is non stati+ t#ere is no +#an!e in t#e answer.
'ifferen$es ,et%een overloading and overriding&
3ropert( !verloading !verriding
1/ %et#od na"es 1/ %(st be sa"e. 1/ %(st be sa"e.
2/ Ar!("ent type 2/ %(st be differentBat
least order/
2/ %(st be sa"e in+l(din!
order.
3/ %et#od si!nat(re 3/ %(st be different. 3/ %(st be sa"e.
4/ Ret(rn types 4/ :o restri+tions. 4/ %(st be sa"e (ntil 1.4v
b(t fro" 1.5v onwards we
+an ta?e +o4variant ret(rn
types also.
5/ private-stati+-final
"et#ods
5/ 'an be overloaded. 5/ 'an not be overridden.
6/ A++ess "odifiers 6/ :o restri+tions. 6/ @ea?erin!Jred(+in! is not
allowed.
7/ T#rows +la(se 7/ :o restri+tions. 7/ If +#ild +lass "et#od
t#rows any +#e+?ed
eE+eption +o"p(lsory
parent +lass "et#od
s#o(ld t#row t#e sa"e
+#e+?ed eE+eptions or its
parent b(t no restri+tions
for (n4+#e+?ed eE+eptions.
$/ %et#od resol(tion $/ Is always ta?es +are
by +o"piler based
$/ Is always ta?es +are by
*% based on r(nti"e

1&4

on referen+ed type.

ob,e+t.
&/ Also ?nown as &/ 'o"pile ti"e
poly"orp#is" Bor/
stati+Bor/early
bindin!.
&/ R(nti"e poly"orp#is"
Bor/ dyna"i+ Bor/ late
bindin!.
/ote:
1/ In overloadin! we #ave to +#e+? only "et#od na"es B"(st be sa"e/ and ar!("ents
B"(st be different/ t#e re"ainin! t#in!s li?e ret(rn type eEtra not reV(ired to +#e+?.
2/ 6(t In overridin! we s#o(ld +o"p(lsory +#e+? everyt#in! li?e "et#od na"es-
ar!("ents- ret(rn types- t#rows ?eyword- "odifiers et+.
*onsider t#e met#od in parent $lass
3arent: pu,li$ void met#od!ne:int i;t#ro%s I!Ex$eption
In t#e +#ild +lass w#i+# of t#e followin! "et#ods we +an ta?e.
1/ p(bli+ void "et#odIneBint i/JJvalidBoverridin!/
2/ private void "et#odIneB/t#rows <E+eptionJJvalidBoverloadin!/
3/ p(bli+ native void "et#odIneBint i/9JJvalidBoverridin!/
4/ p(bli+ stati+ void "et#odIneBdo(ble d/JJvalidBoverloadin!/
5/ p(bli+ stati+ void "et#odIneBint i/
*ompile time error
1/ "et#odIneBint/ in '#ild +annot override "et#odIneBint/ in \arent9 overridin! "et#od
is stati+
6/ p(bli+ stati+ abstra+t void "et#odIneBfloat f/
*ompile time error
1/ ille!al +o"bination of "odifiers. abstra+t and stati+
2/ '#ild is not abstra+t and does not override abstra+t "et#od "et#odIneBfloat/ in '#ild
3ol(morp#ism: Ca"e na"e wit# different for"s is t#e +on+ept of poly"orp#is".
Example 1: @e +an (se sa"e absB/ "et#od for int type- lon! type- float type et+.
Example:
1/ absBint/
2/ absBlon!/
3/ absBfloat/
Example 2: @e +an (se t#e sa"e List referen+e to #old ArrayList ob,e+t- Lin?edList ob,e+t-
e+tor ob,e+t- or Cta+? ob,e+t.
Example:
1/ List l8new ArrayListB/9
2/ List l8new Lin?edListB/9
3/ List l8new e+torB/9
4/ List l8new Cta+?B/9

1&5

'iagram:

'iagram:

1/ In#eritan+e tal?s abo(t re(sability.
2/ \oly"orp#is" tal?s abo(t fleEibility.
3/ <n+aps(lation tal?s abo(t se+(rity.
1eautiful definition of pol(morp#ism:
A boy starts love wit# t#e word friends#ip- b(t !irl ends love wit# t#e sa"e word
friends#ip- word is t#e sa"e b(t wit# different attit(des. T#is +on+ept is not#in! b(t
poly"orp#is".
*onstru$tors
Ib,e+t +reation is not eno(!# +o"p(lsory we s#o(ld perfor" initiali0ation t#en only t#e
ob,e+t is in a position to provide t#e response properly.
@#enever we are +reatin! an ob,e+t so"e pie+e of t#e +ode will be eEe+(ted
a(to"ati+ally to perfor" initiali0ation of an ob,e+t t#is pie+e of t#e +ode is not#in! b(t
+onstr(+tor.
Sen+e t#e "ain ob,e+tive of +onstr(+tor is to perfor" initiali0ation of an ob,e+t.
Example:
+lass Ct(dent
7
Ctrin! na"e9
int rollno9
Ct(dentBCtrin! na"e-int rollno/
7
t#is.na"e8na"e9 *onstru$tor

1&6

t#is.rollno8rollno9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ct(dent s18new Ct(dentBNvi,ayab#as?arN-1)1/9
Ct(dent s28new Ct(dentBNb#as?arN-1)2/9
=
=
'iagram:

*onstru$tor -s instan$e ,lo$+:
6ot# instan+e blo+? and +onstr(+tor will be eEe+(ted a(to"ati+ally for every ob,e+t
+reation b(t instan+e blo+? 1
st
followed by +onstr(+tor.
T#e "ain ob,e+tive of +onstr(+tor is to perform initiali4ation of an o,je$t.
It#er t#an initiali0ation if %e %ant to perform an( a$tivit( for ever( o,je$t $reation %e
#ave to define t#at a$tivit( inside instan$e ,lo$+.
6ot# +on+epts #avin! different p(rposes #en+e repla+in! one +on+ept wit# anot#er
+on+ept is not possible.
'onstr(+tor +an ta?e ar!("ents b(t instan+e blo+? +anAt ta?e any ar!("ents #en$e %e
$anIt repla$e $onstru$tor $on$ept %it# instan$e ,lo$+.
Ci"ilarly we +anAt repla+e instan+e blo+? p(rpose wit# +onstr(+tor.
'emo program to tra$+ no of o,je$ts $reated for a $lass:
+lass Test
7
stati+ int +o(nt8)9
7
+o(ntFF9 instan$e ,lo$+
=
TestB/
7=
TestBint i/
7=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t18new TestB/9
Test t28new TestB1)/9

1&7

Test t38new TestB/9
Cyste".o(t.printlnB+o(nt/9JJ3
=
=
Rules to %rite $onstru$tors:
1/ :a"e of t#e +onstr(+tor and na"e of t#e +lass "(st be sa"e.
2/ Ret(rn type +on+ept is not appli+able for +onstr(+tor even void also by "ista?e if we are
de+larin! t#e ret(rn type for t#e +onstr(+tor we wonAt !et any +o"pile ti"e error and
r(nti"e error +o"piler si"ply treats it as a "et#od.
Example:
+lass Test
7
void TestB/ it is not a $onstru$tor and it is a met#od
7=
=
3/ It is le!al Bb(t st(pid/ to #ave a "et#od w#ose na"e is eEa+tly sa"e as +lass na"e.
4/ T#e only appli+able "odifiers for t#e +onstr(+tors are pu,li$H defaultH privateH
prote$ted.
5/ If we are (sin! any ot#er "odifier we will !et +o"pile ti"e error.
Example:
+lass Test
7
stati+ TestB/
7=
=
!utput:
%odifier stati+ not allowed #ere
'efault $onstru$tor:
Hor every +lass in ,ava in+l(din! abstra+t +lasses also +onstr(+tor +on+ept is appli+able.
If we are not writin! at least one +onstr(+tor t#en +o"piler will !enerate defa(lt
+onstr(+tor.
If we are writin! at least one +onstr(+tor t#en +o"piler wonAt !enerate any defa(lt
+onstr(+tor. Sen+e every +lass +ontains eit#er +o"piler !enerated +onstr(+tor Bor/
pro!ra""er written +onstr(+tor b(t not bot# si"(ltaneo(sly.
3rotot(pe of default $onstru$tor:
1/ It is always no ar!("ent +onstr(+tor.
2/ T#e a++ess "odifier of t#e defa(lt +onstr(+tor is sa"e as +lass "odifier. BT#is r(le is
appli+able only for p(bli+ and defa(lt/.

1&$

3/ Defa(lt +onstr(+tor +ontains only one line. super:;E it is a no ar!("ent +all to s(per +lass
+onstr(+tor.
3rogrammers $ode *ompiler generated $ode
+lass Test
7=
+lass Test
7
TestB/
7
s(perB/9
=
=
p(bli+ +lass Test
7=

p(bli+ +lass Test
7
p(bli+ TestB/
7
s(perB/9
=
=
+lass Test
7
void TestB/7=
=

+lass Test
7
TestB/
7
s(perB/9
=
void TestB/
7=
=
+lass Test
7
TestBint i/
7=
=
+lass Test
7
TestBint i/
7
s(perB/9
=
=
+lass Test
7
TestB/
7
s(perB/9
=
=
+lass Test
7
TestB/
7
s(perB/9
=
=
+lass Test
7
TestBint i/
+lass Test
7
TestBint i/

1&&

7
t#isB/9
=
TestB/
7=
=
7
t#isB/9
=
TestB/
7
s(perB/9
=
=
super:; vs t#is:;:
T#e 1
st
line inside every +onstr(+tor s#o(ld be eit#er s(perB/ or t#isB/ if we are not
writin! anyt#in! +o"piler will always !enerate s(perB/.
*ase 1: @e #ave to ta?e s(perB/ Bor/ t#isB/ only in t#e 1
st
line of +onstr(+tor. If we are ta?in!
anyw#ere else we will !et +o"pile ti"e error.
Example:
+lass Test
7
TestB/
7
Cyste".o(t.printlnBN+onstr(+torN/9
s(perB/9
=
=
!utput:
'o"pile ti"e error.
'all to s(per "(st be first state"ent in +onstr(+tor
*ase 2: @e +an (se eit#er s(perB/ Bor/ t#isB/ b(t not bot# si"(ltaneo(sly.
Example:
+lass Test
7
TestB/
7
s(perB/9
t#isB/9
=
=
!utput:
'o"pile ti"e error.
'all to t#is "(st be first state"ent in +onstr(+tor

2))

*ase 3: @e +an (se s(perB/ Bor/ t#isB/ only inside +onstr(+tor. If we are (sin! anyw#ere else we
will !et +o"pile ti"e error.
Example:
+lass Test
7
p(bli+ void "et#odIneB/
7
s(perB/9
=
=
!utput:
'o"pile ti"e error.
'all to s(per "(st be first state"ent in +onstr(+tor
T#at is we +an +all a +onstr(+tor dire+tly fro" anot#er +onstr(+tor only.
'iagram:

Example:
super:;Ht#is:; superH t#is
1. T#ese are +onstr(+tors +alls. 1. T#ese are ?eywords w#i+# +an be (sed to
+all parent +lass and +(rrent +lass instan+e
"e"bers.
2. @e s#o(ld (se only inside +onstr(+tors. 2. @e +an (se anyw#ere eE+ept stati+ area.
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBs(per.#as#'odeB//9
=
=
!utput:
'o"pile ti"e error.
:on4stati+ variable s(per +annot be referen+ed fro" a stati+ +onteEt.



2)1

!verloaded $onstru$tors:
A +lass +an +ontain "ore t#an one +onstr(+tor and all t#ese +onstr(+tors #avin! t#e
sa"e na"e b(t different ar!("ents and #en+e t#ese +onstr(+tors are +onsidered as
overloaded +onstr(+tors.
Example:
+lass Test
7
TestBdo(ble d/
7
t#isB1)/9
Cyste".o(t.printlnBNdo(ble4ar!("ent +onstr(+torN/9
=
TestBint i/
7
t#isB/9
Cyste".o(t.printlnBNint4ar!("ent +onstr(+torN/9
=
TestB/
7
Cyste".o(t.printlnBNno4ar!("ent +onstr(+torN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t18new TestB1).5/9JJno4ar!("ent +onstr(+torJint4ar!("ent
+onstr(+torJdo(ble4ar!("ent +onstr(+tor
Test t28new TestB1)/9JJno4ar!("ent +onstr(+torJint4ar!("ent +onstr(+tor
Test t38new TestB/9JJno4ar!("ent +onstr(+tor
=
=
KIn#eritan+e +on+ept is not appli+able for +onstr(+tors and #en+e overridin! +on+ept
also not appli+able to t#e +onstr(+tors. 6(t +onstr(+tors +an be overloadedL.
@e +an ta?e +onstr(+tor in any ,ava +lass in+l(din! abstra+t +lass also b(t %e $anIt ta+e
$onstru$tor inside in#eritan$e.






2)2

Example:

"e $anIt $reate o,je$t for a,stra$t $lass ,ut a,stra$t $lass $an $ontain $onstru$tor %#at is t#e
need&
Abstra+t +lass +onstr(+tor will be eEe+(ted to perfor" initiali0ation of +#ild +lass ob,e+t.
"#i$# of t#e follo%ing statement is true&
1/ @#enever we are +reatin! +#ild +lass ob,e+t t#en a(to"ati+ally parent +lass ob,e+t will
be +reated.Bfalse/
2/ @#enever we are +reatin! +#ild +lass ob,e+t t#en parent +lass +onstr(+tor will be
eEe+(ted.Btr(e/
Example:
abstra+t +lass \arent
7
\arentB/
7
Cyste".o(t.printlnBt#is.#as#'odeB//9JJ113&4)33JJ#ere t#is "eans +#ild +lass
ob,e+t
=
=
+lass '#ild eEtends \arent
7
'#ildB/
7
Cyste".o(t.printlnBt#is.#as#'odeB//9JJ113&4)33
=
=
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
'#ild +8new '#ildB/9
Cyste".o(t.printlnB+.#as#'odeB//9JJ113&4)33
=
=

2)3

*ase 1: re+(rsive "et#od +all is always r(nti"e eE+eption w#ere as re+(rsive +onstr(+tor
invo+ation is a +o"pile ti"e error.
/ote:
Re$ursive fun$tions:
A f(n+tion is +alled (sin! two "et#ods Btypes/.
1/ :ested +all
2/ Re+(rsive +all
/ested $all:
'allin! a f(n+tion inside anot#er f(n+tion is +alled nested +all.
In nested +all t#ere is a +allin! f(n+tion w#i+# +alls anot#er f(n+tionB+alled f(n+tion/.
Example:
p(bli+ stati+ void "et#odIneB/
7
"et#odTwoB/9
=
p(bli+ stati+ void "et#odTwoB/
7
"et#odIneB/9
=
Re$ursive $all:
'allin! a f(n+tion wit#in sa"e f(n+tion is +alled re+(rsive +all.
In re+(rsive +all +alled and +allin! f(n+tion is sa"e.
Example:
p(bli+ void "et#odIneB/
7
"et#odIneB/9
=












2)4

Example:

/ote: 'o"piler is responsible for t#e followin! +#e+?in!s.
1/ 'o"piler will +#e+? w#et#er t#e pro!ra""er wrote any +onstr(+tor or not. If #e didnAt
write at least one +onstr(+tor t#en +o"piler will !enerate defa(lt +onstr(+tor.
2/ If t#e pro!ra""er wrote any +onstr(+tor t#en +o"piler will +#e+? w#et#er #e wrote
s(perB/ or t#isB/ in t#e 1
st
line or not. If #is not writin! any of t#ese +o"piler will always
write B!enerate/ s(perB/.
3/ 'o"piler will +#e+? is t#ere any +#an+e of re+(rsive +onstr(+tor invo+ation. If t#ere is a
possibility t#en +o"piler will raise +o"pile ti"e error.
*ase 2:

If t#e \arent +lass +ontains any ar!("ent +onstr(+tors w#ile writin! '#ild +lasses we
s#o(ld ta?es spe+ial +are wit# respe+t to +onstr(+tors.
@#enever we are writin! any ar!("ent +onstr(+tor it is #i!#ly re+o""ended to write
no ar!("ent +onstr(+tor also.
*ase 3:
+lass \arent

2)5

7
\arentB/t#rows ,ava.io.II<E+eption
7=
=
+lass '#ild eEtends \arent
7=
!utput:
'o"pile ti"e error
;nreported eE+eption ,ava.io.II<E+eption in defa(lt +onstr(+tor.
Example:
+lass \arent
7
\arentB/t#rows ,ava.io.II<E+eption
7=
=
+lass '#ild eEtends \arent
7
'#ildB/t#rows <E+eption
7
s(perB/9
=
=
If \arent +lass +onstr(+tor t#rows so"e +#e+?ed eE+eption +o"p(lsory '#ild +lass
+onstr(+tor s#o(ld t#row t#e sa"e +#e+?ed eE+eption Bor/ its \arent.
2ingleton $lasses:
Hor any ,ava +lass if we are allow to +reate only one ob,e+t s(+# type of +lass is said to be
sin!leton +lass.
Example:
1/ R(nti"e +lass
2/ A+tionCervlet
3/ Cervi+eLo+ator
R(nti"e r18R(nti"e.!etR(nti"eB/9JJgetRuntime:; met#od is a fa$tor( met#od
.................................................
.................................................
R(nti"e r28R(nti"e.!etR(nti"eB/9
.................................................
.................................................
R(nti"e r38R(nti"e.!etR(nti"eB/9

2)6

Cyste".o(t.printlnBr188r2/9JJtr(e
Cyste".o(t.printlnBr188r3/9JJtr(e
'iagram:

If t#e reV(ire"ent is sa"e t#en instead of +reatin! a separate ob,e+t for every person
we will +reate only one ob,e+t and we +an s#are t#at ob,e+t for every reV(ired person
we +an a+#ieve t#is by (sin! sin!leton +lasses. T#at is t#e "ain advanta!es of sin!leton
+lasses are \erfor"an+e will be i"proved and "e"ory (tili0ation will be i"proved.
*reation of our o%n singleton $lasses:
@e +an +reate o(r own sin!leton +lasses for t#is we #ave to (se private +onstr(+tor and
fa+tory "et#od.
Example:
+lass Test
7
private stati+ Test t8n(ll9
private TestB/
7=
p(bli+ stati+ Test !etTestB/JJ!etTestB/ "et#od is a fa+tory "et#od
7
ifBt88n(ll/
7
t8new TestB/9
=
ret(rn t9
=
=
+lass 'lient
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBTest.!etTestB/.#as#'odeB//9JJ1671711
Cyste".o(t.printlnBTest.!etTestB/.#as#'odeB//9JJ1671711
Cyste".o(t.printlnBTest.!etTestB/.#as#'odeB//9JJ1671711
Cyste".o(t.printlnBTest.!etTestB/.#as#'odeB//9JJ1671711
=
=

2)7

'iagram:

/ote:
@e +an +reate any EEEton +lasses li?eBdo(ble ton-trible tone.et+/
Example:
+lass Test
7
private stati+ Test t18n(ll9
private stati+ Test t28n(ll9
private TestB/
7=
p(bli+ stati+ Test !etTestB/JJ!etTestB/ "et#od is a fa+tory "et#od
7
ifBt188n(ll/
7
t18new TestB/9
ret(rn t19
=
else ifBt288n(ll/
7
t28new TestB/9
ret(rn t29
=
else
7
ifB%at#.rando"B/Z).5/
ret(rn t19
else
ret(rn t29
=
=
=
+lass 'lient
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7

2)$

Cyste".o(t.printlnBTest.!etTestB/.#as#'odeB//9JJ1671711
Cyste".o(t.printlnBTest.!etTestB/.#as#'odeB//9JJ113&4)33
Cyste".o(t.printlnBTest.!etTestB/.#as#'odeB//9JJ113&4)33
Cyste".o(t.printlnBTest.!etTestB/.#as#'odeB//9JJ1671711
=
=
"#i$# of t#e follo%ing is true&
1/ T#e na"e of t#e +onstr(+tor and na"e of t#e +lass need not be sa"e.Bfalse/
2/ @e +an de+lare ret(rn type for t#e +onstr(+tor b(t it s#o(ld be void. Bfalse/
3/ @e +an (se any "odifier for t#e +onstr(+tor. Bfalse/
4/ 'o"piler will always !enerate defa(lt +onstr(+tor. Bfalse/
5/ T#e "odifier of t#e defa(lt +onstr(+tor is always defa(lt. Bfalse/
6/ T#e 1
st
line inside every +onstr(+tor s#o(ld be s(per always. Bfalse/
7/ T#e 1
st
line inside every +onstr(+tor s#o(ld be eit#er s(per or t#is and if we are not
writin! anyt#in! +o"piler will always pla+e t#isB/.Bfalse/
$/ Iverloadin! +on+ept is not appli+able for +onstr(+tor. Bfalse/
&/ In#eritan+e and overridin! +on+epts are appli+able for +onstr(+tors. Bfalse/
1)/ 'on+rete +lass +an +ontain +onstr(+tor b(t abstra+t +lass +annot. Bfalse/
11/ Interfa+e +an +ontain +onstr(+tor. Bfalse/
12/ Re+(rsive +onstr(+tor +all is always r(nti"e eE+eption. Bfalse/
13/ If \arent +lass +onstr(+tor t#rows so"e (n4+#e+?ed eE+eption +o"p(lsory '#ild +lass
+onstr(+tor s#o(ld t#row t#e sa"e (n4+#e+?ed eE+eption or itAs \arent. Bfalse/
14/ @it#o(t (sin! private +onstr(+tor we +an +reate sin!leton +lass. Bfalse/
15/ :one of t#e above.Btr(e/
Fa$tor( met#od:
6y (sin! +lass na"e if we are +allin! a "et#od and t#at "et#od ret(rns t#e sa"e +lass
ob,e+t s(+# type of "et#od is +alled fa+tory "et#od.
Example:
R(nti"e r8R(nti"e.!etR(nti"eB/9JJ!etR(nti"e is a fa+tory "et#od.
DateHor"at df8DateHor"at.!etInstan+eB/9
If ob,e+t +reation reV(ired (nder so"e +onstraints t#en we +an i"ple"ent by (sin!
fa+tory "et#od.







2)&

2tati$ $ontrol flo%:
Example:

7nal(sis:

!utput:
<.Ys+,pT,ava+ 6ase.,ava
<.Ys+,pT,ava 6ase
)
Hirst stati+ blo+?
Ce+ond stati+ blo+?
2)
%ain "et#od

21)

Read indire$tl( %rite onl( state :or; RI"!:
If a variable is in RI@I state t#en we +anAt perfor" read operation dire+tly ot#erwise
we will !et +o"pile ti"e error sayin! ille!al forward referen+e.
Example:
























211

Example:






212

7nal(sis:

!utput:
<.Ys+,pT,ava Derived
)
6ase stati+ blo+?
)
Derived first stati+ blo+?
Derived se+ond stati+ blo+?
2))
Derived "ain
@#enever we are eEe+(tin! '#ild +lass t#e followin! seV(en+e of events will be perfor"ed
a(to"ati+ally.
1/ Identifi+ation of stati+ "e"bers fro" \arent to '#ild. D1 to 11>
2/ <Ee+(tion of stati+ variable assi!n"ents and stati+ blo+?s fro" \arent to '#ild.D12 to 22>
3/ <Ee+(tion of '#ild +lass "ainB/ "et#od.D23 to 25>.
2tati$ ,lo$+:
Ctati+ blo+?s will be eEe+(ted at t#e ti"e of +lass loadin! #en+e if we want to perfor"
any a+tivity at t#e ti"e of +lass loadin! we #ave to define t#at a+tivity inside stati+ blo+?.
@it# in a +lass we +an ta?e any no. If stati+ blo+?s and all t#ese stati+ blo+?s will be
eEe+(ted fro" top to botto".
Example:
T#e native libraries s#o(ld be loaded at t#e ti"e of +lass loadin! #en+e we #ave to
define t#at a+tivity inside stati+ blo+?.
Example:
+lass Test
7
stati+
7
Cyste".loadLibraryBNnative library pat#N/9
=
=

213

<very *D6' driver +lass internally +ontains a stati+ blo+? to re!ister t#e driver wit#
Driver%ana!er #en+e pro!ra""er is not responsible to define t#is eEpli+itly.
Example:
+lass Driver
7
stati+
7
Re!ister t#is driver wit# Driver%ana!er
=
=
"it#out using main:; met#od is it possi,le to print some statements to t#e $onsole&
Ans. aes- by (sin! stati+ blo+?.
Example:
+lass ^oo!le
7
stati+
7
Cyste".o(t.printlnBN#ello i +an printN/9
Cyste".eEitB)/9
=
=
!utput:
Sello i +an print
"it#out using main:; met#od and stati$ ,lo$+ is it possi,le to print some statements to t#e
$onsole&
Example 1:
+lass Test
7
stati+ int i8"et#odIneB/9
p(bli+ stati+ int "et#odIneB/
7
Cyste".o(t.printlnBN#ello i +an printN/9
Cyste".eEitB)/9
ret(rn 1)9
=
=
!utput:
Sello i +an print

214

Example 2:
+lass Test
7
stati+ Test t8new TestB/9
TestB/
7
Cyste".o(t.printlnBN#ello i +an printN/9
Cyste".eEitB)/9
=
=
!utput:
Sello i +an print
Example 3:
+lass Test
7
stati+ Test t8new TestB/9
7
Cyste".o(t.printlnBN#ello i +an printN/9
Cyste".eEitB)/9
=
=
!utput:
Sello i +an print
"it#out using 2(stem9out9println:; statement is it possi,le to print some statement to t#e
$onsole&
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".err.printlnBN#elloN/9
=
=






215

Instan$e $ontrol flo%:

7nal(sis:
i8)DRI@I>
,8)DRI@I>
i81)DRc@>
,82)DRc@>
!utput:


216

@#enever we are +reatin! an ob,e+t t#e followin! seV(en+e of events will be perfor"ed
a(to"ati+ally.
1/ Identifi+ation of instan+e "e"bers fro" top to botto"B3 to $/.
2/ <Ee+(tion of instan+e variable assi!n"ents and instan+e blo+?s fro" top to botto"B& to
14/.
3/ <Ee+(tion of +onstr(+tor.
/ote: stati+ +ontrol flow is one ti"e a+tivity and it will be eEe+(ted at t#e ti"e of +lass loadin!.
6(t instan+e +ontrol flow is not one ti"e a+tivity for every ob,e+t +reation it will be
eEe+(ted.
Instan$e $ontrol flo% in 3arent and *#ild relations#ip:
Example:
+lass \arent
7
int E81)9
7
"et#odIneB/9
Cyste".o(t.printlnBN\arent first instan+e blo+?N/9
=
\arentB/
7
Cyste".o(t.printlnBNparent +lass +onstr(+torN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\arent p8new \arentB/9
Cyste".o(t.printlnBNparent +lass "ain "et#odN/9
=
p(bli+ void "et#odIneB/
7
Cyste".o(t.printlnBy/9
=
int y82)9
=
+lass '#ild eEtends \arent
7
int i81))9
7
"et#odTwoB/9

217

Cyste".o(t.printlnBN'#ild first instan+e blo+?N/9
=
'#ildB/
7
Cyste".o(t.printlnBN'#ild +lass +onstr(+torN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
'#ild +8new '#ildB/9
Cyste".o(t.printlnBN'#ild +lass "ain "et#odN/9
=
p(bli+ void "et#odTwoB/
7
Cyste".o(t.printlnB,/9
=
7
Cyste".o(t.printlnBN'#ild se+ond instan+e blo+?N/9
=
int ,82))9
=
!utput:
<.Ys+,pT,ava+ '#ild.,ava
<.Ys+,pT,ava '#ild
)
\arent first instan+e blo+?
\arent +lass +onstr(+tor
)
'#ild first instan+e blo+?
'#ild se+ond instan+e blo+?
'#ild +lass +onstr(+tor
'#ild +lass "ain "et#od
@#enever we are +reatin! +#ild +lass ob,e+t t#e followin! seV(en+e of events will be
eEe+(ted a(to"ati+ally.
1/ Identifi+ation of instan+e "e"bers fro" \arent to '#ild.
2/ <Ee+(tion of instan+e variable assi!n"ents and instan+e blo+? only in \arent +lass.
3/ <Ee+(tion of \arent +lass +onstr(+tor.
4/ <Ee+(tion of instan+e variable assi!n"ents and instan+e blo+?s in '#ild +lass.
5/ <Ee+(tion of '#ild +lass +onstr(+tor.

21$

/ote. Ib,e+t +reation is t#e "ost +ostly operation in ,ava and #en+e if t#ere is no spe+ifi+
reV(ire"ent never re+o""ended to +rate ob,e+ts.
Example 1:
p(bli+ +lass Initili0ation
7
private stati+ Ctrin! "et#odIneBCtrin! "s!/
7
Cyste".o(t.printlnB"s!/9
ret(rn "s!9
=
p(bli+ Initili0ationB/
7
"8"et#odIneBN1N/9
=
7
"8"et#odIneBN2N/9
=
Ctrin! "8"et#odIneBN3N/9
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ib,e+t ob,8new Initili0ationB/9
=
=
7nal(sis:


21&

!utput:
2
3
1
Example 2:
p(bli+ +lass Initili0ation
7
private stati+ Ctrin! "et#odIneBCtrin! "s!/
7
Cyste".o(t.printlnB"s!/9
ret(rn "s!9
=
stati+ Ctrin! "8"et#odIneBN1N/9
7
"8"et#odIneBN2N/9
=
stati+
7
"8"et#odIneBN3N/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ib,e+t ob,8new Initili0ationB/9
=
=
!utput:
1
3
2
@e +anAt a++ess instan+e variables dire+tly fro" stati+ area be+a(se at t#e ti"e of
eEe+(tion of stati+ area *% "ay not identify t#ose "e"bers.








22)

Example:

6(t fro" t#e instan+e area we +an a++ess instan+e "e"bers dire+tly.
Ctati+ "e"bers we +an a++ess fro" anyw#ere dire+tly be+a(se t#ese are identified
already at t#e ti"e of +lass loadin! only.
8(pe $asting:
\arent +lass referen+e +an be (sed to #old '#ild +lass ob,e+t b(t by (sin! t#at referen+e
we +anAt +all '#ild spe+ifi+ "et#ods.
Example:
Ib,e+t o8new Ctrin!BNb#as?arN/9JJvalid
Cyste".o(t.printlnBo.#as#'odeB//9JJvalid
Cyste".o(t.printlnBo.len!t#B//9JJ'.<.+annot find sy"bol-sy"bol . "et#od len!t#B/-lo+ation.
+lass ,ava.lan!.Ib,e+t
Ci"ilarly we +an (se interfa+e referen+e to #old i"ple"ented +lass ob,e+t.
Example:
R(nnable r8new T#readB/9
8(pe $asting s(ntax:

*ompile time $#e$+ing:
Rule 1: T#e type of KdL and K+L "(st #ave so"e relations#ip Deit#er '#ild to \arent Bor/ \arent
to '#ild Bor/ sa"e type> ot#erwise we will !et +o"pile ti"e error sayin! in+onvertible types.
Example 1:



221

Example 2:

Rule 2: K'L "(st be eit#er sa"e Bor/ derived type of KAL ot#erwise we will !et +o"pile ti"e
error sayin! in+o"patible types.
Ho(nd. '
ReV(ired. A
Example 1:

Example 2:

Runtime $#e$+ing:
T#e (nderlyin! ob,e+t type of KdL "(st be eit#er sa"e Bor/ derived type of K'L
ot#erwise we will !et r(nti"e eE+eption sayin! 'lass'ast<E+eption.
Example:





222

'iagram:

6ase1 b8new Derived2B/9JJvalid
Ib,e+t o8B6ase1/b9JJvalid
Ib,e+t o18B6ase2/o9JJinvalid
Ib,e+t o28B6ase2/b9JJinvalid
6ase2 b18B6ase1/Bnew Derived1B//9JJinvalid
6ase2 b28B6ase2/Bnew Derived3B//9JJvalid
6ase2 b28B6ase2/Bnew Derived1B//9JJinvalid
T#ro(!# Type 'astin! ,(st we are +onvertin! t#e type of ob,e+t b(t not ob,e+t itself t#at
is we are perfor"in! type +astin! b(t not ob,e+t +astin!.
Example:
















223

Example 1:

Example 2:

It is overridin! and "et#od resol(tion is based on r(nti"e ob,e+t.

224

' +8new 'B/9
+."et#odIneB/9JJ+
BB6/+/."et#odIneB/9JJ+
BBA/BB6/+//."et#odIneB/9JJ+
Example 3:

It is "et#od #idin! and "et#od resol(tion is based on referen+e type.
' +8new 'B/9
+."et#odIneB/9JJ'
BB6/+/."et#odIneB/9JJ6
BBA/BB6/+//."et#odIneB/9JJA
Example 4:

' +8new 'B/9
Cyste".o(t.printlnB+.E/9JJ&&&
Cyste".o(t.printlnBBB6/+/.E/9JJ$$$
Cyste".o(t.printlnBBBA/BB6/+//.E/9JJ777
ariable resol(tion is always based on referen+e type only.
If we are +#an!in! variable as stati+ t#en also we will !et t#e sa"e o(tp(t.
*oupling:
T#e de!ree of dependen+y between t#e +o"ponents is +alled +o(plin!.

225

Example:
+lass A
7
stati+ int i86.,9
=
+lass 6 eEtends A
7
stati+ int ,8'."et#odIneB/9
=
+lass ' eEtends 6
7
p(bli+ stati+ int "et#odIneB/
7
ret(rn D.?9
=
=
+lass D eEtends '
7
stati+ int ?81)9
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
D d8new DB/9
=
=
T#e above +o"ponents are said to be ti!#tly +o(pled to ea+# ot#er be+a(se t#e
dependen+y between t#e +o"ponents is "ore.
Ti!#tly +o(plin! is not a !ood pro!ra""in! pra+ti+e be+a(se it #as several serio(s
disadvanta!es.
1/ @it#o(t effe+tin! re"ainin! +o"ponents we +anAt "odify any +o"ponent #en+e
en#an+e"entBdevelop"ent/ will be+o"e diffi+(lt.
2/ It red(+es "aintainability of t#e appli+ation.
3/ It doesnAt pro"ote re(sability of t#e +ode.
It is always re+o""ended to "aintain loosely +o(plin! between t#e +o"ponents.
*o#esion:
Hor every +o"ponent we #ave to "aintain a +lear well defined f(n+tionality s(+# type of
+o"ponent is said to be follow #i!# +o#esion.



226

'iagram:

Si!# +o#esion is always !ood pro!ra""in! pra+ti+e be+a(se it #as several advanta!es.
1/ @it#o(t effe+tin! re"ainin! +o"ponents we +an "odify any +o"ponent #en+e
en#an+e"ent will be+o"e very easy.
2/ It i"proves "aintainability of t#e appli+ation.
3/ It pro"otes re(sability of t#e appli+ation.
/ote: It is #i!#ly re+o""ended to follow loosely +o(plin! and #i!# +o#esion.











227

=ulti 8#reading
7genda
1/ Introd(+tion.
2/ T#e ways to define instantiate and start a new T#read.
3/ ^ettin! and settin! na"e of a T#read.
4/ T#read priorities.
5/ T#e "et#ods to preventBstop/ T#read eEe+(tion.
1. yieldB/
2. ,oinB/
3. sleepB/
6/ Cyn+#roni0ation.
7/ Inter T#read +o""(ni+ation.
$/ Deadlo+?
V; Dae"on T#reads.
=ultitas+ing: <Ee+(tin! several tas?s si"(ltaneo(sly is t#e +on+ept of "(ltitas?in!. T#ere are
two types of "(ltitas?in!As.
1; 3ro$ess ,ased multitas+ing9
2/ 8#read ,ased multitas+ing9
'iagram:

3ro$ess ,ased multitas+ing: <Ee+(tin! several tas?s si"(ltaneo(sly w#ere ea+# tas? is a
separate independent pro+ess s(+# type of "(ltitas?in! is +alled pro+ess based "(ltitas?in!.
Example:
@#ile typin! a ,ava pro!ra" in t#e editor we +an able to listen "p3 a(dio son!s at t#e
sa"e ti"e we +an download a file fro" t#e net all t#ese tas?s are independent of ea+#
ot#er and eEe+(tin! si"(ltaneo(sly and #en+e it is \ro+ess based "(ltitas?in!.
T#is type of "(ltitas?in! is best s(itable at Kos levelL.
8#read ,ased multitas+ing: <Ee+(tin! several tas?s si"(ltaneo(sly w#ere ea+# tas? is a
separate independent part of t#e sa"e pro!ra"- is +alled T#read based "(ltitas?in!. And ea+#
independent part is +alled a KT#readL.
T#is type of "(ltitas?in! is best s(itable for Kpro!ra"ati+ levelL.
@#en +o"pared wit# K'FFL- developin! "(ltit#readin! eEa"ples is very easy in ,ava
be+a(se ,ava provides in b(ilt s(pport for "(ltit#readin! t#ro(!# a ri+# A\I BT#read-
R(nnable- T#read^ro(p- T#readLo+ale.et+/.

22$

In "(ltit#readin! on 1)` of t#e wor? t#e pro!ra""er is reV(ired to do and &)` of t#e
wor? will be down by ,ava A\I.
T#e "ain i"portant appli+ation areas of "(ltit#readin! are.
1/ To i"ple"ent "(lti"edia !rap#i+s.
2/ To develop ani"ations.
3/ To develop video !a"es et+.
@#et#er it is pro+ess based or T#read based t#e "ain ob,e+tive of "(ltitas?in! is to
i"prove perfor"an+e of t#e syste" by red(+in! response ti"e.
8#e %a(s to define instantiate and start a ne% 8#read:
"#at is singleton& Give example&
@e +an define a T#read in t#e followin! 2 ways.
1. 6y eEtendin! T#read +lass.
2. 6y i"ple"entin! R(nnable interfa+e.
'efining a 8#read ,( extending >8#read $lass@:
Example:

+lass T#readDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
%yT#read t8new %yT#readB/9JJInstantiation of a T#read
t.startB/9JJstartin! of a T#read

forBint i8)9iZ59iFF/
7
Cyste".o(t.printlnBN"ain t#readN/9
=
=
=


22&

*ase 1: 8#read 2$#eduler:
If "(ltiple T#reads are waitin! to eEe+(te t#en w#i+# T#read will eEe+(te 1
st
is de+ided
by KT#read C+#ed(lerL w#i+# is part of *%.
@#i+# al!orit#" or be#avior followed by T#read C+#ed(ler we +anAt eEpe+t eEa+tly it is
t#e *% vendor dependent #en+e in "(ltit#readin! eEa"ples we +anAt eEpe+t eEa+t
eEe+(tion order and eEa+t o(tp(t.
T#e followin! are vario(s possible o(tp(ts for t#e above pro!ra".

*ase 2: 'ifferen$e ,et%een t9start:; and t9run:; met#ods9
In t#e +ase of t.startB/ a new T#read will be +reated w#i+# is responsible for t#e
eEe+(tion of r(nB/ "et#od. 6(t in t#e +ase of t.r(nB/ no new T#read will be +reated and
r(nB/ "et#od will be eEe+(ted ,(st li?e a nor"al "et#od by t#e "ain T#read. In t#e
above pro!ra" if we are repla+in! t.startB/ wit# t.r(nB/ t#e followin! is t#e o(tp(t.
!utput:
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
"ain t#read

23)

"ain t#read
"ain t#read
"ain t#read
"ain t#read
<ntire o(tp(t prod(+ed by only "ain T#read.
*ase 3: importan$e of 8#read $lass start:; met#od9
Hor every T#read t#e reV(ired "andatory a+tivities li?e re!isterin! t#e T#read wit#
T#read C+#ed(ler will ta?es +are by T#read +lass startB/ "et#od and pro!ra""er is
responsible ,(st to define t#e ,ob of t#e T#read inside r(nB/ "et#od. T#at is startB/
"et#od a+ts as best assistant to t#e pro!ra""er.
Example:
startB/
7
1. Re!ister T#read wit# T#read C+#ed(ler
2. All ot#er "andatory low level a+tivities.
3. Invo?e or +allin! r(nB/ "et#od.
=
@e +an +on+l(de t#at wit#o(t eEe+(tin! T#read +lass startB/ "et#od t#ere is no +#an+e
of startin! a new T#read in ,ava.
*ase 4: If %e are not overriding run:; met#od:
If we are not overridin! r(nB/ "et#od t#en T#read +lass r(nB/ "et#od will be eEe+(ted
w#i+# #as e"pty i"ple"entation and #en+e we wonAt !et any o(tp(t.
Example:
+lass %yT#read eEtends T#read
7=
+lass T#readDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
%yT#read t8new %yT#readB/9
t.startB/9
=
=
It is #i!#ly re+o""ended to override r(nB/ "et#od. It#erwise donAt !o for
"(ltit#readin! +on+ept.




231

*ase 5: !verriding of run:; met#od9
@e +an overload r(nB/ "et#od b(t T#read +lass startB/ "et#od always invo?es no
ar!("ent r(nB/ "et#od t#e ot#er overload r(nB/ "et#ods we #ave to +all eEpli+itly t#en
only it will be eEe+(ted ,(st li?e nor"al "et#od.
Example:
+lass %yT#read eEtends T#read
7
p(bli+ void r(nB/
7
Cyste".o(t.printlnBNno ar! "et#odN/9
=
p(bli+ void r(nBint i/
7
Cyste".o(t.printlnBNint ar! "et#odN/9
=
=
+lass T#readDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
%yT#read t8new %yT#readB/9
t.startB/9
=
=
!utput:
:o ar! "et#od
*ase 6: overriding of start:; met#od:
If we override startB/ "et#od t#en o(r startB/ "et#od will be eEe+(ted ,(st li?e a nor"al
"et#od +all and no new T#read will be started.
Example:
+lass %yT#read eEtends T#read
7
p(bli+ void startB/
7
Cyste".o(t.printlnBNstart "et#odN/9
=
p(bli+ void r(nB/
7

232

Cyste".o(t.printlnBNr(n "et#odN/9
=
=
+lass T#readDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
%yT#read t8new %yT#readB/9
t.startB/9
Cyste".o(t.printlnBN"ain "et#odN/9
=
=
!utput:
start "et#od
"ain "et#od
<ntire o(tp(t prod(+ed by only "ain T#read.
*ase :
Example 1:










233

Example 2:

!utput:

*ase B: life $($le of t#e 8#read:
'iagram:

In+e we +reated a T#read ob,e+t t#en t#e T#read is said to be in new state or born
state.
In+e we +all startB/ "et#od t#en t#e T#read will be entered into Ready or R(nnable
state.
If T#read C+#ed(ler allo+ates '\; t#en t#e T#read will be entered into r(nnin! state.
In+e r(nB/ "et#od +o"pletes t#en t#e T#read will entered into dead state.
*ase V:
After startin! a T#read we are not allowed to restart t#e sa"e T#read on+e a!ain
ot#erwise we will !et r(nti"e eE+eption sayin! KIlle!alT#readCtate<E+eptionL.
Example:
%yT#read t8new %yT#readB/9
t.startB/9JJvalid
99999999
t.startB/9JJwe will !et R.< sayin!. Ille!alT#readCtate<E+eption

234

'efining a 8#read ,( implementing Runna,le interfa$e:
@e +an define a T#read even by i"ple"entin! R(nnable interfa+e also. R(nnable
interfa+e present in ,ava.lan!.p?! and +ontains only one "et#od r(nB/.
'iagram:

Example:

+lass T#readDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
%yR(nnable r8new %yR(nnableB/9
T#read t8new T#readBr/9JJ#ere r is a Tar!et R(nnable
t.startB/9

forBint i8)9iZ1)9iFF/
7
Cyste".o(t.printlnBN"ain t#readN/9
=
=
=


235

!utput:
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
@e +anAt eEpe+t eEa+t o(tp(t b(t t#ere are several possible o(tp(ts.
*ase stud(:
%yR(nnable r8new %yR(nnableB/9
T#read t18new T#readB/9
T#read t28new T#readBr/9
*ase 1: t19start:;:
A new T#read will be +reated w#i+# is responsible for t#e eEe+(tion of T#read +lass
r(nB/"et#od.
!utput:
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
*ase 2: t19run:;:
:o new T#read will be +reated b(t T#read +lass r(nB/ "et#od will be eEe+(ted ,(st li?e
a nor"al "et#od +all.

236

!utput:
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
*ase 3: t29start:;:
:ew T#read will be +reated w#i+# is responsible for t#e eEe+(tion of %yR(nnable r(nB/
"et#od.
!utput:
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
*ase 4: t29run:;:
:o new T#read will be +reated and %yR(nnable r(nB/ "et#od will be eEe+(ted ,(st li?e
a nor"al "et#od +all.
!utput:
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
*ase 5: r9start:;:
@e will !et +o"pile ti"e error sayin! startB/"et#od is not available in %yR(nnable
+lass.


237

!utput:
'o"pile ti"e error
<.YC'*\T,ava+ T#readDe"o.,ava
T#readDe"o.,ava.1$. +annot find sy"bol
Cy"bol. "et#od startB/
Lo+ation. +lass %yR(nnable
*ase 6: r9run:;:
:o new T#read will be +reated and %yR(nnable +lass r(nB/ "et#od will be eEe+(ted ,(st
li?e a nor"al "et#od +all.
!utput:
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
+#ild T#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
1est approa$# to define a 8#read:
A"on! t#e 2 ways of definin! a T#read- i"ple"ents R(nnable approa+# is always
re+o""ended.
In t#e 1
st
approa+# o(r +lass s#o(ld always eEtends T#read +lass t#ere is no +#an+e of
eEtendin! any ot#er +lass #en+e we are "issin! t#e benefits of in#eritan+e.
6(t in t#e 2
nd
approa+# w#ile i"ple"entin! R(nnable interfa+e we +an eEtend so"e
ot#er +lass also. Sen+e i"ple"ents R(nnable "e+#anis" is re+o""ended to define a
T#read.
8#read $lass $onstru$tors:
1/ T#read t8new T#readB/9
2/ T#read t8new T#readBR(nnable r/9
3/ T#read t8new T#readBCtrin! na"e/9
4/ T#read t8new T#readBR(nnable r-Ctrin! na"e/9
5/ T#read t8new T#readBT#read^ro(p !-Ctrin! na"e/9
6/ T#read t8new T#readBT#read^ro(p !-R(nnable r/9
7/ T#read t8new T#readBT#read^ro(p !-R(nnable r-Ctrin! na"e/9
$/ T#read t8new T#readBT#read^ro(p !-R(nnable r-Ctrin! na"e-lon! sta+?Ci0e/9


23$

'urgaIs approa$# to define a 8#read:not re$ommended to use;:

'iagram:

!utput:
"ain "et#od
r(n "et#od
Getting and setting name of a 8#read:
<very T#read in ,ava #as so"e na"e it "ay be provided eEpli+itly by t#e pro!ra""er or
a(to"ati+ally !enerated by *%.
T#read +lass defines t#e followin! "et#ods to !et and set na"e of a T#read.
=et#ods:
1; pu,li$ final 2tring get/ame:;
2; pu,li$ final void set/ame:2tring name;
Example:
+lass %yT#read eEtends T#read
7=
+lass T#readDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBT#read.+(rrentT#readB/.!et:a"eB//9JJ"ain
%yT#read t8new %yT#readB/9
Cyste".o(t.printlnBt.!et:a"eB//9JJT#read4)
T#read.+(rrentT#readB/.set:a"eBN6#as?ar T#readN/9
Cyste".o(t.printlnBT#read.+(rrentT#readB/.!et:a"eB//9JJ6#as?ar T#read
=
=

23&

/ote: @e +an !et +(rrent eEe+(tin! T#read ob,e+t referen+e by (sin! T#read.+(rrentT#readB/
"et#od.
8#read 3riorities
<very T#read in ,ava #as so"e priority it "ay be defa(lt priority !enerated by *% Bor/
eEpli+itly provided by t#e pro!ra""er.
T#e valid ran!e of T#read priorities is 1 to 1)Db(t not ) to 1)> w#ere 1 is t#e least
priority and 1) is #i!#est priority.
T#read +lass defines t#e followin! +onstants to represent so"e standard priorities.
1; 8#read9 =I/X3RI!RI8J<<<<<<<<<<1
2; 8#read9 =7DX3RI!RI8J<<<<<<<<<<15
3; 8#read9 /!R=X3RI!RI8J<<<<<<<<5
T#ere are no +onstants li?e T#read.LI@2\RIIRITa- T#read.SI^S2\RIIRITa
T#read s+#ed(ler (ses t#ese priorities w#ile allo+atin! '\;.
T#e T#read w#i+# is #avin! #i!#est priority will !et +#an+e for 1
st
eEe+(tion.
If 2 T#reads #avin! t#e sa"e priority t#en we +anAt eEpe+t eEa+t eEe+(tion order it
depends on T#read s+#ed(ler w#ose be#avior is vendor dependent.
@e +an !et and set t#e priority of a T#read by (sin! t#e followin! "et#ods.
1; pu,li$ final int get3riorit(:;
2) pu,li$ final void set3riorit(:int ne%3riorit(;EWWt#e allo%ed values are 1 to 15
T#e allowed val(es are 1 to 1) ot#erwise we will !et r(nti"e eE+eption sayin!
KIlle!alAr!("ent<E+eptionL.
'efault priorit(:
T#e defa(lt priority only for t#e "ain T#read is 5. 6(t for all t#e re"ainin! T#reads t#e
defa(lt priority will be in#eritin! fro" parent to +#ild. T#at is w#atever t#e priority
parent #as by defa(lt t#e sa"e priority will be for t#e +#ild also.
Example 1:
+lass %yT#read eEtends T#read
7=
+lass T#read\riorityDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBT#read.+(rrentT#readB/.!et\riorityB//9JJ5
T#read.+(rrentT#readB/.set\riorityB&/9
%yT#read t8new %yT#readB/9
Cyste".o(t.printlnBt.!et\riorityB//9JJ&
=
=

24)

Example 2:
+lass %yT#read eEtends T#read
7
p(bli+ void r(nB/
7
forBint i8)9iZ1)9iFF/
7
Cyste".o(t.printlnBN+#ild t#readN/9
=
=
=
+lass T#read\riorityDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
%yT#read t8new %yT#readB/9
JJt.set\riorityB1)/9 1
t.startB/9
forBint i8)9iZ1)9iFF/
7
Cyste".o(t.printlnBN"ain t#readN/9
=
=
=
If we are +o""entin! line 1 t#en bot# "ain and +#ild T#reads will #ave t#e sa"e
priority and #en+e we +anAt eEpe+t eEa+t eEe+(tion order.
If we are not +o""entin! line 1 t#en +#ild T#read #as t#e priority 1) and "ain T#read
#as t#e priority 5 #en+e +#ild T#read will !et +#an+e for eEe+(tion and after +o"pletin!
+#ild T#read "ain T#read will !et t#e +#an+e in t#is t#e o(tp(t is.
!utput:
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read

241

+#ild t#read
+#ild t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
Co"e operatin! syste"sBli?e windowsP\/ "ay not provide proper s(pport for T#read
priorities. @e #ave to install separate bats provided by vendor to provide s(pport for
priorities.
8#e =et#ods to 3revent a 8#read from Exe$ution:
@e +an preventBstop/ a T#read eEe+(tion by (sin! t#e followin! "et#ods.
1; (ield:;E
2; join:;E
3; sleep:;E
(ield:;:
yieldB/ "et#od +a(ses Kto pa(se +(rrent eEe+(tin! T#read for !ivin! t#e +#an+e of
re"ainin! waitin! T#reads of sa"e priorityL.
If all waitin! T#reads #ave t#e low priority or if t#ere is no waitin! T#reads t#en t#e
sa"e T#read will be +ontin(ed its eEe+(tion.
If several waitin! T#reads wit# sa"e priority available t#en we +anAt eEpe+t eEa+t w#i+#
T#read will !et +#an+e for eEe+(tion.
T#e T#read w#i+# is yielded w#en it !et +#an+e on+e a!ain for eEe+(tion is depends on
"er+y of t#e T#read s+#ed(ler.
p(bli+ stati+ native void (ieldB/9
'iagram:





242

Example:
+lass %yT#read eEtends T#read
7
p(bli+ void r(nB/
7
forBint i8)9iZ59iFF/
7
T#read.yieldB/9
Cyste".o(t.printlnBN+#ild t#readN/9
=
=
=
+lass T#readaieldDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
%yT#read t8new %yT#readB/9
t.startB/9
forBint i8)9iZ59iFF/
7
Cyste".o(t.printlnBN"ain t#readN/9
=
=
=
!utput:
"ain t#read
"ain t#read
"ain t#read
"ain t#read
"ain t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
+#ild t#read
In t#e above eEa"ple t#e +#an+e of +o"pletin! "ain T#read 1
st
is #i!# be+a(se +#ild
T#read always +allin! yieldB/ "et#od.


243

0oin:;:
If a T#read wants to wait (ntil +o"pletin! so"e ot#er T#read t#en we s#o(ld !o for
,oinB/ "et#od.
Example:
If a T#read t1 eEe+(tes t2.,oinB/ t#en t1 s#o(ld !o for waitin! state (ntil +o"pletin! t2.
'iagram:

1; pu,li$ final void join:;t#ro%s InterruptedEx$eption
2; pu,li$ final void join:long ms; t#ro%s InterruptedEx$eption
3; pu,li$ final void join:long msHint ns; t#ro%s InterruptedEx$eption
'iagram:

<very ,oinB/ "et#od t#rows Interr(pted<E+eption- w#i+# is +#e+?ed eE+eption #en+e
+o"p(lsory we s#o(ld #andle eit#er by try +at+# or by t#rows ?eyword.
Example:
+lass %yT#read eEtends T#read
7
p(bli+ void r(nB/
7
forBint i8)9iZ59iFF/
7
Cyste".o(t.printlnBNCeet#e T#readN/9
try

244

7
T#read.sleepB2)))/9
=
+at+# BInterr(pted<E+eption e/7=
=
=
=
+lass T#read*oinDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows Interr(pted<E+eption
7
%yT#read t8new %yT#readB/9
t.startB/9
JJt.,oinB/9 1
forBint i8)9iZ59iFF/
7
Cyste".o(t.printlnBNRa"a T#readN/9
=
=
=
If we are +o""entin! line 1 t#en bot# T#reads will be eEe+(ted si"(ltaneo(sly and we
+anAt eEpe+t eEa+t eEe+(tion order.
If we are not +o""entin! line 1 t#en "ain T#read will wait (ntil +o"pletin! +#ild
T#read in t#is t#e o(tp(t is seet#e T#read 5 ti"es followed by Ra"a T#read 5 ti"es.
2leep:; met#od:
If a T#read donAt want to perfor" any operation for a parti+(lar a"o(nt of ti"e t#en we
s#o(ld !o for sleepB/ "et#od.
1; pu,li$ stati$ native void sleep:long ms; t#ro%s InterruptedEx$eption
2; pu,li$ stati$ void sleep:long msHint ns;t#ro%s InterruptedEx$eption












245

'iagram:

Example:
+lass T#read*oinDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows Interr(pted<E+eption
7
Cyste".o(t.printlnBN%N/9
T#read.sleepB3)))/9
Cyste".o(t.printlnBN<N/9
T#read.sleepB3)))/9
Cyste".o(t.printlnBN^N/9
T#read.sleepB3)))/9
Cyste".o(t.printlnBNAN/9
=
=
!utput:
%
<
^
A
Interrupting a 8#read:
@e +an interr(pt a sleepin! or waitin! T#read by (sin! interr(ptB/Bbrea? off/ "et#od of
T#read +lass.
Example:
+lass %yT#read eEtends T#read
7
p(bli+ void r(nB/
7
try

246

7
forBint i8)9iZ59iFF/
7
Cyste".o(t.printlnBNi a" la0y T#read .NFi/9
T#read.sleepB2)))/9
=
=
+at+# BInterr(pted<E+eption e/
7
Cyste".o(t.printlnBNi !ot interr(ptedN/9
=
=
=
+lass T#readInterr(ptDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
%yT#read t8new %yT#readB/9
t.startB/9
JJt.interr(ptB/9 1
Cyste".o(t.printlnBNend of "ain t#readN/9
=
=
If we are +o""entin! line 1 t#en "ain T#read wonAt interr(pt +#ild T#read and #en+e
+#ild T#read will be +ontin(ed (ntil its +o"pletion.
If we are not +o""entin! line 1 t#en "ain T#read interr(pts +#ild T#read and #en+e
+#ild T#read wonAt +ontin(ed (ntil its +o"pletion in t#is +ase t#e o(tp(t is.
<nd of "ain t#read
I a" la0y T#read. )
I !ot interr(pted
/ote:
@#enever we are +allin! interr(ptB/ "et#od we "ay not see t#e effe+t i""ediately- if
t#e tar!et T#read is in sleepin! or waitin! state it will be interr(pted i""ediately.
If t#e tar!et T#read is not in sleepin! or waitin! state t#en interr(pt +all will wait (ntil
tar!et T#read will enter into sleepin! or waitin! state. In+e tar!et T#read entered into
sleepin! or waitin! state it will effe+t i""ediately.
In its lifeti"e if t#e tar!et T#read never entered into sleepin! or waitin! state t#en t#ere
is no i"pa+t of interr(pt +all si"ply interr(pt +all will be wasted.

247

Example:
+lass %yT#read eEtends T#read
7
p(bli+ void r(nB/
7
forBint i8)9iZ59iFF/
7
Cyste".o(t.printlnBNia"la0y t#readN/9
=
try
7
T#read.sleepB3)))/9
=
+at+# BInterr(pted<E+eption e/
7
Cyste".o(t.printlnBNi !ot interr(ptedN/9
=
=
=
+lass T#readInterr(ptDe"o1
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
%yT#read t8new %yT#readB/9
t.startB/9
t.interr(ptB/9
Cyste".o(t.printlnBNend of "ain t#readN/9
=
=
In t#e above pro!ra" interr(ptB/ "et#od +all invo?ed by "ain T#read will wait (ntil
+#ild T#read entered into sleepin! state.
In+e +#ild T#read entered into sleepin! state t#en it will be interr(pted i""ediately.
*ompression of (ieldH join and sleep:; met#od&
propert( Jield:; 0oin:; 2leep:;
1; 3urpose& To pa(se +(rrent
eEe+(tin! T#read
for !ivin! t#e
+#an+e of
re"ainin! waitin!
If a T#read wants
to wait (ntil
+o"pletin! so"e
ot#er T#read t#en
we s#o(ld !o for
If a T#read donAt
want to perfor"
any operation for
a parti+(lar
a"o(nt of ti"e

24$

T#reads of sa"e
priority.
,oin.

t#en we s#o(ld
!o for sleepB/
"et#od.
2; Is it stati$& yes no yes
3; Is it final& no yes no
4; Is it overloaded& :o yes yes
5; Is it t#ro%s
6/ InterruptedEx$eption&
no yes yes
; Is it native met#od& yes no sleepBlon! "s/
sleepBlon! "s-int
ns/
2(n$#roni4ation
Cyn+#roni0ed is t#e ?eyword appli+able for "et#ods and blo+?s b(t not for +lasses and
variables.
If a "et#od or blo+? de+lared as t#e syn+#roni0ed t#en at a ti"e only one T#read is allow
to eEe+(te t#at "et#od or blo+? on t#e !iven ob,e+t.
T#e "ain advanta!e of syn+#roni0ed ?eyword is we +an resolve date in+onsisten+y
proble"s.
6(t t#e "ain disadvanta!e of syn+#roni0ed ?eyword is it in+reases waitin! ti"e of t#e
T#read and effe+ts perfor"an+e of t#e syste".
Sen+e if t#ere is no spe+ifi+ reV(ire"ent t#en never re+o""ended to (se syn+#roni0ed
?eyword.
Internally syn+#roni0ation +on+ept is i"ple"ented by (sin! lo+? +on+ept.
<very ob,e+t in ,ava #as a (niV(e lo+?. @#enever we are (sin! syn+#roni0ed ?eyword t#en
only lo+? +on+ept will +o"e into t#e pi+t(re.
If a T#read wants to eEe+(te any syn+#roni0ed "et#od on t#e !iven ob,e+t 1
st
it #as to !et
t#e lo+? of t#at ob,e+t. In+e a T#read !ot t#e lo+? of t#at ob,e+t t#en itAs allow to eEe+(te
any syn+#roni0ed "et#od on t#at ob,e+t. If t#e syn+#roni0ed "et#od eEe+(tion +o"pletes
t#en a(to"ati+ally T#read releases lo+?.
@#ile a T#read eEe+(tin! any syn+#roni0ed "et#od t#e re"ainin! T#reads are not allowed
eEe+(te any syn+#roni0ed "et#od on t#at ob,e+t si"(ltaneo(sly. 6(t re"ainin! T#reads
are allowed to eEe+(te any non4syn+#roni0ed "et#od si"(ltaneo(sly. Dlo+? +on+ept is
i"ple"ented based on ob,e+t b(t not based on "et#od>.
Example:
+lass Display
7
p(bli+ syn+#roni0ed void wis#BCtrin! na"e/
7

24&

forBint i8)9iZ59iFF/
7
Cyste".o(t.printBN!ood "ornin!.N/9
try
7
T#read.sleepB1)))/9
=
+at+# BInterr(pted<E+eption e/
7=
Cyste".o(t.printlnBna"e/9
=
=
=
+lass %yT#read eEtends T#read
7
Display d9
Ctrin! na"e9
%yT#readBDisplay d-Ctrin! na"e/
7
t#is.d8d9
t#is.na"e8na"e9
=
p(bli+ void r(nB/
7
d.wis#Bna"e/9
=
=
+lass Cyn+#roni0edDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Display d18new DisplayB/9
%yT#read t18new %yT#readBd1-Nd#oniN/9
%yT#read t28new %yT#readBd1-Ny(vara,N/9
t1.startB/9
t2.startB/9
=
=

25)

If we are not de+larin! wis#B/ "et#od as syn+#roni0ed t#en bot# T#reads will be
eEe+(ted si"(ltaneo(sly and we will !et irre!(lar o(tp(t.
!utput:
!ood "ornin!.!ood "ornin!.y(vara,
!ood "ornin!.d#oni
!ood "ornin!.y(vara,
!ood "ornin!.d#oni
!ood "ornin!.y(vara,
!ood "ornin!.d#oni
!ood "ornin!.y(vara,
!ood "ornin!.d#oni
!ood "ornin!.y(vara,
d#oni
If we de+lare wis#B/"et#od as syn+#roni0ed t#en t#e T#reads will be eEe+(ted one by
one t#at is (ntil +o"pletin! t#e 1
st
T#read t#e 2
nd
T#read will wait in t#is +ase we will
!et re!(lar o(tp(t w#i+# is not#in! b(t
!utput:
!ood "ornin!.d#oni
!ood "ornin!.d#oni
!ood "ornin!.d#oni
!ood "ornin!.d#oni
!ood "ornin!.d#oni
!ood "ornin!.y(vara,
!ood "ornin!.y(vara,
!ood "ornin!.y(vara,
!ood "ornin!.y(vara,
!ood "ornin!.y(vara,
*ase stud(:
*ase 1:
Display d18new DisplayB/9
Display d28new DisplayB/9
%yT#read t18new %yT#readBd1-Nd#oniN/9
%yT#read t28new %yT#readBd2-Ny(vara,N/9
t1.startB/9
t2.startB/9




251

'iagram:

<ven t#o(!# we de+lared wis#B/ "et#od as syn+#roni0ed b(t we will !et irre!(lar
o(tp(t in t#is +ase- be+a(se bot# T#reads are operatin! on different ob,e+ts.
*lass level lo$+:
<very +lass in ,ava #as a (niV(e lo+?. If a T#read wants to eEe+(te a stati+ syn+#roni0ed
"et#od t#en it reV(ired +lass level lo+?.
In+e a T#read !ot +lass level lo+? t#en it is allow to eEe+(te any stati+ syn+#roni0ed
"et#od of t#at +lass.
@#ile a T#read eEe+(tin! any stati+ syn+#roni0ed "et#od t#e re"ainin! T#reads are
not allow to eEe+(te any stati+ syn+#roni0ed "et#od of t#at +lass si"(ltaneo(sly.
6(t re"ainin! T#reads are allowed to eEe+(te nor"al syn+#roni0ed "et#ods- nor"al
stati+ "et#ods- and nor"al instan+e "et#ods si"(ltaneo(sly.
'lass level lo+? and ob,e+t lo+? bot# are different and t#ere is no relations#ip between
t#ese two.
2(n$#roni4ed ,lo$+:
If very few lines of t#e +ode reV(ired syn+#roni0ation t#en itAs never re+o""ended to
de+lare entire "et#od as syn+#roni0ed we #ave to en+lose t#ose few lines of t#e +ode
wit# in syn+#roni0ed blo+?.
T#e "ain advanta!e of syn+#roni0ed blo+? over syn+#roni0ed "et#od is it red(+es
waitin! ti"e of T#read and i"proves perfor"an+e of t#e syste".
Example 1: To !et lo+? of +(rrent ob,e+t we +an de+lare syn+#roni0ed blo+? as follows.
2(n$#roni4ed:t#is;FY
Example 2: To !et t#e lo+? of a parti+(lar ob,e+t XbA we #ave to de+lare a syn+#roni0ed blo+? as
follows.
2(n$#roni4ed:,;FY
Example 3: To !et +lass level lo+? we #ave to de+lare syn+#roni0ed blo+? as follows.
2(n$#roni4ed:'ispla(9$lass;FY
As t#e ar!("ent to t#e syn+#roni0ed blo+? we +an pass eit#er ob,e+t referen+e or
K.+lass fileL and we +anAt pass pri"itive val(es as ar!("ent Dbe+a(se lo+? +on+ept is
dependent only for ob,e+ts and +lasses b(t not for pri"itives>.



252

Example:
Int E8b9
Cyn+#roni0edBE/7=
!utput:
'o"pile ti"e error.
;neEpe+ted type.
Ho(nd. int
ReV(ired. referen+e
Zuestions:
1/ <Eplain abo(t syn+#roni0ed ?eyword and its advanta!es and disadvanta!esW
2/ @#at is ob,e+t lo+? and w#en a T#read reV(iredW
3/ @#at is +lass level lo+? and w#en a T#read reV(iredW
4/ @#at is t#e differen+e between ob,e+t lo+? and +lass level lo+?W
5/ @#ile a T#read eEe+(tin! a syn+#roni0ed "et#od on t#e !iven ob,e+t is t#e re"ainin!
T#reads are allowed to eEe+(te ot#er syn+#roni0ed "et#ods si"(ltaneo(sly on t#e
sa"e ob,e+tW
7ns: :o.
6/ @#at is syn+#roni0ed blo+? and eEplain its de+larationW
7/ @#at is t#e advanta!e of syn+#roni0ed blo+? over syn+#roni0ed "et#odW
$/ Is a T#read +an #old "ore t#an one lo+? at a ti"eW
7ns: aes- (p +o(rse fro" different ob,e+ts.
Example:

'iagram:

&/ @#at is syn+#roni0ed state"entW
7ns: T#e state"ents w#i+# present inside syn+#roni0ed "et#od and syn+#roni0ed blo+? are
+alled syn+#roni0ed state"ents. DInterview people +reated ter"inolo!y>.

253

Inter 8#read $ommuni$ation :%ait:;Hnotif(:;H notif(7ll:;;:
Two T#reads +an +o""(ni+ate wit# ea+# ot#er by (sin! waitB/- notifyB/ and notifyAllB/
"et#ods.
T#e T#read w#i+# is eE+eptin! (pdation it #as to +all waitB/ "et#od and t#e T#read
w#i+# is perfor"in! (pdation it #as to +all notifyB/ "et#od. After !ettin! notifi+ation t#e
waitin! T#read will !et t#ose (pdations.
'iagram:

waitB/- notifyB/ and notifyAllB/ "et#ods are available in Ib,e+t +lass b(t not in T#read
+lass be+a(se T#read +an +all t#ese "et#ods on any +o""on ob,e+t.
To +all waitB/- notifyB/ and notifyAllB/ "et#ods +o"p(lsory t#e +(rrent T#read s#o(ld be
owner of t#at ob,e+t t#at is +(rrent T#read s#o(ld #as lo+? of t#at ob,e+t t#at is +(rrent
T#read s#o(ld be in syn+#roni0ed area. Sen+e we +an +all waitB/- notifyB/ and notifyAllB/
"et#ods only fro" syn+#roni0ed area ot#erwise we will !et r(nti"e eE+eption sayin!
Ille!al%onitorCtate<E+eption.
In+e a T#read +alls waitB/ "et#od on t#e !iven ob,e+t 1
st
it releases t#e lo+? of t#at
ob,e+t i""ediately and entered into waitin! state.
In+e a T#read +alls notifyB/ Bor/ notifyAllB/ "et#ods it releases t#e lo+? of t#at ob,e+t
b(t "ay not i""ediately.
<E+ept t#ese BwaitB/-notifyB/-notifyAllB// "et#ods t#ere is no ot#er pla+eB"et#od/ w#ere
t#e lo+? release will be #appen.


254

=et#od Is 8#read Releases Lo$+&
yieldB/ :o
,oinB/ :o
sleepB/ :o
waitB/ aes
notifyB/ aes
notifyAllB/ aes
In+e a T#read +alls waitB/- notifyB/- notifyAllB/ "et#ods on any ob,e+t t#en it releases
t#e lo+? of t#at parti+(lar ob,e+t b(t not all lo+?s it #as.
1; pu,li$ final void %ait:;t#ro%s InterruptedEx$eption
2; pu,li$ final native void %ait:long ms;t#ro%s InterruptedEx$eption
3; pu,li$ final void %ait:long msHint ns;t#ro%s InterruptedEx$eption
4; pu,li$ final native void notif(:;
5; pu,li$ final void notif(7ll:;
'iagram:

Example 1:
+lass T#readA
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows Interr(pted<E+eption
7
T#read6 b8new T#read6B/9
b.startB/9
syn+#roni0edBb/
7
Cyste".o(t.printlnBN"ain T#read +allin! waitB/ "et#odN/9JJstep41
b.waitB/9
Cyste".o(t.printlnBN"ain T#read !ot notifi+ation +allN/9JJstep44
Cyste".o(t.printlnBb.total/9
=

255

=
=
+lass T#read6 eEtends T#read
7
int total8)9
p(bli+ void r(nB/
7
syn+#roni0edBt#is/
7
Cyste".o(t.printlnBN+#ild t#read starts +al+(ationN/9JJstep42
forBint i8)9iZ81))9iFF/
7
total8totalFi9
=
Cyste".o(t.printlnBN+#ild t#read !ivin! notifi+ation +allN/9JJstep43
t#is.notifyB/9
=
=
=
!utput:
"ain T#read +allin! waitB/ "et#od
+#ild t#read starts +al+(lation
+#ild t#read !ivin! notifi+ation +all
"ain T#read !ot notifi+ation +all
5)5)
Example 2:
3rodu$er $onsumer pro,lem:
\rod(+erBprod(+er T#read/ will prod(+e t#e ite"s to t#e V(e(e and
+ons("erB+ons("er t#read/ will +ons("e t#e ite"s fro" t#e V(e(e. If t#e V(e(e is
e"pty t#en +ons("er #as to +all waitB/ "et#od on t#e V(e(e ob,e+t t#en it will entered
into waitin! state.
After prod(+in! t#e ite"s prod(+er T#read +all notifyB/ "et#od on t#e V(e(e to !ive
notifi+ation so t#at +ons("er T#read will !et t#at notifi+ation and +ons("e ite"s.
'iagram:


256

Example:

/otif( vs notif(7ll:;:
@e +an (se notifyB/ "et#od to !ive notifi+ation for only one T#read. If "(ltiple
T#reads are waitin! t#en only one T#read will !et t#e +#an+e and re"ainin! T#reads
#as to wait for f(rt#er notifi+ation. 6(t w#i+# T#read will be notifyBinfor"/ we +anAt
eEpe+t eEa+tly it depends on *%.
@e +an (se notifyAllB/ "et#od to !ive t#e notifi+ation for all waitin! T#reads. All
waitin! T#reads will be notified and will be eEe+(ted one by one.
/ote: In w#i+# ob,e+t we are +allin! waitB/- notifyB/ and notifyAllB/ "et#ods t#at +orrespondin!
ob,e+t lo+? we #ave to !et b(t not ot#er ob,e+t lo+?s.
Example:

'ead lo$+:
If 2 T#reads are waitin! for ea+# ot#er foreverBwit#o(t end/ s(+# type of
sit(ationBinfinite waitin!/ is +alled dead lo+?.
T#ere are no resol(tion te+#niV(es for dead lo+? b(t several preventionBavoidan+e/
te+#niV(es are possible.

257

Cyn+#roni0ed ?eyword is t#e +a(se for deadlo+? #en+e w#enever we are (sin!
syn+#roni0ed ?eyword we #ave to ta?e spe+ial +are.
Example:
+lass A
7
p(bli+ syn+#roni0ed void fooB6 b/
7
Cyste".o(t.printlnBNT#read1 starts eEe+(tion of fooB/ "et#odN/9
try
7
T#read.sleepB2)))/9
=
+at+# BInterr(pted<E+eption e/
7=
Cyste".o(t.printlnBNT#read1 tryin! to +all b.lastB/N/9
b.lastB/9
=
p(bli+ syn+#roni0ed void lastB/
7
Cyste".o(t.printlnBNinside A- t#is is lastB/"et#odN/9
=
=
+lass 6
7
p(bli+ syn+#roni0ed void barBA a/
7
Cyste".o(t.printlnBNT#read2 starts eEe+(tion of barB/ "et#odN/9
try
7
T#read.sleepB2)))/9
=
+at+# BInterr(pted<E+eption e/
7=
Cyste".o(t.printlnBNT#read2 tryin! to +all a.lastB/N/9
a.lastB/9
=
p(bli+ syn+#roni0ed void lastB/
7

25$

Cyste".o(t.printlnBNinside 6- t#is is lastB/ "et#odN/9
=
=
+lass DeadLo+? i"ple"ents R(nnable
7
A a8new AB/9
6 b8new 6B/9
DeadLo+?B/
7
T#read t8new T#readBt#is/9
t.startB/9
a.fooBb/9JJ"ain t#read
=
p(bli+ void r(nB/
7
b.barBa/9JJ+#ild t#read
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
new DeadLo+?B/9JJ"ain t#read
=
=
!utput:
T#read1 starts eEe+(tion of fooB/ "et#od
T#read2 starts eEe+(tion of barB/ "et#od
T#read2 tryin! to +all a.lastB/
T#read1 tryin! to +all b.lastB/
JJ#ere +(rsor always waitin!.
'aemon 8#reads:
T#e T#reads w#i+# are eEe+(tin! in t#e ba+?!ro(nd are +alled dae"on T#reads. T#e
"ain ob,e+tive of dae"on T#reads is to provide s(pport for non dae"on T#reads.
Example:
^arba!e +olle+tor
@e +an +#e+? w#et#er t#e T#read is dae"on or not by (sin! isDae"onB/ "et#od.
pu,li$ final ,oolean is'aemon:;E
@e +an +#an!e dae"on nat(re of a T#read by (sin! setDae"on B/ "et#od.
pu,li$ final void set'aemon:,oolean ,;E

25&

6(t we +an +#an!e dae"on nat(re before startin! T#read only. T#at is after startin! t#e
T#read if we are tryin! to +#an!e t#e dae"on nat(re we will !et R.< sayin!
Ille!alT#readCtate<E+eption.
%ain T#read is always non dae"on and we +anAt +#an!e its dae"on nat(re be+a(se itAs
already started at t#e be!innin! only.
%ain T#read is always non dae"on and for t#e re"ainin! T#reads dae"on nat(re will
be in#eritin! fro" parent to +#ild t#at is if t#e parent is dae"on +#ild is also dae"on
and if t#e parent is non dae"on t#en +#ild is also non dae"on.
@#enever t#e last non dae"on T#read ter"inates a(to"ati+ally all dae"on T#reads
will be ter"inated.
Example:
+lass %yT#read eEtends T#read
7
p(bli+ void r(nB/
7
forBint i8)9iZ1)9iFF/
7
Cyste".o(t.printlnBNla0y t#readN/9
try
7
T#read.sleepB2)))/9
=
+at+# BInterr(pted<E+eption e/
7=
=
=
=
+lass Dae"onT#readDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
%yT#read t8new %yT#readB/9
t.setDae"onBtr(e/9 1
t.startB/9
Cyste".o(t.printlnBNend of "ain T#readN/9
=
=


26)

!utput:
<nd of "ain T#read
La0y t#read
If we are +o""entin! line 1 t#en bot# "ain and +#ild T#reads are non dae"on and
#en+e bot# will be eEe+(ted (ntil t#ey +o"pletion.
If we are not +o""entin! line 1 t#en "ain T#read is non dae"on and +#ild T#read is
dae"on and #en+e w#enever "ain T#read ter"inates a(to"ati+ally +#ild T#read will be
ter"inated.
'eadlo$+ vs 2tarvation:
A lon! waitin! of a T#read w#i+# never ends is +alled deadlo+?.
A lon! waitin! of a T#read w#i+# ends at +ertain point is +alled starvation.
A low priority T#read #as to wait (ntil +o"pletin! all #i!# priority T#reads.
T#is lon! waitin! of T#read w#i+# ends at +ertain point is +alled starvation.
6o% to +ill a 8#read in t#e middle of t#e line&
@e +an +all stopB/ "et#od to stop a T#read in t#e "iddle t#en it will be entered into
dead state i""ediately.
pu,li$ final void stop:;E
stopB/ "et#od #as been depre+ated and #en+e not re+o""ended to (se.
suspend and resume met#ods:
A T#read +an s(spend anot#er T#read by (sin! s(spendB/ "et#od t#en t#at T#read will
be pa(sed te"porarily.
A T#read +an res("e a s(spended T#read by (sin! res("eB/ "et#od t#en s(spended
T#read will +ontin(e its eEe+(tion.
1; pu,li$ final void suspend:;E
2; pu,li$ final void resume:;E
6ot# "et#ods are depre+ated and not re+o""ended to (se.
R7*E $ondition:
<Ee+(tin! "(ltiple T#reads si"(ltaneo(sly and +a(sin! data in+onsisten+y proble"s
is not#in! b(t Ra+e +ondition we +an resolve ra+e +ondition by (sin! syn+#roni0ed
?eyword.






261

Life $($le of a 8#read:

"#at is t#e differen$e ,et%een extends 8#read and implements Runna,le&
<Etends T#read is (sef(l to override t#e p(bli+ void r(nB/ "et#od of T#read +lass.
I"ple"ents R(nnable is (sef(l to i"ple"ent p(bli+ void r(nB/ "et#od of R(nnable
interfa+e.
Extends 8#readH implements Runna,le %#i$# one is advantage&
If we eEtend T#read +lass- t#ere is no s+ope to eEtend anot#er +lass.
Example:
*lass =(*lass extends FrameH8#readWWinvalid
If we write i"ple"ents R(nnable still t#ere is a s+ope to eEtend one "ore +lass.
Example:
1; $lass =(*lass extends 8#read implements Runna,le
2; $lass =(*lass extends Frame implements Runna,le
6o% $an (ou stop a 8#read %#i$# is running&
2tep 1:
De+lare a boolean type variable and store false in t#at variable.
,oolean stopMfalseE
2tep 2:
If t#e variable be+o"es tr(e ret(rn fro" t#e r(nB/ "et#od.

262

If:stop; returnE
2tep 3:
@#enever to stop t#e T#read store tr(e into t#e variable.
2(stem9in9read:;EWWpress enter
!,j9stopMtrueE
Zuestions:
1; "#at is a 8#read&
2; "#i$# 8#read ,( default runs in ever( java program&
Ans. 6y defa(lt "ain T#read r(ns in every ,ava pro!ra".
3; "#at is t#e default priorit( of t#e 8#read&
4; 6o% $an (ou $#ange t#e priorit( num,er of t#e 8#read&
5; "#i$# met#od is exe$uted ,( an( 8#read&
Ans. A T#read eEe+(tes only p(bli+ void r(nB/ "et#od.
6; 6o% $an (ou stop a 8#read %#i$# is running&
; Explain t#e t%o t(pes of multitas+ing&
B; "#at is t#e differen$e ,et%een a pro$ess and a 8#read&
V; "#at is 8#read s$#eduler&
15; Explain t#e s(n$#roni4ation of 8#reads&
11; "#at is t#e differen$e ,et%een s(n$#roni4ed ,lo$+ and s(n$#roni4ed +e(%ord&
12; "#at is 8#read deadlo$+& 6o% $an (ou resolve deadlo$+ situation&
13; "#i$# met#ods are used in 8#read $ommuni$ation&
14; "#at is t#e differen$e ,et%een notif(:; and notif(7ll:; met#ods&
15; "#at is t#e differen$e ,et%een sleep:; and %ait:; met#ods&
16; Explain t#e life $($le of a 8#read&
1; "#at is daemon 8#read&










263

0ava9lang 3a$+age
1/ Ib,e+t
2/ Ctrin!
3/ Ctrin!6(ffer
4/ Ctrin!6(ilder
5/ @rapper 'lasses
6/ A(toboEin! and A(to(nboEin!
Hor writin! any ,ava pro!ra" t#e "ost +o""only reV(ired +lasses and interfa+es are
en+aps(lated in t#e separate pa+?a!e w#i+# is not#in! b(t ,ava.lan! pa+?a!e.
It is not reV(ired to i"port ,ava.lan! pa+?a!e in o(r pro!ra" be+a(se it is available by
defa(lt to every ,ava pro!ra".
T#e followin! are so"e of i"portant +lasses present in ,ava.lan! pa+?a!e.
1. Ib,e+t
2. Ctrin!
3. Ctrin!6(ffer
4. Ctrin!6(ilder
5. All wrapper +lasses
6. <Ee+ption A\I
7. T#read A\Ie.et+
"#at is (our favorite pa$+age&
"#( java9lang is (our favorite pa$+age&
It is not reV(ired to i"port lan! pa+?a!e eEpli+itly b(t t#e re"ainin! pa+?a!es we #ave
to i"port.
0ava9lang9!,je$t $lass: Hor any ,ava ob,e+t w#et#er it is predefine or +(sto"i0ed t#e "ost
+o""only reV(ired "et#ods are en+aps(lated into a separate +lass w#i+# is not#in! b(t ob,e+t
+lass.
As ob,e+t +lass a+ts as a root Bor/ parent Bor/ s(per for all ,ava +lasses- by defa(lt its
"et#ods are available to every ,ava +lass.
T#e followin! is t#e list of all "et#ods present in ,ava.lan! Ib,e+t +lass.
1/ p(bli+ Ctrin! toCtrin!B/9
2/ p(bli+ native int #as#'odeB/9
3/ p(bli+ boolean eV(alsBIb,e+t o/9
4/ prote+ted native Ib,e+t +loneB/t#rows 'lone:otC(pported<E+eption9
5/ p(bli+ final 'lassZWT !et'lassB/9
6/ prote+ted void finali0eB/t#rows T#rowable9
7/ p(bli+ final void waitB/t#rows Interr(pted<E+eption9
$/ p(bli+ final native void waitB/t#rows Interr(pted<E+eption9
&/ p(bli+ final void waitBlon! "s-int ns/t#rows Interr(pted<E+eption9

264

1)/ p(bli+ final native void notifyB/9
11/ p(bli+ final native void notifyAllB/9
to2tring:; met#od: @e +an (se t#is "et#od to !et strin! representation of an ob,e+t.
@#enever we are try to print any ob,e+t referen+e internally toCtrin!B/ "et#od will be
eEe+(ted.
If o(r +lass doesnAt +ontain toCtrin!B/ "et#od t#en Ib,e+t +lass toCtrin!B/ "et#od will be
eEe+(ted.
Example: Cyste".o(t.printlnBs1/9 s(perBs1.toCtrin!B//9
Example 1:
+lass Ct(dent
7
Ctrin! na"e9
int rollno9
Ct(dentBCtrin! na"e-int rollno/
7
t#is.na"e8na"e9
t#is.rollno8rollno9
=
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Ct(dent s18new Ct(dentBNvi,ayab#as?arN-1)1/9
Ct(dent s28new Ct(dentBNb#as?arN-1)2/9
Cyste".o(t.printlnBs1/9
Cyste".o(t.printlnBs1.toCtrin!B//9
Cyste".o(t.printlnBs2/9
=
=
!utput:
Ct(dent[3e25a5
Ct(dent[3e25a5
Ct(dent[1&$21f
In t#e above pro!ra" Ib,e+t +lass toCtrin!B/ "et#od !ot eEe+(ted w#i+# is
i"ple"ented as follows.
p(bli+ Ctrin! toCtrin!B/ 7
ret(rn !et'lassB/.!et:a"eB/ F N[N F Inte!er.toSeECtrin!B#as#'odeB//9
=
To provide o(r own Ctrin! representation we #ave to override toCtrin!B/ "et#od in o(r
+lass.
Hor eEa"ple w#enever we are try to print st(dent referen+e to print #is a na"e and roll
no we #ave to override toCtrin!B/ "et#od as follows.
p(bli+ Ctrin! toCtrin!B/7
ret(rn na"eFN........NFrollno9
=

265

In Ctrin! +lass- Ctrin!6(ffer- Ctrin!6(ilder- wrapper +lasses and in all +olle+tion +lasses
toCtrin!B/ "et#od is overridden for "eanin!f(l strin! representation. Sen+e in o(r
+lasses also #ig#l( re$ommended to override to2tring:; met#od.
Example 2:
+lass Test
7
p(bli+ Ctrin! toCtrin!B/
7
ret(rn NTestN9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Inte!er i8new Inte!erB1)/9
Ctrin! s8new Ctrin!BNb#as?arN/9
Test t8new TestB/9
Cyste".o(t.printlnBi/9
Cyste".o(t.printlnBs/9
Cyste".o(t.printlnBt/9
==
!utput:
1)
6#as?ar
Test
#as#*ode:; met#od:
Hor every ob,e+t ,v" will !enerate a (niV(e n("ber w#i+# is not#in! b(t #as#'ode.
#as#'ode of an ob,e+t will be (sed by ,v" w#ile savin! ob,e+ts into Sas#Cet- Sas#%ap-
and Sas#table et+.
If t#e ob,e+ts are stored a++ordin! to #as#'ode sear+#in! will be+o"e very effi+ient
BT#e "ost powerf(l sear+# al!orit#" is #as#in! w#i+# will wor? based on #as#'ode/.
If we didnAt override #as#'odeB/ "et#od t#en Ib,e+t +lass #as#'odeB/ "et#od will be
eEe+(ted w#i+# !enerates #as#'ode based on address of t#e ob,e+t b(t it doesnAt "ean
#as#'ode represents address of t#e ob,e+t.
6ased on o(r pro!ra""in! reV(ire"ent we +an override #as#'odeB/ "et#od in o(r
+lass.
Iverridin! #as#'odeB/ "et#od is said to be proper if and only if for every ob,e+t we
#ave to !enerate a (niV(e n("ber.
Example 3:
+lass Ct(dent
7
p(bli+ int #as#'odeB/
7
ret(rn 1))9
==
It is i"proper way of overridin!
+lass Ct(dent
7
int rollno9
p(bli+ int #as#'odeB/
7
ret(rn rollno9
==

266

#as#'odeB/ "et#od be+a(se for every
ob,e+t we are !eneratin! sa"e
#as#+ode.
It is proper way of overridin!
#as#+odeB/ "et#od be+a(se for every
ob,e+t we are !eneratin! a different
#as#+ode.
to2tring:; met#od vs #as#*ode:; met#od:
+lass Test
7
int i9
TestBint i/
7
t#is.i8i9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Test t18new TestB1)/9
Test t28new TestB1))/9
Cyste".o(t.printlnBt1/9
Cyste".o(t.printlnBt2/9
=
=
Ib,e+t88toCtrin!B/ +alled.
Ib,e+t88#as#'odeB/ +alled.
In t#is +ase Ib,e+t +lass toCtrin!B/
"et#od !ot eEe+(ted w#i+# is internally
+alls Ib,e+t +lass #as#'odeB/ "et#od.
+lass Test7
int i9
TestBint i/7
t#is.i8i9
=
p(bli+ int #as#'odeB/7
ret(rn i9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Test t18new TestB1)/9
Test t28new TestB1))/9
Cyste".o(t.printlnBt1/9
Cyste".o(t.printlnBt2/9
==
Ib,e+t88toCtrin!B/ +alled.
Test88#as#'odeB/ +alled.
In t#is +ase Ib,e+t +lass toCtrin!B/
"et#od !ot eEe+(ted w#i+# is
internally +alls Test +lass #as#'odeB/
"et#od.
Example 4:
+lass Test
7
int i9
TestBint i/
7
t#is.i8i9
=
p(bli+ int #as#'odeB/7
ret(rn i9
=
p(bli+ Ctrin! toCtrin!B/
7
ret(rn iFNN9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Test t18new TestB1)/9
Test t28new TestB1))/9
Cyste".o(t.printlnBt1/9

267

Cyste".o(t.printlnBt2/9
=
=
!utput:
1)
1))
In t#is +ase Test +lass toCtrin!B/ "et#od !ot eEe+(ted.
/ote: if we are !ivin! optr(rni(ty to Ib,e+t +lass toCtrin!B/ "et#od it internally +alls #as#'odeB/
"et#od. 6(t if we are overridin! toCtrin!B/ "et#od it "ay not +all #as#'odeB/ "et#od.
@e +an (se toCtrin!B/ "et#od w#ile printin! ob,e+t referen+es and we +an (se
#as#'odeB/ "et#od w#ile savin! ob,e+ts into Sas#Cet or Sas#table or Sas#%ap.
eAuals:; met#od:
@e +an (se t#is "et#od to +#e+? eV(ivalen+e of two ob,e+ts.
If o(r +lass doesnAt +ontain .eV(alsB/ "et#od t#en ob,e+t +lass .eV(alsB/ "et#od will be
eEe+(ted w#i+# is always "eant for referen+e +o"pressionDaddress +o"pression>.
Example 5:
+lass Ct(dent
7
Ctrin! na"e9
int rollno9
Ct(dentBCtrin! na"e-int rollno/
7
t#is.na"e8na"e9
t#is.rollno8rollno9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Ct(dent s18new Ct(dentBNvi,ayab#as?arN-1)1/9
Ct(dent s28new Ct(dentBNb#as?arN-1)2/9
Ct(dent s38new Ct(dentBNvi,ayab#as?arN-1)1/9
Ct(dent s48s19
Cyste".o(t.printlnBs1.eV(alsBs2//9
Cyste".o(t.printlnBs1.eV(alsBs3//9
Cyste".o(t.printlnBs1.eV(alsBs4//9
==
!utput:
Halse
Halse
Tr(e
'iagram:



26$

In t#e above pro!ra" Ib,e+t +lass .eV(alsB/ "et#od !ot eEe+(ted w#i+# is always "eant
for referen+e +o"pression t#at is if two referen+es pointin! to t#e sa"e ob,e+t t#en
only .eV(alsBB/ "et#od ret(rns tr(e.
In ob,e+t +lass .eV(alsB/ "et#od is i"ple"ented as follows w#i+# is "eant for referen+e
+o"pression.
p(bli+ boolean eV(alsBIb,e+t ob,/ 7
ret(rn Bt#is 88 ob,/9
=
6ased on o(r pro!ra""in! reV(ire"ent we +an override .eV(alsB/ "et#od for +ontent
+o"pression p(rpose.
@#ile overridin! .eV(alsB/ "et#od we #ave to +onsider t#e followin! t#in!s.
1/ %eanin! of +ontent +o"pression li?e w#et#er t#e na"es are eV(al Bor/ roll n("bers
Bor/ bot# are eV(al.
2/ If we are passin! #etero!eneo(s ob,e+t o(r .eV(alsB/ "et#od s#o(ld ret(rn false t#at is
we #ave to #andle *lass*astEx$eption to ret(rn false.
3/ If we are providin! n(ll ar!("ent o(r .eV(alsB/ "et#od s#o(ld ret(rn false t#at is we
#ave to #andle /ull3ointerEx$eption to ret(rn false.
T#e followin! is t#e proper way of overridin! .eV(alsB/ "et#od for +ontent +o"pression
in Ct(dent +lass.
Example 6:
+lass Ct(dent
7
Ctrin! na"e9
int rollno9
Ct(dentBCtrin! na"e-int rollno/
7
t#is.na"e8na"e9
t#is.rollno8rollno9
=
p(bli+ boolean eV(alsBIb,e+t ob,/
7
try7
Ctrin! na"e18t#is.na"e9
int rollno18t#is.rollno9
Ct(dent s28BCt(dent/ob,9
Ctrin! na"e28s2.na"e9
int rollno28s2.rollno9
ifBna"e1.eV(alsBna"e2/ccrollno188rollno2/
7
ret(rn tr(e9
=
else ret(rn false9
=

26&

+at+#B'lass'ast<E+eption e/
7
ret(rn false9
=
+at+#B:(ll\ointer<E+eption e/
7
ret(rn false9
=
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Ct(dent s18new Ct(dentBNvi,ayab#as?arN-1)1/9
Ct(dent s28new Ct(dentBNb#as?arN-1)2/9
Ct(dent s38new Ct(dentBNvi,ayab#as?arN-1)1/9
Ct(dent s48s19
Cyste".o(t.printlnBs1.eV(alsBs2//9
Cyste".o(t.printlnBs1.eV(alsBs3//9
Cyste".o(t.printlnBs1.eV(alsBs4//9
Cyste".o(t.printlnBs1.eV(alsBNvi,ayab#as?arN//9
Cyste".o(t.printlnBs1.eV(alsBNn(llN//9
=
=
!utput:
Halse
Tr(e
Tr(e
Halse
Halse
2implified version of 9eAuals:; met#od:
p(bli+ boolean eV(alsBIb,e+t o/7
try7
Ct(dent s28BCt(dent/o9
ifBna"e.eV(alsBs2.na"e/ccrollno88s2.rollno/7
ret(rn tr(e9=
else ret(rn false9
=
+at+#B'lass'ast<E+eption e/
7
ret(rn false9
=
+at+#B:(ll\ointer<E+eption e/
7
ret(rn false9
==


27)

=ore simplified version of 9eAuals:; met#od:
p(bli+ boolean eV(alsBIb,e+t o/
7
ifBt#is88o/
ret(rn tr(e9
ifBo instan+eof Ct(dent/
7
Ct(dent s28BCt(dent/o9
ifBna"e.eV(alsBs2.na"e/ccrollno88s2.rollno/
ret(rn tr(e9
else
ret(rn false9
=
ret(rn false9
=
Example :
+lass Ct(dent
7
Ctrin! na"e9
int rollno9
Ct(dentBCtrin! na"e-int rollno/
7
t#is.na"e8na"e9
t#is.rollno8rollno9
=
p(bli+ boolean eV(alsBIb,e+t o/
7
ifBt#is88o/
ret(rn tr(e9
ifBo instan+eof Ct(dent/
7
Ct(dent s28BCt(dent/o9
ifBna"e.eV(alsBs2.na"e/ccrollno88s2.rollno/
ret(rn tr(e9
else
ret(rn false9
=
ret(rn false9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
Ct(dent s8new Ct(dentBNvi,ayab#as?arN-1)1/9
Inte!er i8new Inte!erB1)/9
Cyste".o(t.printlnBs.eV(alsBi//9
=

271

=
!utput:
Halse
To "a?e .eV(alsB/ "et#od "ore effi+ient we #ave to pla+e t#e followin! +ode at t#e top
inside .eV(alsB/ "et#od.
ifBt#is88o/
ret(rn tr(e9
'iagram:

If 2 referen+es pointin! to t#e sa"e ob,e+t t#en .eV(alsB/ "et#od ret(rn tr(e dire+tly
wit#o(t perfor"in! any +ontent +o"pression t#is approa+# i"proves perfor"an+e of
t#e syste".
Relations#ip ,et%een 9eAuals:; met#od and MM:dou,le eAual operator;:
1/ If r188r2 is tr(e t#en r1.eV(alsBr2/ is always tr(e t#at is if two ob,e+ts are eV(al by
do(ble eV(al operator t#en t#ese ob,e+ts are always eV(al by .eV(alsB/ "et#od also.
2/ If r188r2 is false t#en we +anAt +on+l(de anyt#in! abo(t r1.eV(alsBr2/ it "ay ret(rn tr(e
Bor/ false.
3/ If r1.eV(alsBr2/ is tr(e t#en we +anAt +on+l(de anyt#in! abo(t r188r2 it "ay ret(rns tr(e
Bor/ false.
4/ If r1.eV(alsBr2/ is false t#en r188r2 is always false.
'ifferen$es ,et%een MM :dou,le eAual operator; and 9eAuals:; met#od&
88Bdo(ble eV(al operator/ .eV(alsB/ "et#od
1/ It is an operator appli+able for bot#
pri"itives and ob,e+t referen+es.
1/ It is a "et#od appli+able only for
ob,e+t referen+es b(t not for
pri"itives.
2/ In t#e +ase of pri"itives 88 Bdo(ble
eV(al operator/ "eant for +ontent
+o"pression- b(t in t#e +ase of ob,e+t
referen+es 88 operator "eant for
referen+e +o"pression.
2/ 6y defa(lt .eV(alsB/ "et#od present in
ob,e+t +lass is also "eant for referen+e
+o"pression.
3/ @e +anAt override88 operator for
+ontent +o"pression in ob,e+t
referen+es.
3/ @e +an override .eV(alsB/ "et#od for
+ontent +o"pression.
4/ If t#ere is no relations#ip between
ar!("ent types t#en we will !et
+o"pile ti"e error sayin! in+o"patible
types.
4/ If t#ere is no relations#ip between
ar!("ent types t#en .eV(alsB/ "et#od
si"ply ret(rns false and we wonAt !et
any +o"pile ti"e error and r(nti"e
error.
5/ Hor any ob,e+t referen+e r-
r88n(ll is always false.
5/ Hor any ob,e+t referen+e r-
r.eV(alsBn(ll/ is also ret(rns false.

272

/ote: in !eneral we +an (se 88 Bdo(ble eV(al operator/ for referen+e +o"pression w#ereas
.eV(alsB/ "et#od for +ontent +o"pression.
*ontra$t ,et%een 9eAuals:; met#od and #as#*ode:; met#od:
1/ If 2 ob,e+ts are eV(al by .eV(alsB/ "et#od +o"p(lsory t#eir #as#+odes "(st be eV(al
Bor/ sa"e. T#at is
If r1.eV(alsBr2/ is tr(e t#en r1.#as+odeB/88r2.#as#+odeB/ "(st be tr(e.
2/ If 2 ob,e+ts are not eV(al by .eV(alsB/ "et#od t#en t#ere are no restri+tions on
#as#'odeB/ "et#ods. T#ey "ay be sa"e Bor/ "ay be different. T#at is
If r1.eV(alsBr2/ is false t#en r1.#as#'odeB/88r2.#as#'odeB/ "ay be sa"e Bor/ "ay be
different.
3/ If #as#+odes of 2 ob,e+ts are eV(al we +anAt +on+l(de anyt#in! abo(t .eV(alsB/ "et#od it
"ay ret(rns tr(e Bor/ false. T#at is
If r1.#as#'odeB/88r2.#as#'odeB/ is tr(e t#en r1.eV(alsBr2/ "et#od "ay ret(rns tr(e Bor/
false.
4/ If #as#+odes of 2 ob,e+ts are not eV(al t#en t#ese ob,e+ts are always not eV(al by
.eV(alsB/ "et#od also. T#at is
If r1.#as#'odeB/88r2.#as#'odeB/ is false t#en r1.eV(alsBr2/ is always false.
To "aintain t#e above +ontra+t between .eV(alsB/ and #as#'odeB/ "et#ods w#enever
we are overridin! .eV(alsB/ "et#od +o"p(lsory we s#o(ld override #as#'odeB/ "et#od.
iolation leads to no +o"pile ti"e error and r(nti"e error b(t it is not !ood
pro!ra""in! pra+ti+e.
'onsider t#e followin! person +lass.
3rogram:
+lass \erson
7
Ctrin! na"e9
int a!e9
\ersonBCtrin! na"e-int a!e/
7
t#is.na"e8na"e9
t#is.a!e8a!e9
=
p(bli+ boolean eV(alsBIb,e+t o/
7
ifBt#is88o/
ret(rn tr(e9
ifBo instan+eof \erson/
7
\erson p28B\erson/o9
ifBna"e.eV(alsBp2.na"e/cca!e88p2.a!e/
ret(rn tr(e9
else
ret(rn false9
=

273

ret(rn false9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
\erson p18new \ersonBNvi,ayab#as?arN-1)1/9
\erson p28new \ersonBNvi,ayab#as?arN-1)1/9
Inte!er i8new Inte!erB1)2/9
Cyste".o(t.printlnBp1.eV(alsBp2//9
Cyste".o(t.printlnBp1.eV(alsBi//9
==
!utput:
Tr(e
Halse
"#i$# of t#e follo%ing is appropriate %a( of overriding #as#*ode:; met#od&


6ased on w#atever t#e para"eters we override K.eV(alsB/ "et#odL we s#o(ld (se sa"e
para"eters w#ile overridin! #as#'odeB/ "et#od also.
/ote: in all wrapper +lasses- in strin! +lass- in all +olle+tion +lasses .eV(alsB/ "et#od is
overridden for +ontent +o"pression in o(r +lasses also it is #i!#ly re+o""ended to override
.eV(alsB/ "et#od.
"#i$# of t#e follo%ing is valid&
1/ If #as# 'odes of 2 ob,e+ts are not eV(al t#en .eV(alsB/ "et#od always ret(rn false.Bvalid/
Example:
+lass Test
7
int i9
TestBint i/
7
t#is.i8i9
=
p(bli+ int #as#'odeB/
7
ret(rn i9
=
p(bli+ Ctrin! toCtrin!B/
7
ret(rn iFNN9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7

274

Test t18new TestB1)/9
Test t28new TestB2)/9
Cyste".o(t.printlnBt1.#as#'odeB//9JJ1)
Cyste".o(t.printlnBt2.#as#'odeB//9JJ2)
Cyste".o(t.printlnBt1.#as#'odeB/88t2.#as#'odeB//9JJfalse
Cyste".o(t.printlnBt1.eV(alsBt2//9JJfalse
=
=
2/ If 2 ob,e+ts are eV(al by 88 operator t#en t#eir #as# +odes "(st be sa"e.Bvalid/
Example:
+lass Test
7
int i9
TestBint i/
7
t#is.i8i9
=
p(bli+ int #as#'odeB/
7
ret(rn i9
=
p(bli+ Ctrin! toCtrin!B/
7
ret(rn iFNN9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t18new TestB1)/9
Test t28t19
Cyste".o(t.printlnBt1.#as#'odeB//9JJ1)
Cyste".o(t.printlnBt2.#as#'odeB//9JJ1)
Cyste".o(t.printlnBt188t2/9JJtr(e

=
=
3/ If 88 operator ret(rns false t#en t#eir #as# +odesB"ay be sa"e Bor/ "ay be different/
"(st be different.Binvalid/
Example:
+lass Test
7
int i9
TestBint i/

275

7
t#is.i8i9
=
p(bli+ int #as#'odeB/
7
ret(rn i9
=
p(bli+ Ctrin! toCtrin!B/
7
ret(rn iFNN9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test t18new TestB1)/9
Test t28new TestB1)/9
Cyste".o(t.printlnBt1.#as#'odeB//9JJ1)
Cyste".o(t.printlnBt2.#as#'odeB//9JJ1)
Cyste".o(t.printlnBt188t2/9JJfalse
=
=
4/ If #as#+odes of 2 ob,e+ts are eV(al t#en t#ese ob,e+ts are always eV(al by 88 operator
also.Binvalid/
*lone :; met#od:
T#e pro+ess of +reatin! eEa+tly d(pli+ate ob,e+t is +alled +lonin!.
T#e "ain ob,e+tive of +lonin! is to "aintain ba+?(p.
T#at is if so"et#in! !oes wron! we +an re+over t#e sit(ation by (sin! ba+?(p +opy.
@e +an perfor" +lonin! by (sin! +loneB/ "et#od of Ib,e+t +lass.
prote$ted native o,je$t $lone:; t#ro%s *lone/ot2upportedEx$eptionE
Example:
+lass Test i"ple"ents 'loneable
7
int i81)9
int ,82)9
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows 'lone:otC(pported<E+eption
7
Test t18new TestB/9
Test t28BTest/t1.+loneB/9
t2.i8$$$9
t2.,8&&&9
Cyste".o(t.printlnBt1.iFN444444444444444NFt1.,/9
Cyste".o(t.printlnBt2.iFN444444444444444NFt2.,/9
=

276

=
!utput:
1)4444444444444442)
$$$444444444444444&&&
'iagram:

@e +an perfor" +lonin! only for 'loneable ob,e+ts.
An ob,e+t is said to be 'loneable if and only if t#e +orrespondin! +lass i"ple"ents
'loneable interfa+e.
'loneable interfa+e present in ,ava.lan! pa+?a!e and does not +ontain any "et#ods. It is
a "ar?er interfa+e w#ere t#e reV(ired ability will be provided a(to"ati+ally by t#e *%.
2#allo% $loning vs deep $loning:
T#e pro+ess of +reatin! ,(st d(pli+ate referen+e variable b(t not d(pli+ate ob,e+t is
+alled s#allow +lonin!.
Example:
Test t18new TestB/9
Test t28t19
'iagram:

T#e pro+ess of +reatin! eEa+tly independent d(pli+ate ob,e+t is +alled deep +lonin!.
Example:
Test t18new TestB/9
Test t28BTest/t1.+loneB/9
Cyste".o(t.printlnBt188t2/9JJfalse
Cyste".o(t.printlnBt1.#as#'odeB/88t2.#as#'odeB//9JJfalse
'iagram:

'lonin! by defa(lt deep +lonin!.
get*lass:; met#od:
T#is "et#od ret(rns r(nti"e +lass definition of an ob,e+t.
Example:
+lass Test i"ple"ents 'loneable
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows 'lone:otC(pported<E+eption
7
Ib,e+t o8new Ctrin!BNb#as?arN/9

277

Cyste".o(t.printlnBNR(nti"e ob,e+t type of o is .NFo.!et'lassB/.!et:a"eB//9
=
=
!utput:
R(nti"e ob,e+t type of o is. ,ava.lan!. Ctrin!
2tring
*ase 1:
Ctrin! s8new Ctrin!BNb#as?arN/9
s.+on+atBNsoftwareN/9
Cyste".o(t.printlnBs/9JJb#as?ar
In+e we +reate a Ctrin! ob,e+t we
+anAt perfor" any +#an!es in t#e
eEistin! ob,e+t. If we are try to perfor"
any +#an!es wit# t#ose +#an!es a new
ob,e+t will be +reated. T#is be#avior is
+alled i""(tability of t#e Ctrin! ob,e+t.
'iagram:

Ctrin!6(ffer sb8new Ctrin!6(fferBNb#as?arN/9
sb.appendBNsoftwareN/9
Cyste".o(t.printlnBsb/9
In+e we +reated a Ctrin!6(ffer ob,e+t
we +an perfor" any +#an!es in t#e
eEistin! ob,e+t. T#is be#avior is +alled
"(tability of t#e Ctrin!6(ffer ob,e+t.
'iagram:

*ase 2:
Ctrin! s18new Ctrin!BNb#as?arN/9
Ctrin! s28new Ctrin!BNb#as?arN/9
Cyste".o(t.printlnBs188s2/9JJfalse
Cyste".o(t.printlnBs1.eV(alsBs2//9JJtr(e
In Ctrin! +lass .eV(alsB/ "et#od is
overridden for +ontent +o"pression
#en+e if t#e +ontent is sa"e .eV(alsB/
"et#od ret(rns tr(e even t#o(!#
ob,e+ts are different.
Ctrin!6(ffer sb18new Ctrin!6(fferBNb#as?arN/9
Ctrin!6(ffer sb28new Ctrin!6(fferBNb#as?arN/9
Cyste".o(t.printlnBsb188sb2/9JJfalse
Cyste".o(t.printlnBsb1.eV(alsBsb2//9JJfalse
In Ctrin!6(ffer +lass .eV(alsB/ "et#od
is not overridden for +ontent
+o"pression #en+e Ib,e+t +lass
.eV(alsB/ "et#od !ot eEe+(ted w#i+# is
always "eant for referen+e
+o"pression. Sen+e if ob,e+ts are
different .eV(alsB/ "et#od ret(rns
false even t#o(!# +ontent is sa"e.
*ase 3:
Ctrin! s8new Ctrin!BNb#as?arN/9
In t#is +ase two ob,e+ts will be +reated
one is on t#e #eap t#e ot#er one is
C'\BCtrin! +onstant pool/ and s is
always pointin! to #eap ob,e+t.
Ctrin! s8Nb#as?arN9
In t#is +ase only one ob,e+t will be
+reated in C'\ and s is always referrin!
t#at ob,e+t.
'iagram:

27$

'iagram:


/ote:
1/ Ib,e+t +reation in C'\ is always optional 1
st
*% will +#e+? is any ob,e+t already +reated
wit# reV(ired +ontent or not. If it is already available t#en it will re(se eEistin! ob,e+t
instead of +reatin! new ob,e+t. If it is not already t#ere t#en only a new ob,e+t will be
+reated. Sen+e t#ere is no +#an+e of eEistin! 2 ob,e+ts wit# sa"e +ontent on C'\ t#at is
d(pli+ate ob,e+ts are not allowed in C'\.
2/ ^arba!e +olle+tor +anAt a++ess C'\ area #en+e even t#o(!# ob,e+t doesnAt #ave any
referen+e still t#at ob,e+t is not eli!ible for ^' if it is present in C'\.
3/ All C'\ ob,e+ts will be destroyed at t#e ti"e of *% s#(tdown a(to"ati+ally.
Example 1:
Ctrin! s18new Ctrin!BNb#as?arN/9
Ctrin! s28new Ctrin!BNb#as?arN/9
Ctrin! s38Nb#as?arN9
Ctrin! s48Nb#as?arN9
'iagram:

Example 2:
Ctrin! s8new Ctrin!BNb#as?arN/9
s.+on+atBNsoftwareN/9
s8s.+on+atBNsol(tionsN/9
s8Nb#as?arsoftN9
'iagram:


27&

Hor every Ctrin! 'onstant one ob,e+t will be +reated in C'\. 6e+a(se of r(nti"e
operation if an ob,e+t is reV(ired to +reate +o"p(lsory t#at ob,e+t s#o(ld be pla+ed on
t#e #eap b(t not C'\.
Example 3:
Ctrin! s18new Ctrin!BNsprin!N/9
s1.+on+atBNfallN/9
s18s1FNwinterN9
Ctrin! s28s1.+on+atBNs(""erN/9
Cyste".o(t.printlnBs1/9
Cyste".o(t.printlnBs2/9
'iagram:

Example:
+lass Ctrin!De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s18new Ctrin!BNyo( +annot +#an!e "ebN/9
Ctrin! s28new Ctrin!BNyo( +annot +#an!e "ebN/9
Cyste".o(t.printlnBs188s2/9JJfalse
Ctrin! s38Nyo( +annot +#an!e "ebN9
Cyste".o(t.printlnBs188s3/9JJfalse
Ctrin! s48Nyo( +annot +#an!e "ebN9
Cyste".o(t.printlnBs388s4/9JJtr(e
Ctrin! s58Nyo( +annot NFN+#an!e "ebN9
Cyste".o(t.printlnBs388s5/9JJtr(e
Ctrin! s68Nyo( +annot N9
Ctrin! s78s6FN+#an!e "ebN9
Cyste".o(t.printlnBs388s7/9JJfalse

2$)

final Ctrin! s$8Nyo( +annot N9
Ctrin! s&8s$FN+#an!e "ebN9
Cyste".o(t.printlnBs388s&/9JJtr(e
Cyste".o(t.printlnBs688s$/9JJtr(e
=
=
'iagram:

Importan$e of 2tring $onstant pool :2*3;:
'iagram:

In o(r pro!ra" if any Ctrin! ob,e+t is reV(ired to (se repeatedly t#en it is not
re+o""ended to +reate "(ltiple ob,e+t wit# sa"e +ontent it red(+es perfor"an+e of
t#e syste" and effe+ts "e"ory (tili0ation.
@e +an +reate only one +opy and we +an re(se t#e sa"e ob,e+t for every reV(ire"ent.
T#is approa+# i"proves perfor"an+e and "e"ory (tili0ation we +an a+#ieve t#is
byLs+pL.
In C'\ several referen+es pointin! to sa"e ob,e+t t#e "ain disadvanta!e in t#is
approa+# is by (sin! one referen+e if we are perfor"in! any +#an!e t#e re"ainin!
referen+es will be i"pa+ted. To parent t#is s(n people de+lared Ctrin! ob,e+ts as
i""(table.

2$1

A++ordin! to t#is on+e we +reates a Ctrin! ob,e+t we +anAt perfor" any +#an!es in t#e
eEistin! ob,e+t if we are tryin! to perfor" any +#an!es wit# t#ose +#an!es a new Ctrin!
ob,e+t will be +reated #en+e i""(tability is t#e "ain disadvanta!e of s+p.
1; "#at is t#e main differen$e ,et%een 2tring and 2tring1uilder&
2; "#at is t#e meaning of immuta,ilit( and muta,ilit(&
3; Explain immuta,ilit( and muta,ilit( %it# an example&
4; "#at is 2*3&
A spe+ially desi!ned "e"ory area for t#e Ctrin! literals.
5; "#at is t#e advantage of 2*3&
Instead of +reatin! a separate ob,e+t for every reV(ire"ent we +an +reate only one
ob,e+t and we +an re(se sa"e ob,e+t for every reV(ire"ent. T#is approa+# i"proves
perfor"an+e and "e"ory (tili0ation.
6; "#at is t#e disadvantage of 2*3&
In C'\ as several referen+es pointin! to t#e sa"e ob,e+t by (sin! one referen+e if we are
perfor"in! any +#an!es t#e re"ainin! referen+es will be infle+ted. To prevent t#is
+o"p(lsory Ctrin! ob,e+ts s#o(ld be i""(table. T#at is i""(tability is t#e disadvanta!e
of C'\.
; "#( 2*3 li+e $on$ept availa,le onl( for t#e 2tring ,ut not for t#e 2tring1uffer&
As Ctrin! ob,e+t is t#e "ost +o""only (sed ob,e+t s(n people provided a spe+ially
desi!ned "e"ory area li?e C'\ to i"prove "e"ory (tili0ation and perfor"an+e.
6(t Ctrin!6(ffer ob,e+t is not +o""only (sed ob,e+t #en+e spe+ially desi!ned "e"ory
area is not at all reV(ired.
B; "#( 2tring o,je$ts are immuta,le %#ere as 2tring1uffer o,je$ts are muta,le&
In t#e +ase of Ctrin! as several referen+es pointin! to t#e sa"e ob,e+t- by (sin! one
referen+e if we are allowed perfor" t#e +#an!e t#e re"ainin! referen+es will be
i"pa+ted. To prevent t#is on+e we +reated a Ctrin! ob,e+t we +anAt perfor" any +#an!e
in t#e eEistin! ob,e+t t#at is i""(tability is only d(e to C'\.
6(t in t#e +ase of Ctrin!6(ffer for every reV(ire"ent we are +reatin! a separate ob,e+t
by (sin! one reveren+e if we are perfor"in! any +#an!e in t#e ob,e+t t#e re"ainin!
referen+es wonAt be i"pa+ted #en+e i""(tability +on+ept is not reV(ire for t#e
Ctrin!6(ffer.
V; 2imilar to 2tring o,je$ts an( ot#er o,je$ts are immuta,le in java&
In addition to Ctrin! all wrapper ob,e+ts are i""(table in ,ava.
15; Is it possi,le to $reate our o%n muta,le $lass&
aes.
11; Explain t#e pro$ess of $reating our o%n immuta,le $lass %it# an example&
12; "#at is t#e differen$e ,et%een final and immuta,ilit(&
13; "#at is interning of 2tring o,je$ts&

2$2

Interning of 2tring o,je$ts:
6y (sin! #eap ob,e+t referen+e- if we want to +orrespondin! C'\ ob,e+t referen+e we
s#o(ld !o for internB/ "et#od.
Example 1:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s18new Ctrin!BNb#as?arN/9
Ctrin! s28s1.internB/9
Ctrin! s38Nb#as?arN9
Cyste".o(t.printlnBs288s3/9JJtr(e

=
=
'iagram:

If t#e +orrespondin! ob,e+t is not t#ere in C'\ t#en internB/ "et#od itself will +reate
t#at ob,e+t and ret(rns it.
Example 2:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s18new Ctrin!BNb#as?arN/9
Ctrin! s28s1.+on+atBNsoftwareN/9
Ctrin! s38s2.internB/9
Ctrin! s48Nb#as?arsoftwareN9
Cyste".o(t.printlnBs388s4/9JJtr(e

=
=




2$3

'iagram 2:

2tring $lass $onstru$tors:
1; 2tring sMne% 2tring:;E
'reates an e"pty Ctrin! Ib,e+t.
2; 2tring sMne% 2tring:2tring literals;E
To +reate an eV(ivalent Ctrin! ob,e+t for t#e !iven Ctrin! literal on t#e #eap.
3; 2tring sMne% 2tring:2tring1uffer s,;E
'reates an eV(ivalent Ctrin! ob,e+t for t#e !iven Ctrin!6(ffer.
4; 2tring sMne% 2tring:$#arTU $#;E
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
+#arD> +#87QaQ-QbQ-Q+Q=9
Ctrin! s8new Ctrin!B+#/9
Cyste".o(t.printlnB+#/9JJab+
=
=
5; 2tring sMne% 2tring:,(teTU ,;E
Hor t#e !iven byteD> we +an +reate a Ctrin!.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
byteD> b871))-1)1-1)2=9
Ctrin! s8new Ctrin!Bb/9
Cyste".o(t.printlnBs/9JJdef
=

2$4

=
Important met#ods of 2tring $lass:
1; pu,li$ $#ar $#ar7t:int index;E
Ret(rns t#e +#ara+ter lo+atin! at spe+ified indeE.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8Nb#as?arN9
Cyste".o(t.printlnBs.+#arAtB3//9JJs
Cyste".o(t.printlnBs.+#arAtB1))//9JJCtrin!IndeEI(tIf6o(nds<E+eption
=
=
2; pu,li$ 2tring $on$at:2tring str;E
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8Nb#as?arN9
s8s.+on+atBNsoftwareN/9
JJs8sFNsoftwareN9
JJsF8NsoftwareN9
Cyste".o(t.printlnBs/9JJb#as?arsoftware
=
=
T#e overloaded KFL and KF8L operators also "eant for +on+atenation p(rpose only.
3; pu,li$ ,oolean eAuals:!,je$t o;E
Hor +ontent +o"pression w#ere +ase is i"portant.
It is t#e overridin! version of Ib,e+t +lass .eV(alsB/ "et#od.
4; pu,li$ ,oolean eAualsIgnore*ase:2tring s;E
Hor +ontent +o"pression w#ere +ase is not i"portant.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8Nb#as?arN9
Cyste".o(t.printlnBs.eV(alsBNb#as?arN//9JJtr(e
Cyste".o(t.printlnBs.eV(alsI!nore'aseBN6SACGARN//9JJtr(e
=
=

2$5

/ote: @e +an validate (serna"e by (sin! eV(alsI!nore'aseB/ "et#od w#ere +ase is not
i"portant and we +an validate password by (sin! .eV(alsB/ "et#od w#ere +ase is i"portant.
5; pu,li$ 2tring su,string:int ,egin;E
Ret(rn t#e s(bstrin! fro" be!in indeE to end of t#e strin!.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8Nvi,ayab#as?arN9
Cyste".o(t.printlnBs.s(bstrin!B6//9JJb#as?ar
=
=
6; pu,li$ 2tring su,string:int ,eginH int end;E
Ret(rns t#e s(bstrin! fro" be!in indeE to end41 indeE.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8Nvi,ayab#as?arN9
Cyste".o(t.printlnBs.s(bstrin!B6//9JJb#as?ar
Cyste".o(t.printlnBs.s(bstrin!B3-7//9JJayab
=
=
; pu,li$ int lengt#:;E
Ret(rns t#e no of +#ara+ters present in t#e strin!.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8Nvi,ayab#as?arN9
Cyste".o(t.printlnBs.len!t#B//9JJ13
JJCyste".o(t.printlnBs.len!t#/9JJ+o"pile ti"e error
JJCtrin!InternDe"o.,ava.7. +annot find sy"bol
JJsy"bol . variable len!t#
JJlo+ation. +lass ,ava.lan!.Ctrin!
=
=
/ote: len!t# is t#e variable appli+able for arrays w#ere as len!t#B/ "et#od is appli+able for
Ctrin! ob,e+t.
B; pu,li$ 2tring repla$e:$#ar oldH$#ar ne%;E
To repla+e every old +#ara+ter wit# a new +#ara+ter.

2$6

Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8NabababN9
Cyste".o(t.printlnBs.repla+eBQaQ-QbQ//9JJbbbbbb
=
=
V; pu,li$ 2tring toLo%er*ase:;E
'onverts t#e all +#ara+ters of t#e strin! to lower+ase.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8N6SACGARN9
Cyste".o(t.printlnBs.toLower'aseB//9JJb#as?ar
=
=
15; pu,li$ 2tring to.pper*ase:;E
'onverts t#e all +#ara+ters of t#e strin! to (pper+ase.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8Nb#as?arN9
Cyste".o(t.printlnBs.to;pper'aseB//9JJ6SACGAR
=
=
11; pu,li$ 2tring trim:;
@e +an (se t#is "et#od to re"ove blan? spa+es present at be!innin! and end of t#e
strin! b(t not blan? spa+es present at "iddle of t#e Ctrin!.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8N b#a s?ar N9
Cyste".o(t.printlnBs.tri"B//9JJb#a s?ar
=
=
12; pu,li$ int index!f:$#ar $#;E

2$7

It ret(rns indeE of 1
st
o++(rren+e of t#e spe+ified +#ara+ter if t#e spe+ified +#ara+ter is
not available t#en ret(rn 41.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8Nvi,ayab#as?arreddyN9
Cyste".o(t.printlnBs.indeEIfBQaQ//9JJ3
Cyste".o(t.printlnBs.indeEIfBQ0Q//941
=
=
13; pu,li$ int lastIndex!f:*#ar $#;E
It ret(rns indeE of last o++(rren+e of t#e spe+ified +#ara+ter if t#e spe+ified +#ara+ter is
not available t#en ret(rn 41.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8Nvi,ayab#as?arreddyN9
Cyste".o(t.printlnBs.lastIndeEIfBQaQ//9JJ11
Cyste".o(t.printlnBs.indeEIfBQ0Q//9JJ41
=
=

/ote:
6e+a(se r(nti"e operation if t#ere is a +#an!e in +ontent wit# t#ose +#an!es a new
ob,e+t will be +reated only on t#e #eap b(t not in C'\.
If t#ere is no +#an!e in +ontent no new ob,e+t will be +reated t#e sa"e ob,e+t will be
re(sed.
Example 1:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s18Nb#as?arN9
Ctrin! s28s1.to;pper'aseB/9
Ctrin! s38s1.toLower'aseB/9
Cyste".o(t.printlnBs188s2/9JJfalse
Cyste".o(t.printlnBs188s3/9JJtr(e
=
=


2$$

'iagram:

Example 2:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s18Nb#as?arN9
Ctrin! s28s1.toCtrin!B/9
Cyste".o(t.printlnBs188s2/9JJtr(e
=
=
'iagram:

*reation of our o%n immuta,le $lass:
@e +an +reate o(r own i""(table +lasses.
In+e we +reated an ob,e+t we +anAt perfor" any +#an!es in t#e eEistin! ob,e+t. If we
are tryin! to perfor" any +#an!es wit# t#ose +#an!es a new ob,e+t will be +reated. If
t#ere is no +#an!e in t#e +ontent t#en eEistin! ob,e+t will be re(sed. T#is be#avior is
+alled i""(tability.
Example:
+lass Ctrin!InternDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s18Nb#as?arN9
Ctrin! s28s1.to;pper'aseB/9
Ctrin! s38s1.toLower'aseB/9
Cyste".o(t.printlnBs188s2/9JJfalse
Cyste".o(t.printlnBs188s3/9JJtr(e
=
=


2$&

'iagram:

Immuta,le program:
final +lass 'reateI""(table
7
private int i9
'reateI""(tableBint i/
7
t#is.i8i9
=
p(bli+ 'reateI""(table "odifyBint i/
7
ifBt#is.i88i/
ret(rn t#is9
else
ret(rn Bnew 'reateI""(tableBi//9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
'reateI""(table +18new 'reateI""(tableB1)/9
'reateI""(table +28+1."odifyB1))/9
'reateI""(table +38+1."odifyB1)/9
Cyste".o(t.printlnB+188+2/9JJfalse
Cyste".o(t.printlnB+188+3/9JJtr(e
'reateI""(table +48+1."odifyB1))/9
Cyste".o(t.printlnB+288+4/9JJfalse
=
=
'iagram:

Final vs immuta,ilit(:
If we de+lare a variable as final t#en we +anAt perfor" reassi!n"ent for t#at variable. It
doesnAt "ean in t#e +orrespondin! ob,e+t we +anAt perfor" any +#an!es. T#at is
t#ro(!# final ?eyword we wonAt !et any i""(tability t#at is final and i""(tability
+on+epts are different.



2&)

Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
final Ctrin!6(ffer sb8new Ctrin!6(fferBNb#as?arN/9
sb.appendBNsoftwareN/9
Cyste".o(t.printlnBsb/9JJb#as?arsoftware
sb8new Ctrin!6(fferBNsol(tionsN/9JJ'.<. +annot assi!n a val(e to final variable
sb
=
=
In t#e above eEa"ple even t#o(!# KsbL is final we +an perfor" any type of +#an!e in
t#e +orrespondin! ob,e+t. T#at is t#ro(!# final ?eyword we are not !ettin! any
i""(tability nat(re.
2tring1uffer
If t#e +ontent will +#an!e freV(ently t#en never re+o""ended to !o for Ctrin! ob,e+t
be+a(se for every +#an!e a new ob,e+t will be +reated internally.
To #andle t#is type of reV(ire"ent we s#o(ld !o for Ctrin!6(ffer +on+ept.
T#e "ain advanta!e of Ctrin!6(ffer over Ctrin! is- all reV(ired +#an!es will be
perfor"ed in t#e eEistin! ob,e+t only instead of +reatin! new ob,e+t.
*onstru$tors:
1; 2tring1uffer s,Mne% 2tring1uffer:;E
'reates an e"pty Ctrin!6(ffer ob,e+t wit# defa(lt initial+apa+ity K16L.
In+e Ctrin!6(ffer ob,e+t rea+#es its "aEi"(" +apa+ity a new Ctrin!6(ffer ob,e+t will be
+reated wit# /e%$apa$it(M:$urrent$apa$it(?1;[29
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferB/9
Cyste".o(t.printlnBsb.+apa+ityB//9JJ16
sb.appendBNab+def!#i,?l"nopN/9
Cyste".o(t.printlnBsb.+apa+ityB//9JJ16
sb.appendBNVN/9
Cyste".o(t.printlnBsb.+apa+ityB//9JJ34
=
=

2&1

2; 2tring1uffer s,Mne% 2tring1uffer:int initial$apa$it(;E
'reates an e"pty Ctrin!6(ffer ob,e+t wit# t#e spe+ified initial +apa+ity.
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferB1&/9
Cyste".o(t.printlnBsb.+apa+ityB//9JJ1&
=
=
3; 2tring1uffer s,Mne% 2tring1uffer:2tring s;E
'reates an eV(ivalent Ctrin!6(ffer ob,e+t for t#e !iven Ctrin! wit#
+apa+ity8s.len!t#B/F169
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferBNb#as?arN/9
Cyste".o(t.printlnBsb.+apa+ityB//9JJ23
=
=
Important met#ods of 2tring1uffer:
1; pu,li$ int lengt#:;E
Ret(rn t#e no of +#ara+ters present in t#e Ctrin!6(ffer.
2; pu,li$ int $apa$it(:;E
Ret(rns t#e total no of +#ara+ters b(t a Ctrin!6(ffer +an a++o""odateB#old/.
3; pu,li$ $#ar $#ar7t:int index;E
It ret(rns t#e +#ara+ter lo+ated at spe+ified indeE.
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferBNvi,ayab#as?arreddyN/9
Cyste".o(t.printlnBsb.len!t#B//9JJ1$
Cyste".o(t.printlnBsb.+apa+ityB//9JJ34

2&2

Cyste".o(t.printlnBsb.+#arAtB14//9JJe
=
=
4; pu,li$ void set*#ar7t:int indexH$#ar $#;E
To repla+e t#e +#ara+ter lo+atin! at spe+ified indeE wit# t#e provided +#ara+ter.
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferBNvi,ayab#as?arreddyN/9
sb.set'#arAtB6-QAQ/9
Cyste".o(t.printlnBsb/9
=
=
5; pu,li$ 2tring1uffer append:2tring s;E
p(bli+ Ctrin!6(ffer appendBint i/9
p(bli+ Ctrin!6(ffer appendBlon! l/9
p(bli+ Ctrin!6(ffer appendBboolean b/9 All t#ese are overloaded "et#ods.
p(bli+ Ctrin!6(ffer appendBdo(ble d/9
p(bli+ Ctrin!6(ffer appendBfloat f/9
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferB/9
sb.appendBN\I val(e is .N/9
sb.appendB3.14/9
sb.appendBN t#is is eEa+tly N/9
sb.appendBtr(e/9
Cyste".o(t.printlnBsb/9JJ\I val(e is .3.14 t#is is eEa+tly tr(e
=
=
6; pu,li$ 2tring1uffer insert:int indexH2tring s;E
p(bli+ Ctrin!6(ffer insertBint indeE-int i/9
p(bli+ Ctrin!6(ffer insertBint indeE-lon! l/9
p(bli+ Ctrin!6(ffer insertBint indeE-do(ble d/9 All are overloaded "et#ods

2&3

p(bli+ Ctrin!6(ffer insertBint indeE-boolean b/9
p(bli+ Ctrin!6(ffer insertBint indeE-float f/9
To insert at t#e spe+ified lo+ation.
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferBNvi,ayaN/9
sb.insertB6-Nb#as?arN/9
sb.insertB13-N&N/9
Cyste".o(t.printlnBsb/9JJvi,ayab#as?ar&
=
=
; pu,li$ 2tring1uffer delete:int ,eginHint end;E
To delete +#ara+ters fro" be!in indeE to end n41 indeE.
B; pu,li$ 2tring1uffer delete*#ar7t:int index;E
To delete t#e +#ara+ter lo+atin! at spe+ified indeE.
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferBNvi,ayab#as?arN/9
Cyste".o(t.printlnBsb/9JJvi,ayab#as?ar
sb.deleteB6-13/9
Cyste".o(t.printlnBsb/9JJvi,aya
sb.delete'#arAtB5/9
Cyste".o(t.printlnBsb/9JJvi,ay
=
=
V; pu,li$ 2tring1uffer reverse:;E
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferBNvi,ayab#as?arN/9

2&4

Cyste".o(t.printlnBsb/9JJvi,ayab#as?ar
Cyste".o(t.printlnBsb.reverseB//9JJra?sa#baya,iv
=
=
15; pu,li$ void setLengt#:int lengt#;E
'onsider only spe+ified no of +#ara+ters and re"ove all t#e re"ainin! +#ara+ters.
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferBNvi,ayab#as?arN/9
sb.setLen!t#B6/9
Cyste".o(t.printlnBsb/9JJvi,aya
=
=
11; pu,li$ void trim8o2i4e:;E
To deallo+ate t#e eEtra free "e"ory s(+# t#at +apa+ity and si0e are eV(al.
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferB1)))/9
Cyste".o(t.printlnBsb.+apa+ityB//9JJ1)))
sb.appendBNb#as?arN/9
Cyste".o(t.printlnBsb.+apa+ityB//9JJ1)))
sb.tri"ToCi0eB/9
Cyste".o(t.printlnBsb.+apa+ityB//9JJ7
=
=
12; pu,li$ void ensure*apa$it(:int initial$apa$it(;E
To in+rease t#e +apa+ity dyna"i+ally based on o(r reV(ire"ent.
Example:
+lass Ctrin!6(fferDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7

2&5

Ctrin!6(ffer sb8new Ctrin!6(fferB/9
Cyste".o(t.printlnBsb.+apa+ityB//9JJ16
sb.ens(re'apa+ityB1)))/9
Cyste".o(t.printlnBsb.+apa+ityB//9JJ1)))
=
=
2tring1uilder :195;
<very "et#od present in Ctrin!6(ffer is de+lared as syn+#roni0ed #en+e at a ti"e only
one t#read is allowed to operate on t#e Ctrin!6(ffer ob,e+t d(e to t#is- waitin! ti"e of
t#e t#reads will be in+reased and effe+ts perfor"an+e of t#e syste".
To over+o"e t#is proble" s(n people introd(+ed Ctrin!6(ilder +on+ept in 1.5v.
Ctrin!6(ilder is eEa+tly sa"e as Ctrin!6(ffer eE+ept t#e followin! differen+es.
2tring1uffer 2tring1uilder
1/ <very "et#od present in Ctrin!6(ffer is
syn+#roni0ed.
1/ :o "et#od present in Ctrin!6(ilder is
syn+#roni0ed.
2/ At a ti"e only one t#read is allow to
operate on t#e Ctrin!6(ffer ob,e+t
#en+e Ctrin!6(ffer ob,e+t is T#read
safe.
2/ %(ltiple T#reads are allowed to
operate si"(ltaneo(sly on t#e
Ctrin!6(ilder ob,e+t #en+e
Ctrin!6(ilder is not T#read safe.
3/ It in+reases waitin! ti"e of t#e T#read
and #en+e relatively perfor"an+e is
low.
3/ T#reads are not reV(ired to wait and
#en+e relatively perfor"an+e is #i!#.
4/ Introd(+ed in 1.) version. 4/ Introd(+ed in 1.5 versions.
2tring vs 2tring1uffer vs 2tring1uilder:
If t#e +ontent is fiEed and wonAt +#an!e freV(ently t#en we s#o(ld !o for Ctrin!.
If t#e +ontent will +#an!e freV(ently b(t T#read safety is reV(ired t#en we s#o(ld !o for
Ctrin!6(ffer.
If t#e +ontent will +#an!e freV(ently and T#read safety is not reV(ired t#en we s#o(ld
!o for Ctrin!6(ilder.
=et#od $#aining:
Hor "ost of t#e "et#ods in Ctrin!- Ctrin!6(ffer and Ctrin!6(ilder t#e ret(rn type is sa"e
type only. Sen+e after applyin! "et#od on t#e res(lt we +an +all anot#er "et#od w#i+#
for"s "et#od +#ainin!.
Example:
s."1B/."2B/."3B/eeeeee.
In "et#od +#ainin! all "et#ods will be eval(ated fro" left to ri!#t.
Example:
+lass Ctrin!6(fferDe"o

2&6

7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!6(ffer sb8new Ctrin!6(fferB/9
sb.appendBNvi,ayaN/.insertB6-Nb#as?arreddyN/.deleteB13-17/.reverseB/.appendBNsol(tions
N/.insertB22-Nab+dfN/.reverseB/9
Cyste".o(t.printlnBsb/9JJsfd+banoit(losvi,ayab#as?ary
=
=
"rapper $lasses
T#e "ain ob,e+tives of wrapper +lasses are.
To wrap pri"itives into ob,e+t for" so t#at we +an #andle pri"itives also ,(st li?e
ob,e+ts.
To define several (tility f(n+tions w#i+# are reV(ired for t#e pri"itives.
*onstru$tors:
All "ost all wrapper +lasses define t#e followin! 2 +onstr(+tors one +an ta?e
+orrespondin! pri"itive as ar!("ent and t#e ot#er +an ta?e Ctrin! as ar!("ent.
Example:
1; Integer iMne% Integer:15;E
2; Integer iMne% Integer:>15@;E
If t#e Ctrin! is not properly for"atted t#en we will !et r(nti"e eE+eption sayin!
K/um,erFormatEx$eptionL.
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption
7
Inte!er i8new Inte!erBNtenN/9
Cyste".o(t.printlnBi/9JJ:("berHor"at<E+eption
=
=
Hloat +lass defines 3 +onstr(+tors wit# float- Ctrin! and do(ble ar!("ents.
1; Float fMne% Float :1595f;E
2; Float fMne% Float :>1595f@;E
3; Float fMne% Float:1595;E
4; Float fMne% Float :>1595@;E

2&7

'#ara+ter +lass defines only one +onstr(+tor w#i+# +an ta?e +#ar pri"itive as ar!("ent
t#ere is no Ctrin! ar!("ent +onstr(+tor.
*#ara$ter $#Mne% *#ara$ter:\aI;EWWvalid
'#ara+ter +#8new '#ara+terBKaL/9JJinvalid
6oolean +lass defines 2 +onstr(+tors wit# boolean pri"itive and Ctrin! ar!("ents.
If we want to pass boolean pri"itive t#e only allowed val(es are tr(e- false w#ere +ase
s#o(ld be lower +ase.
Example:
6oolean b8new 6ooleanBtr(e/9
JJ6oolean b18new 6ooleanBTr(e/9JJ'.<
JJ6oolean b8new 6ooleanBHalse/9JJ'.<
If we are passin! Ctrin! ar!("ent t#en +ase is not i"portant and +ontent is not
i"portant. If t#e +ontent is +ase insensitive Ctrin! of tr(e t#en it is treated as tr(e in all
ot#er +ases it is treated as false.
Example 1:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption
7
6oolean b18new 6ooleanBNtr(eN/9
6oolean b28new 6ooleanBNTr(eN/9
6oolean b38new 6ooleanBNfalseN/9
6oolean b48new 6ooleanBNHalseN/9
6oolean b58new 6ooleanBNb#as?arN/9
Cyste".o(t.printlnBb1/9JJtr(e
Cyste".o(t.printlnBb2/9JJtr(e
Cyste".o(t.printlnBb3/9JJfalse
Cyste".o(t.printlnBb4/9JJfalse
Cyste".o(t.printlnBb5/9JJfalse
=
=
Example 2:for exam purpose;:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption
7
6oolean b18new 6ooleanBNyesN/9
6oolean b28new 6ooleanBNnoN/9

2&$

Cyste".o(t.printlnBb1/9JJfalse
Cyste".o(t.printlnBb2/9JJfalse
Cyste".o(t.printlnBb1.eV(alsBb2//9JJtr(e
Cyste".o(t.printlnBb188b2/9JJfalse
=
=
"rapper $lass *onstru$tor summer(
6yte byte- Ctrin!
C#ort s#ort- Ctrin!
Inte!er Int- Ctrin!
Lon! lon!- Ctrin!
Hloat float- Ctrin!- do(ble
Do(ble do(ble- Ctrin!
'#ara+ter

6oolean boolean- Ctrin!
/ote:
1/ In all wrapper +lasses toCtrin!B/ "et#od is overridden to ret(rn its +ontent.
2/ In all wrapper +lasses .eV(alsB/ "et#od is overridden for +ontent +o"pression.
.tilit( met#ods:
1/ val(eIfB/ "et#od.
2/ PPPal(eB/ "et#od.
3/ parsePEEB/ "et#od.
4/ toCtrin!B/ "et#od.
value!f:; met#od: @e +an (se val(eIfB/ "et#od to +reate wrapper ob,e+t for t#e !iven
pri"itive or Ctrin! t#is "et#od is alternative to +onstr(+tor.
Form 1: <very wrapper +lass eE+ept '#ara+ter +lass +ontains a stati+ val(eIfB/ "et#od to +reate
wrapper ob,e+t for t#e !iven Ctrin!.
pu,li$ stati$ %rapper value!f:2tring s;E
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption
7
Inte!er i8Inte!er.val(eIfBN1)N/9
Do(ble d8Do(ble.val(eIfBN1).5N/9
6oolean b86oolean.val(eIfBNb#as?arN/9
Cyste".o(t.printlnBi/9JJ1)
Cyste".o(t.printlnBd/9JJ1).5
Cyste".o(t.printlnBb/9JJfalse
=
=

2&&

Form 2: <very inte!ral type wrapper +lass B6yte- C#ort- Inte!er- and Lon!/ +ontains t#e followin!
val(eIfB/ "et#od to +onvert spe+ified radiE strin! to wrapper ob,e+t.

/ote: t#e allowed radiE ran!e is 2436.

Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Inte!er i8Inte!er.val(eIfBN1))N-2/9
Cyste".o(t.printlnBi/9JJ4
=
=
7nal(sis:

Form 3: <very wrapper +lass in+l(din! '#ara+ter +lass defines val(eIfB/ "et#od to +onvert
pri"itive to wrapper ob,e+t.
pu,li$ stati$ %rapper value!f:primitive p;E
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption
7
Inte!er i8Inte!er.val(eIfB1)/9
Do(ble d8Do(ble.val(eIfB1).5/9
6oolean b86oolean.val(eIfBtr(e/9
Cyste".o(t.printlnBi/9JJ1)
Cyste".o(t.printlnBd/9JJ1).5

3))

Cyste".o(t.printlnBb/9JJtr(e
=
=
'iagram:

xxx-alue:; met#od: @e +an (se EEEal(eB/ "et#ods to +onvert wrapper ob,e+t to pri"itive.
<very n("ber type wrapper +lass B6yte- C#ort- Inte!er- Lon!- Hloat- Do(ble/ +ontains t#e
followin! 6 EEEal(eB/ "et#ods to +onvert wrapper ob,e+t to pri"itives.
1; pu,li$ ,(te ,(te-alue:;
2; pu,li$ s#ort s#ort-alue:;
3; pu,li$ int int-alue:;
4; pu,li$ long long-alue:;
5; pu,li$ float float-alue:;
6; p,li$ dou,le dou,le-alue:;E
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption
7
Inte!er i8new Inte!erB13)/9
Cyste".o(t.printlnBi.byteal(eB//9JJ4126
Cyste".o(t.printlnBi.s#ortal(eB//9JJ13)
Cyste".o(t.printlnBi.intal(eB//9JJ13)
Cyste".o(t.printlnBi.lon!al(eB//9JJ13)
Cyste".o(t.printlnBi.floatal(eB//9JJ13).)
Cyste".o(t.printlnBi.do(bleal(eB//9JJ13).)
=
=
$#ar-alue:; met#od: '#ara+ter +lass +ontains +#aral(eB/ "et#od to +onvert '#ara+ter ob,e+t
to +#ar pri"itive.
pu,li$ $#ar $#ar-alue:;E
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
'#ara+ter +#8new '#ara+terBQaQ/9
+#ar +8+#.+#aral(eB/9

3)1

Cyste".o(t.printlnB+/9JJa
=
=
,oolean-alue:; met#od: 6oolean +lass +ontains booleanal(eB/ "et#od to +onvert 6oolean
ob,e+t to boolean pri"itive.
pu,li$ ,oolean ,oolean-alue:;E
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
6oolean b8new 6ooleanBNb#as?arN/9
boolean b18b.booleanal(eB/9
Cyste".o(t.printlnBb1/9JJfalse
=
=
'iagram:

In total t#ere are 3$B6U6F1F1/ EEEal(eB/ "et#ods are possible.
parseDxx:; met#od: @e +an (se t#is "et#od to +onvert Ctrin! to +orrespondin! pri"itive.
Form1: <very wrapper +lass eE+ept '#ara+ter +lass +ontains a stati+ parsePEEB/ "et#od to
+onvert Ctrin! to +orrespondin! pri"itive.
pu,li$ stati$ primitive parseDxx:2tring s;E
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int i8Inte!er.parseIntBN1)N/9
boolean b86oolean.parse6ooleanBNb#as?arN/9
do(ble d8Do(ble.parseDo(bleBN1).5N/9
Cyste".o(t.printlnBi/9JJ1)
Cyste".o(t.printlnBb/9JJfalse
Cyste".o(t.printlnBd/9JJ1).5
=
=

3)2

Form 2: inte!ral type wrapper +lassesB6yte- C#ort- Inte!er- Lon!/ +ontains t#e followin!
parsePEEB/ "et#od to +onvert spe+ified radiE Ctrin! for" to +orrespondin! pri"itive.
pu,li$ stati$ primitive parseDxx:2tring sHint radix;E
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int i8Inte!er.parseIntBN1))N-2/9
Cyste".o(t.printlnBi/9JJ4
=
=
'iagram:

to2tring:; met#od: @e +an (se toCtrin!B/ "et#od to +onvert wrapper ob,e+t Bor/ pri"itive to
Ctrin!.
Form 1:
p(bli+ Ctrin! toCtrin!B/9

<very wrapper +lass in+l(din! '#ara+ter +lass +ontains t#e above toCtrin!B/ "et#od to
+onvert wrapper ob,e+t to Ctrin!.
It is t#e overridin! version of Ib,e+t +lass toCtrin!B/ "et#od.
@#enever we are tryin! to print wrapper ob,e+t referen+e internally t#is toCtrin!B/
"et#od only eEe+(ted.
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Inte!er i8Inte!er.val(eIfBN1)N/9
Cyste".o(t.printlnBi/9JJ1)
Cyste".o(t.printlnBi.toCtrin!B//9JJ1)
=
=
Form 2: <very wrapper +lass +ontains a stati+ toCtrin!B/ "et#od to +onvert pri"itive to Ctrin!.
pu,li$ stati$ 2tring to2tring:primitive p;E


3)3

Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s18Inte!er.toCtrin!B1)/9
Ctrin! s286oolean.toCtrin!Btr(e/9
Cyste".o(t.printlnBs1/9JJ1)
Cyste".o(t.printlnBs2/9JJtr(e
=
=
Form 3:
Inte!er and lon! +lasses +ontains t#e followin! stati+ toCtrin!B/ "et#od to +onvert t#e
pri"itive to spe+ified radiE Ctrin! for".
pu,li$ stati$ 2tring to2tring:primitive pHint radix;E
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s18Inte!er.toCtrin!B7-2/9
Ctrin! s28Inte!er.toCtrin!B17-2/9
Cyste".o(t.printlnBs1/9JJ111
Cyste".o(t.printlnBs2/9JJ1)))1
=
=
Form 4: Inte!er and Lon! +lasses +ontains t#e followin! toPEECtrin!B/ "et#ods.
pu,li$ stati$ 2tring to1inar(2tring:primitive p;E
pu,li$ stati$ 2tring to!$tal2tring:primitive p;E
pu,li$ stati$ 2tring to6ex2tring:primitive p;E
Example:
+lass @rapper'lassDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s18Inte!er.to6inaryCtrin!B7/9
Ctrin! s28Inte!er.toI+talCtrin!B1)/9
Ctrin! s38Inte!er.toSeECtrin!B2)/9
Cyste".o(t.printlnBs1/9JJ111
Cyste".o(t.printlnBs2/9JJ12

3)4

Cyste".o(t.printlnBs3/9JJ14
=
=
'iagram:

'an$ing ,et%een 2tringH %rapper o,je$t and primitive:
'iagram:

Ctrin!- Ctrin!6(ffer- Ctrin!6(ilder and all wrapper +lasses are final +lasses.
T#e wrapper +lasses w#i+# are not +#ild +lass of /um,er of 6oolean and '#ara+ter.
T#e wrapper +lasses w#i+# are not dire+t +lass of Ib,e+t of 6yte- C#ort- Inte!er- Lon!-
Hloat- Do(ble.
Co"eti"es we +an +onsider -oid is also as wrapper +lass.
In addition to Ctrin! all wrapper ob,e+ts also i""(table in ,ava.
7uto,oxing and 7utoun,oxing
;ntil 1.4 version we +anAt provide wrapper ob,e+t in t#e pla+e of pri"itive and pri"itive
in t#e pla+e of wrapper ob,e+t all t#e reV(ired +onversions s#o(ld be perfor"ed
eEpli+itly by t#e pro!ra""er.
Example 1:
3rogram 1:


3)5

3rogram 2:
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
6oolean b8new 6ooleanBtr(e/9
ifBb/
7
Cyste".o(t.printlnBN#elloN/9
===
!utput:
Sello
Example 2:
3rogram 1:

3rogram 2:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
ArrayList l8new ArrayListB/9
Inte!er i8new Inte!erB1)/9
l.addBi/9
=
=

6(t fro" 1.5 version onwards we +an provide pri"itive val(e in t#e pla+e of wrapper
and wrapper ob,e+t in t#e pla+e of pri"itive all reV(ired +onversions will be perfor"ed
a(to"ati+ally by +o"piler. T#ese a(to"ati+ +onversions are +alled A(toboEin! and
A(to(nboEin!.

3)6

7uto,oxing: A(to"ati+ +onversion of pri"itive to wrapper ob,e+t by +o"piler is +alled
A(toboEin!.
Example:
Inte!er i81)9 D+o"piler +onverts KintL to KInte!erL a(to"ati+ally by A(toboEin!>
After +o"pilation t#e above line will be+o"e.
Inte!er i8Inte!er.val(eIfB1)/9
T#at is internally A(toboEin! +on+ept is i"ple"ented by (sin! val(eIfB/ "et#od.
7utoun,oxing: a(to"ati+ +onversion of wrapper ob,e+t to pri"itive by +o"piler is +alled
A(to(nboEin!.
Example:
Inte!er i8new Inte!erB1)/9
Int i8I9 D+o"piler +onverts KInte!erL to KintL a(to"ati+ally by A(to(nboEin!>
After +o"pilation t#e above line will be+o"e.
Int i8I.intal(eB/9
T#at is A(to(nboEin! +on+ept is internally i"ple"ented by (sin! EEEal(eB/ "et#od.
'iagram:

Example:

/ote: Hro" 1.5 version onwards we +an (se pri"itives and wrapper ob,e+ts inter+#an!ly t#e
reV(ired +onversions will be perfor"ed a(to"ati+ally by +o"piler.
Example 1:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7

3)7

stati+ Inte!er I8)9
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int i8I9
Cyste".o(t.printlnBi/9JJ)
=
=
Example 2:

Example 3:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Inte!er E81)9
Inte!er y8E9
FFE9
Cyste".o(t.printlnBE/9JJ11
Cyste".o(t.printlnBy/9JJ1)
Cyste".o(t.printlnBE88y/9JJfalse
=
=
'iagram:


3)$

/ote: All wrapper ob,e+ts are i""(table t#at is on+e we +reated a wrapper ob,e+t we +anAt
perfor" any +#an!es in t#e eEistin! ob,e+t. If we are tryin! to perfor" any +#an!es wit# t#ose
+#an!es a new ob,e+t will be +reated.
Example 4:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Inte!er E8new Inte!erB1)/9
Inte!er y8new Inte!erB1)/9
Cyste".o(t.printlnBE88y/9JJfalse
=
=
'iagram:

Example 5:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Inte!er E8new Inte!erB1)/9
Inte!er y81)9
Cyste".o(t.printlnBE88y/9JJfalse
=
=
'iagram:

Example 6:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7

3)&

p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Inte!er E8new Inte!erB1)/9
Inte!er y8E9
Cyste".o(t.printlnBE88y/9JJtr(e
=
=
'iagram:

Example :
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Inte!er E81)9
Inte!er y81)9
Cyste".o(t.printlnBE88y/9JJtr(e
=
=
'iagram:

Example B:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Inte!er E81))9
Inte!er y81))9
Cyste".o(t.printlnBE88y/9JJtr(e
=
=
'iagram:


31)

Example V:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Inte!er E81)))9
Inte!er y81)))9
Cyste".o(t.printlnBE88y/9JJfalse
=
=
'iagram:

'iagram:

*on$lusions:
To i"ple"ent t#e A(toboEin! +on+ept in every wrapper +lass a b(ffer of ob,e+ts will be
+reated at t#e ti"e of +lass loadin!.
6y A(toboEin! if an ob,e+t is reV(ired to +reate 1
st
*% will +#e+? w#et#er t#at ob,e+t is
available in t#e b(ffer or not. If it is available t#en *% will re(se t#at b(ffered ob,e+t
instead of +reatin! new ob,e+t. If t#e ob,e+t is not available in t#e b(ffer t#en only a
new ob,e+t will be +reated. T#is approa+# i"proves perfor"an+e and "e"ory
(tili0ation.
6(t t#is b(ffer +on+ept is available only in t#e followin! +ases.
6yte Always
C#ort 412$ To 127
Inte!er 412$ To 127
Lon! 412$ To 127
'#ara+ter ) To 127
6oolean Always
In all t#e re"ainin! +ases +o"p(lsory a new ob,e+t will be +reated.




311

Examples:

Internally A(toboEin! +on+ept is i"ple"ented by (sin! val(eIfB/ "et#od #en+e t#e
above r(le appli+able even for val(eIfB/ "et#od also.
Examples:

/ote: @#en +o"pared wit# +onstr(+tors it is re+o""ended to (se val(eIfB/ "et#od to +reate
wrapper ob,e+t.
!verloading %it# respe$t to %ideningH 7uto,oxing and var<arg met#ods:
*ase 1: "idening vs 7uto,oxing9
"idening: 'onvertin! a lower data type into a #i!#er data type is +alled widenin!.
Example:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "et#odIneBlon! l/
7
Cyste".o(t.printlnBNwidenin!N/9
=
p(bli+ stati+ void "et#odIneBInte!er i/
7
Cyste".o(t.printlnBNa(toboEin!N/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E81)9
"et#odIneBE/9
=

312

=
!utput:
@idenin!
@idenin! do"inates A(toboEin!.
*ase 2: "idening vs var<arg met#od9
Example:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "et#odIneBlon! l/
7
Cyste".o(t.printlnBNwidenin!N/9
=
p(bli+ stati+ void "et#odIneBint... i/
7
Cyste".o(t.printlnBNvar4ar! "et#odN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E81)9
"et#odIneBE/9
=
=
!utput:
@idenin!
@idenin! do"inates var4ar! "et#od.
*ase 3: A(toboEin! vs var4ar! "et#od.
Example:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "et#odIneBInte!er i/
7
Cyste".o(t.printlnBNA(toboEin!N/9
=
p(bli+ stati+ void "et#odIneBint... i/
7
Cyste".o(t.printlnBNvar4ar! "et#odN/9

313

=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E81)9
"et#odIneBE/9
=
=
!utput:
A(toboEin!
A(toboEin! do"inates var4ar! "et#od.
In !eneral var4ar! "et#od will !et least priority. T#at is if no ot#er "et#od "at+#ed
t#en only var4ar! "et#od will !et +#an+e. It is eEa+tly sa"e as Kdefa(ltL +ase inside a
swit+#.
1; "idening
2; 7uto,oxing
3/ -ar<arg met#od9
*ase 4:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "et#odIneBLon! l/
7
Cyste".o(t.printlnBNLon!N/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E81)9
"et#odIneBE/9
=
=
!utput:
"et#odIneB,ava.lan!.Lon!/ in A(to6oEin!And;nb oEin!De"o +annot be applied to Bint/







314

'iagram:

@idenin! followed by A(toboEin! is not allowed in ,ava b(t A(toboEin! followed by
widenin! is allowed.
*ase 5:
i"port ,ava.(til.U9
+lass A(to6oEin!And;nboEin!De"o
7
p(bli+ stati+ void "et#odIneBIb,e+t o/
7
Cyste".o(t.printlnBNIb,e+tN/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int E81)9
"et#odIneBE/9
=
=
!utput:
Ib,e+t
'iagram:

"#i$# of t#e follo%ing de$larations are valid&
1/ Lon!l81)9Bvalid/
2/ Lon! l81)9Binvalid/B'.</
3/ Lon! l81)l9BA(toboEin!/
4/ :("ber n81)9 Bvalid/
5/ Ib,e+t o81).)9 Bvalid/
6/ int i81)l9 Binvalid/B'.</

315

0ava9I! 3a$+age
7genda:
1/ Hile
2/ Hile@riter
3/ HileReader
4/ 6(ffered@riter
5/ 6(fferedReader
6/ \rint@riter
File:
File fMne% File:]a,$9txt];E
T#is line 1
st
+#e+?s w#et#er ab+.tEt file is already available Bor/ not if it is already
available t#en KfL si"ply refers t#at file. If it is not already available t#en it wonAt +reate
any p#ysi+al file ,(st +reates a ,ava Hile ob,e+t represents na"e of t#e file.
Example:
i"port ,ava.io.U9
+lass HileDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
Hile f8new HileBN+ri+?et.tEtN/9
Cyste".o(t.printlnBf.eEistsB//9JJfalse
f.+reate:ewHileB/9
Cyste".o(t.printlnBf.eEistsB//9JJtr(e
=
=
A ,ava Hile ob,e+t +an represent a dire+tory also.
Example:
i"port ,ava.io.U9
+lass HileDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
Hile f8new HileBN+ri+?et123N/9
Cyste".o(t.printlnBf.eEistsB//9JJfalse
f."?dirB/9
Cyste".o(t.printlnBf.eEistsB//9JJtr(e
=

316

=
/ote: in ;:IP everyt#in! is a file- ,ava Kfile IIL is based on ;:IP operatin! syste" #en+e in ,ava
also we +an represent bot# files and dire+tories by Hile ob,e+t only.
File $lass $onstru$tors:
1; File fMne% File:2tring name;E
'reates a ,ava Hile ob,e+t t#at represents na"e of t#e file or dire+tory.
2; File fMne% File:2tring su,dirnameH2tring name;E
'reates a Hile ob,e+t t#at represents na"e of t#e file or dire+tory present in spe+ified
s(b dire+tory.
3; File fMne% File:File su,dirH2tring name;E
ReAuirement: @rite +ode to +reate a file na"ed wit# de"o.tEt in +(rrent wor?in! dire+tory.
3rogram:
i"port ,ava.io.U9
+lass HileDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
Hile f8new HileBNde"o.tEtN/9
f.+reate:ewHileB/9
=
=
ReAuirement: @rite +ode to +reate a dire+tory na"ed wit# b#as?ar123 in +(rrent wor?in!
dire+tory and +reate a file na"ed wit# ab+.tEt in t#at dire+tory.
3rogram:
i"port ,ava.io.U9
+lass HileDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
Hile f18new HileBNb#as?ar123N/9
f1."?dirB/9
Hile f28new HileBNb#as?ar123N-Nab+.tEtN/9
f2.+reate:ewHileB/9
=
=
ReAuirement: @rite +ode to +reate a file na"ed wit# de"o.tEt present in +.YEy0 folder.



317

3rogram:
i"port ,ava.io.U9
+lass HileDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
Hile f8new HileBN+.YYb#as?arN-Nde"o.tEtN/9
f.+reate:ewHileB/9
=
=
Import met#ods of file $lass:
1; ,oolean exists:;E
Ret(rns tr(e if t#e p#ysi+al file or dire+tory available.
2; ,oolean $reate/e%File:;E
T#is "et#od 1
st
+#e+?s w#et#er t#e p#ysi+al file is already available or not if it is already
available t#en t#is "et#od si"ply ret(rns false. If t#is file is not already available t#en it
will +reate a new file and ret(rns tr(e
3; ,oolean m+dir:;E
4; ,oolean isFile:;E
Ret(rns tr(e if t#e Hile ob,e+t represents a p#ysi+al file.
5; ,oolean is'ire$tor(:;E
6; 2tringTU list:;E
It ret(rns t#e na"es of all files and s(bdire+tories present in t#e spe+ified dire+tory.
; long lengt#:;E
Ret(rns t#e no of +#ara+ters present in t#e file.
B; ,oolean delete:;E
To delete a file or dire+tory.
File"riter:
6y (sin! Hile@riter we +an write +#ara+ter data to t#e file.
*onstru$tors:
File"riter f%Mne% File"riter:2tring name;E
File"riter f%Mne% File"riter:File f;E
T#e above 2 +onstr(+tors "eant for overridin!.
Instead of overridin! if we want append operation t#en we s#o(ld !o for t#e followin! 2
+onstr(+tors.
File"riter f%Mne% File"riter:2tring nameH,oolean append;E
File"riter f%Mne% File"riter:File fH,oolean append;E

31$

If t#e spe+ified p#ysi+al file is not already available t#en t#ese +onstr(+tors will +reate
t#at file.
=et#ods:
1; %rite:int $#;E
To write a sin!le +#ara+ter to t#e file.
2; %rite:$#arTU $#;E
To write an array of +#ara+ters to t#e file.
3; %rite:2tring s;E
To write a Ctrin! to t#e file.
4; flus#:;E
To !ive t#e !(arantee t#e last +#ara+ter of t#e data also added to t#e file.
5; $lose:;E
To +lose t#e strea".
Example:
i"port ,ava.io.U9
+lass Hile@riterDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
Hile@riter fw8new Hile@riterBN+ri+?et.tEtN-tr(e/9
fw.writeB&$/9JJaddin! a sin!le +#ara+ter
fw.writeBN#as?arYnsoftware sol(tionsN/9
fw.writeBNYnN/9
+#arD> +#87QaQ-QbQ-Q+Q=9
fw.writeB+#/9
fw.writeBNYnN/9
fw.fl(s#B/9
fw.+loseB/9
=
=
!utput:
6#as?ar
Coftware sol(tions
A6'
FileReader: 6y (sin! HileReader we +an read +#ara+ter data fro" t#e file.
*onstru$tors:
FileReader frMne% FileReader:2tring name;E
FileReader frMne% FileReader :File f;E

31&

=et#ods:
1; int read:;E
It atte"pts to read neEt +#ara+ter fro" t#e file and ret(rn its ;ni+ode val(e. If t#e neEt
+#ara+ter is not available t#en we will !et 41.
2; int read:$#arTU $#;E
It atte"pts to read eno(!# +#ara+ters fro" t#e file into +#arD> array and ret(rns t#e no
of +#ara+ters +opied fro" t#e file into +#arD> array.
3; void $lose:;E
7pproa$# 1:
i"port ,ava.io.U9
+lass HileReaderDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
HileReader fr8new HileReaderBN+ri+?et.tEtN/9
int i8fr.readB/9
w#ileBib841/
7
Cyste".o(t.printBB+#ar/i/9
i8fr.readB/9
=
=
=
!utput:
6#as?ar
Coftware sol(tions
A6'
7pproa$# 2:
i"port ,ava.io.U9
+lass HileReaderDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
Hile f8new HileBN+ri+?et.tEtN/9
HileReader fr8new HileReaderBf/9
+#arD> +#8new +#arDBint/f.len!t#B/>9
fr.readB+#/9
forB+#ar +#1.+#/

32)

7
Cyste".o(t.printB+#1/9
=
=
=
!utput:
6R
Coftware sol(tions.
.sage of File"riter and FileReader is not re$ommended ,e$ause:
1/ @#ile writin! data by Hile@riter +o"p(lsory we s#o(ld insert line separatorBYn/
"an(ally w#i+# is a bi!!er #eada+#e to t#e pro!ra""er.
2/ @#ile readin! data by HileReader we #ave to read +#ara+ter by +#ara+ter w#i+# is not
+onvent to t#e pro!ra""er.
3/ To over+o"e t#ese li"itations we s#o(ld !o for 6(ffered@riter and 6(fferedReader
+on+epts.
1uffered"riter:
6y (sin! 6(ffered@riter ob,e+t we +an write +#ara+ter data to t#e file.
*onstru$tors:
6(ffered@riter bw8new 6(ffered@riterBwriter w/9
6(ffered@riter bw8new 6(ffered@riterBwriter w-int b(ffersi0e/9
/ote:
6(ffered@riter never +o""(ni+ates dire+tly wit# t#e file it s#o(ld +o""(ni+ates via
so"e writer ob,e+t.
"#i$# of t#e follo%ing de$larations are valid&
1; 1uffered"riter ,%Mne% 1uffered"riter:>$ri$+et9txt@;E :invalid;
2; 1uffered"riter ,%Mne% 1uffered"riter :ne% File:>$ri$+et9txt@;;E :invalid;
3; 1uffered"riter ,%Mne% 1uffered"riter :ne% File"riter:>$ri$+et9txt@;;E :valid;

=et#ods:
1; %rite:int $#;E
2; %rite:$#arTU $#;E
3; %rite:2tring s;E
4; flus#:;E
5; $lose:;E
6; ne%line:;E
Inserting a ne% line $#ara$ter to t#e file9

321

@#en +o"pared wit# Hile@riter w#i+# of t#e followin! +apabilityBfa+ility/ is available as
"et#od in 6(ffered@riter.
1/ @ritin! data to t#e file.BE/
2/ 'losin! t#e writer.BE/
3/ Hl(s# t#e writer.BE/
4/ Insertin! newline +#ara+ter. B /
Example:
i"port ,ava.io.U9
+lass 6(ffered@riterDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
Hile@riter fw8new Hile@riterBN+ri+?et.tEtN/9
6(ffered@riter bw8new 6(ffered@riterBfw/9
bw.writeB1))/9
bw.newLineB/9
+#arD> +#87QaQ-QbQ-Q+Q-QdQ=9
bw.writeB+#/9
bw.newLineB/9
bw.writeBNb#as?arN/9
bw.newLineB/9
bw.writeBNsoftware sol(tionsN/9
bw.fl(s#B/9
bw.+loseB/9
=
=
!utput:
d
ab+d
b#as?ar
software sol(tions
1ufferedReader:
T#is is t#e "ost en#an+edBbetter/ Reader to read +#ara+ter data fro" t#e file.
*onstru$tors:
1ufferedReader ,rMne% 1ufferedReader:Reader r;E
1ufferedReader ,rMne% 1ufferedReader:Reader rHint ,uffersi4e;E



322

/ote:
6(fferedReader +an not +o""(ni+ate dire+tly wit# t#e Hile it s#o(ld +o""(ni+ate via
so"e Reader ob,e+t. T#e "ain advanta!e of 6(fferedReader over HileReader is we +an
read data line by line instead of +#ara+ter by +#ara+ter.
=et#ods:
1; int read:;E
2; int read:$#arTU $#;E
3; 2tring readLine:;E
It atte"pts to read and ret(rn neEt line fro" t#e Hile. if t#e neEt line is not available
t#en t#is "et#od ret(rns n(ll.
4; void $lose:;E
Example:
i"port ,ava.io.U9
+lass 6(fferedReaderDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
HileReader fr8new HileReaderBN+ri+?et.tEtN/9
6(fferedReader br8new 6(fferedReaderBfr/9
Ctrin! line8br.readLineB/9
w#ileBlineb8n(ll/
7
Cyste".o(t.printlnBline/9
line8br.readLineB/9
=
br.+loseB/9
=
=
/ote:
@#enever we are +losin! 6(fferedReader a(to"ati+ally (nderlyin! HileReader will be
+losed it is not reV(ired to +lose eEpli+itly.

<ven t#is r(le is appli+able for 6(ffered@riter also.
3rint"riter:
T#is is t#e "ost en#an+ed @riter to write teEt data to t#e file.

323

6y (sin! Hile@riter and 6(ffered@riter we +an write only +#ara+ter data to t#e Hile b(t
by (sin! \rint@riter we +an write any type of data to t#e Hile.
*onstru$tors:
3rint"riter p%Mne% 3rint"riter:2tring name;E
3rint"riter p%Mne% 3rint"riter:File f;E
3rint"riter p%Mne% 3rint"riter:"riter %;E
\rint@riter +an +o""(ni+ate eit#er dire+tly to t#e Hile or via so"e @riter ob,e+t also.
=et#ods:
writeBint +#/9
write B+#arD> +#/9
writeBCtrin! s/9
fl(s#B/9
+loseB/9
printB+#ar +#/9
print Bint i/9
print Bdo(ble d/9
print Bboolean b/9
print BCtrin! s/9
printlnB+#ar +#/9
println Bint i/9
printlnBdo(ble d/9
printlnBboolean b/9
printlnBCtrin! s/9
Example:
i"port ,ava.io.U9
+lass \rint@riterDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
Hile@riter fw8new Hile@riterBN+ri+?et.tEtN/9
\rint@riter o(t8new \rint@riterBfw/9
o(t.writeB1))/9
o(t.printlnB1))/9
o(t.printlnBtr(e/9
o(t.printlnBQ+Q/9
o(t.printlnBNb#as?arN/9
o(t.fl(s#B/9

324

o(t.+loseB/9
=
=
!utput:
d1))
tr(e
+
b#as?ar
"#at is t#e differen$e ,et%een %rite:155; and print:155;&
In t#e +ase of writeB1))/ t#e +orrespondin! +#ara+ter KdL will be added to t#e Hile b(t in
t#e +ase of printB1))/ K1))L val(e will be added dire+tly to t#e Hile.
/ote 1:
1/ T#e "ost en#an+ed Reader to read +#ara+ter data fro" t#e Hile is 6(fferedReader.
2/ T#e "ost en#an+ed @riter to write +#ara+ter data to t#e Hile is \rint@riter.
/ote 2:
1/ In !eneral we +an (se Readers and @riters to #andle +#ara+ter data. @#ere as we +an
(se Inp(tCtrea"s and I(tp(tCtrea"s to #andle binary dataBli?e i"a!es- a(dio files-
video files et+/.
2/ @e +an (se I(tp(tCtrea" to write binary data to t#e Hile and we +an (se Inp(tCtrea"
to read binary data fro" t#e Hile.
'iagram:










325

ReAuirement: @rite a pro!ra" to perfor" Hile "er!eB+o"bine/ operation.
'iagram:

3rogram:
i"port ,ava.io.U9
+lass Hile@riterDe"o1
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
\rint@riter pw8new \rint@riterBNfile3.tEtN/9
6(fferedReader br8new 6(fferedReaderBnew HileReaderBNfile1.tEtN//9
Ctrin! line8br.readLineB/9
w#ileBlineb8n(ll/
7
pw.printlnBline/9
line8br.readLineB/9
=
br8new 6(fferedReaderBnew HileReaderBNfile2.tEtN//9 reuse
line8br.readLineB/9
w#ileBlineb8n(ll/
7
pw.printlnBline/9
line8br.readLineB/9
=
pw.fl(s#B/9
br.+loseB/9
pw.+loseB/9
=
=
ReAuirement: @rite a pro!ra" to perfor" file "er!e operation w#ere "er!in! s#o(ld be
perfor"ed line by line alternatively.

326

'iagram:

3rogram:
i"port ,ava.io.U9
+lass Hile@riterDe"o1
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
\rint@riter pw8new \rint@riterBNfile3.tEtN/9
6(fferedReader br18new 6(fferedReaderBnew HileReaderBNfile1.tEtN//9
6(fferedReader br28new 6(fferedReaderBnew HileReaderBNfile2.tEtN//9
Ctrin! line18br1.readLineB/9
Ctrin! line28br2.readLineB/9
w#ileBline1b8n(llOOline2b8n(ll/
7
ifBline1b8n(ll/
7
pw.printlnBline1/9
line18br1.readLineB/9
=
ifBline2b8n(ll/
7
pw.printlnBline2/9
line28br2.readLineB/9
=
=
pw.fl(s#B/9
br1.+loseB/9
br2.+loseB/9
pw.+loseB/9
=

327

=
ReAuirement: @rite a pro!ra" to delete d(pli+ate n("bers fro" t#e file.
'iagram:

3rogram:
i"port ,ava.io.U9
+lass Hile@riterDe"o1
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
6(fferedReader br18new 6(fferedReaderBnew HileReaderBNinp(t.tEtN//9
\rint@riter o(t8new \rint@riterBNo(tp(t.tEtN/9
Ctrin! tar!et8br1.readLineB/9
w#ileBtar!etb8n(ll/
7
boolean available8false9
6(fferedReader br28new 6(fferedReaderBnew HileReaderBNo(tp(t.tEtN//9
Ctrin! line8br2.readLineB/9
w#ileBlineb8n(ll/
7
ifBtar!et.eV(alsBline//
7
available8tr(e9
brea?9
=
line8br2.readLineB/9
=
ifBavailable88false/
7
o(t.printlnBtar!et/9
o(t.fl(s#B/9
=
tar!et8br1.readLineB/9

32$

=
=
=
ReAuirement: write a pro!ra" to perfor" file eEtra+tion operation.
'iagram:

3rogram:
i"port ,ava.io.U9
+lass Hile@riterDe"o1
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
6(fferedReader br18new 6(fferedReaderBnew HileReaderBNinp(t.tEtN//9
\rint@riter pw8new \rint@riterBNo(tp(t.tEtN/9
Ctrin! line8br1.readLineB/9
w#ileBlineb8n(ll/
7
boolean available8false9
6(fferedReader br28new 6(fferedReaderBnew HileReaderBNdelete.tEtN//9
Ctrin! tar!et8br2.readLineB/9
w#ileBtar!etb8n(ll/
7
ifBline.eV(alsBtar!et//
7
available8tr(e9
brea?9
=
tar!et8br2.readLineB/9
=
ifBavailable88false/
7

32&

pw.printlnBline/9
=
line8br1.readLineB/9
=
pw.fl(s#B/9
=
=






















33)

2ERI7LIK78I!/
1. Introd(+tion.
2. Ib,e+t !rap# in seriali0ation.
3. +(sto"i0ed seriali0ation.
4. Ceriali0ation wit# respe+t in#eritan+e.
2eriali4ation: T#e pro+ess of savin! Bor/ writin! state of an ob,e+t to a file is +alled seriali0ation
b(t stri+tly spea?in! it is t#e pro+ess of +onvertin! an ob,e+t fro" ,ava s(pported for" to eit#er
networ? s(pported for" Bor/ file s(pported for".
6y (sin! HileI(tp(tCtrea" and Ib,e+tI(tp(tCtrea" +lasses we +an a+#ieve seriali0ation
pro+ess.
'iagram:

'e<2eriali4ation: T#e pro+ess of readin! state of an ob,e+t fro" a file is +alled DeCeriali0ation
b(t stri+tly spea?in! it is t#e pro+ess of +onvertin! an ob,e+t fro" file s(pported for" Bor/
networ? s(pported for" to ,ava s(pported for".
6y (sin! HileInp(tCtrea" and Ib,e+tInp(tCtrea" +lasses we +an a+#ieve DeCeriali0ation.
'iagram:

Example 1:
i"port ,ava.io.U9
+lass Do! i"ple"ents Ceriali0able
7
int i81)9
int ,82)9

331

=
+lass Ceriali0ableDe"o
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/t#rows <E+eption7
Do! d18new Do!B/9
Cyste".o(t.printlnBNCeriali0ation startedN/9
HileI(tp(tCtrea" fos8new HileI(tp(tCtrea"BNab+.serN/9
Ib,e+tI(tp(tCtrea" oos8new Ib,e+tI(tp(tCtrea"Bfos/9
oos.writeIb,e+tBd1/9
Cyste".o(t.printlnBNCeriali0ation endedN/9
Cyste".o(t.printlnBNDeseriali0ation startedN/9
HileInp(tCtrea" fis8new HileInp(tCtrea"BNab+.serN/9
Ib,e+tInp(tCtrea" ois8new Ib,e+tInp(tCtrea"Bfis/9
Do! d28BDo!/ois.readIb,e+tB/9
Cyste".o(t.printlnBNDeseriali0ation endedN/9
Cyste".o(t.printlnBd2.iFN................NFd2.,/9
=
=
!utput:
Ceriali0ation started
Ceriali0ation ended
Deseriali0ation started
Deseriali0ation ended
1)................2)
'iagram:

/ote: @e +an perfor" Ceriali0ation only for Cerili0able ob,e+ts.
An ob,e+t is said to be Cerili0able if and only if t#e +orrespondin! +lass i"ple"ents
Ceriali0able interfa+e.

332

Ceriali0able interfa+e present in java9io pa$+age and does not +ontain any "et#ods. It is
"ar?er interfa+e. T#e reV(ired ability will be provided a(to"ati+ally by *%.
@e +an add any no. If ob,e+ts to t#e file and we +an read all t#ose ob,e+ts fro" t#e file
b(t in w#i+# order we wrote ob,e+ts in t#e sa"e order only t#e ob,e+ts will +o"e ba+?.
T#at is order is i"portant.
Example2:
i"port ,ava.io.U9
+lass Do! i"ple"ents Ceriali0able
7
int i81)9
int ,82)9
=
+lass 'at i"ple"ents Ceriali0able
7
int i83)9
int ,84)9
=
+lass Ceriali0ableDe"o
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/t#rows <E+eption7
Do! d18new Do!B/9
'at +18new 'atB/9
Cyste".o(t.printlnBNCeriali0ation startedN/9
HileI(tp(tCtrea" fos8new HileI(tp(tCtrea"BNab+.serN/9
Ib,e+tI(tp(tCtrea" oos8new Ib,e+tI(tp(tCtrea"Bfos/9
oos.writeIb,e+tBd1/9
oos.writeIb,e+tB+1/9
Cyste".o(t.printlnBNCeriali0ation endedN/9
Cyste".o(t.printlnBNDeseriali0ation startedN/9
HileInp(tCtrea" fis8new HileInp(tCtrea"BNab+.serN/9
Ib,e+tInp(tCtrea" ois8new Ib,e+tInp(tCtrea"Bfis/9
Do! d28BDo!/ois.readIb,e+tB/9
'at +28B'at/ois.readIb,e+tB/9
Cyste".o(t.printlnBNDeseriali0ation endedN/9
Cyste".o(t.printlnBd2.iFN................NFd2.,/9
Cyste".o(t.printlnB+2.iFN................NF+2.,/9
=
=

333

!utput:
Ceriali0ation started
Ceriali0ation ended
Deseriali0ation started
Deseriali0ation ended
1)................2)
3)................4)
8ransient +e(%ord:
@#ile perfor"in! seriali0ation if we donAt want to seriali0e t#e val(e of a parti+(lar
variable t#en we s#o(ld de+lare t#at variable wit# KtransientL ?eyword.
At t#e ti"e of seriali0ation *% i!nores t#e ori!inal val(e of transient variable and save
defa(lt val(e.
T#at is transient "eans Knot to seriali0eL.
2tati$ -s 8ransient:
stati+ variable is not part of ob,e+t state #en+e t#ey wonAt parti+ipate in seriali0ation
be+a(se of t#is de+larin! a stati+ variable as transient t#ese is no (se.
8ransient -s Final:
final variables will be parti+ipated into seriali0ation dire+tly by t#eir val(es. Sen+e
de+larin! a final variable as transient t#ere is no (se.
Example 3:
i"port ,ava.io.U9
+lass Do! i"ple"ents Ceriali0able
7
stati+ transient int i81)9
final transient int ,82)9
=
+lass Ceriali0ableDe"o
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/t#rows <E+eption7
Do! d18new Do!B/9
HileI(tp(tCtrea" fos8new HileI(tp(tCtrea"BNab+.serN/9
Ib,e+tI(tp(tCtrea" oos8new Ib,e+tI(tp(tCtrea"Bfos/9
oos.writeIb,e+tBd1/9
HileInp(tCtrea" fis8new HileInp(tCtrea"BNab+.serN/9
Ib,e+tInp(tCtrea" ois8new Ib,e+tInp(tCtrea"Bfis/9
Do! d28BDo!/ois.readIb,e+tB/9
Cyste".o(t.printlnBd2.iFN................NFd2.,/9
=

334

=
!utput:
1)................2)
'iagram:


8a,le:
de+laration o(tp(t
int i81)9
int ,82)9
1)................2)
transient int i81)9
int ,82)9
)................2)
transient int i81)9
transient stati+ int ,82)9
)................2)
transient final int i81)9
transient int ,82)9
1)................)
transient final int i81)9
transient stati+ int ,82)9
1)................2)
!,je$t grap# in seriali4ation:
@#enever we are seriali0in! an ob,e+t t#e set of all ob,e+ts w#i+# are rea+#able fro"
t#at ob,e+t will be seriali0ed a(to"ati+ally. T#is !ro(p of ob,e+ts is not#in! b(t ob,e+t
!rap# in seriali0ation.
In ob,e+t !rap# every ob,e+t s#o(ld be Ceriali0able ot#erwise we will !et r(nti"e
eE+eption sayin! K:otCeriali0able<E+eptionL.
Example 4:
i"port ,ava.io.U9
+lass Do! i"ple"ents Ceriali0able
7
'at +8new 'atB/9
=

335

+lass 'at i"ple"ents Ceriali0able
7
Rat r8new RatB/9
=
+lass Rat i"ple"ents Ceriali0able
7
int ,82)9
=
+lass Ceriali0ableDe"o
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/t#rows <E+eption7
Do! d18new Do!B/9
HileI(tp(tCtrea" fos8new HileI(tp(tCtrea"BNab+.serN/9
Ib,e+tI(tp(tCtrea" oos8new Ib,e+tI(tp(tCtrea"Bfos/9
oos.writeIb,e+tBd1/9
HileInp(tCtrea" fis8new HileInp(tCtrea"BNab+.serN/9
Ib,e+tInp(tCtrea" ois8new Ib,e+tInp(tCtrea"Bfis/9
Do! d28BDo!/ois.readIb,e+tB/9
Cyste".o(t.printlnBd2.+.r.,/9
=
=
!utput:
2)
'iagram:

In t#e above eEa"ple w#enever we are seriali0in! Do! ob,e+t a(to"ati+ally 'at and Rat
ob,e+ts will be seriali0ed be+a(se t#ese are part of ob,e+t !rap# of Do! ob,e+t.

336

A"on! Do!- 'at- Rat if at least one ob,e+t is not seriali0able t#en we will !et r(nti"e
eE+eption sayin! K:otCeriali0able<E+eptionL.
*ustomi4ed seriali4ation:
Example 5:
i"port ,ava.io.U9
+lass A++o(nt i"ple"ents Ceriali0able
7
Ctrin! (ser:a"e8N6#as?arN9
transient Ctrin! pwd8N?a,alN9
=
+lass '(sto"i0edCeriali0eDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption7
A++o(nt a18new A++o(ntB/9
Cyste".o(t.printlnBa1.(ser:a"eFN.........NFa1.pwd/9
HileI(tp(tCtrea" fos8new HileI(tp(tCtrea"BNab+.serN/9
Ib,e+tI(tp(tCtrea" oos8new Ib,e+tI(tp(tCtrea"Bfos/9
oos.writeIb,e+tBa1/9
HileInp(tCtrea" fis8new HileInp(tCtrea"BNab+.serN/9
Ib,e+tInp(tCtrea" ois8new Ib,e+tInp(tCtrea"Bfis/9
A++o(nt a28BA++o(nt/ois.readIb,e+tB/9
Cyste".o(t.printlnBa2.(ser:a"eFN.........NFa2.pwd/9
=
=
!utput:
6#as?ar.........?a,al
6#as?ar.........n(ll
'iagram:


337

In t#e above eEa"ple before seriali0ation A++o(nt ob,e+t +an provide proper (serna"e
and password. 6(t after Deseriali0ation A++o(nt ob,e+t +an provide only (serna"e b(r
not password. T#is is d(e to de+larin! password as transient. Sen+e doin! defa(lt
seriali0ation t#ere "ay be a +#an+e of loss of infor"ation d(e to transient ?eyword.
@e +an re+over t#is loss of infor"ation by (sin! +(sto"i0ed seriali0ation.
@e +an i"ple"ents +(sto"i0ed seriali0ation by (sin! t#e followin! two "et#ods.
1/ private void writeIb,e+tBI(tp(tCtrea" os/ t#rows <E+eption.
T#is "et#od will be eEe+(ted a(to"ati+ally by ,v" at t#e ti"e of seriali0ation.
It is a +allba+? "et#od. Sen+e at t#e ti"e of seriali0ation if we want to perfor" any
eEtra wor? we #ave to define t#at in t#is "et#od only.
2/ private void readIb,e+tBInp(tCtrea" is/t#rows <E+eption.
T#is "et#od will be eEe+(ted a(to"ati+ally by *% at t#e ti"e of Deseriali0ation. Sen+e
at t#e ti"e of Deseriali0ation if we want to perfor" any eEtra a+tivity we #ave to define
t#at in t#is "et#od only.
Example 6: 'emo program for $ustomi4ed seriali4ation to re$over loss of information %#i$# is
#appen due to transient +e(%ord9
i"port ,ava.io.U9
+lass A++o(nt i"ple"ents Ceriali0able
7
Ctrin! (ser:a"e8N6#as?arN9
transient Ctrin! pwd8N?a,alN9
private void writeIb,e+tBIb,e+tI(tp(tCtrea" os/t#rows <E+eption
7
os.defa(lt@riteIb,e+tB/9
Ctrin! epwd8N123NFpwd9
os.writeIb,e+tBepwd/9
=
private void readIb,e+tBIb,e+tInp(tCtrea" is/t#rows <E+eption7
is.defa(ltReadIb,e+tB/9
Ctrin! epwd8BCtrin!/is.readIb,e+tB/9
pwd8epwd.s(bstrin!B3/9
=
=
+lass '(sto"i0edCeriali0eDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption7
A++o(nt a18new A++o(ntB/9
Cyste".o(t.printlnBa1.(ser:a"eFN.........NFa1.pwd/9

33$

HileI(tp(tCtrea" fos8new HileI(tp(tCtrea"BNab+.serN/9
Ib,e+tI(tp(tCtrea" oos8new Ib,e+tI(tp(tCtrea"Bfos/9
oos.writeIb,e+tBa1/9
HileInp(tCtrea" fis8new HileInp(tCtrea"BNab+.serN/9
Ib,e+tInp(tCtrea" ois8new Ib,e+tInp(tCtrea"Bfis/9
A++o(nt a28BA++o(nt/ois.readIb,e+tB/9
Cyste".o(t.printlnBa2.(ser:a"eFN.........NFa2.pwd/9
=
=
!utput:
6#as?ar.........?a,al
6#as?ar.........?a,al
'iagram:

At t#e ti"e of A++o(nt ob,e+t seriali0ation *% will +#e+? is t#ere any writeIb,e+tB/
"et#od in A++o(nt +lass or not. If it is not available t#en *% is responsible to perfor"
seriali0ationBdefa(lt seriali0ation/. If A++o(nt +lass +ontains writeIb,e+tB/ "et#od t#en
*% feels very #appy and eEe+(tes t#at A++o(nt +lass writeIb,e+tB/ "et#od. T#e sa"e
r(le is appli+able for readIb,e+tB/ "et#od also.
2eriali4ation %it# respe$t to in#eritan$e:
*ase 1:
If parent +lass i"ple"ents Ceriali0able t#en a(to"ati+ally every +#ild +lass by defa(lt
i"ple"ents Ceriali0able. T#at is Ceriali0able nat(re is in#eritin! fro" parent to +#ild.
Example :
i"port ,ava.io.U9
+lass Ani"al i"ple"ents Ceriali0able
7
int i81)9
=

33&

+lass Do! eEtends Ani"al
7
int ,82)9
=
+lass Ceriali0able@RTIn#eritan+e
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption7
Do! d18new Do!B/9
Cyste".o(t.printlnBd1.iFN........NFd1.,/9
HileI(tp(tCtrea" fos8new HileI(tp(tCtrea"BNab+.serN/9
Ib,e+tI(tp(tCtrea" oos8new Ib,e+tI(tp(tCtrea"Bfos/9
oos.writeIb,e+tBd1/9
HileInp(tCtrea" fis8new HileInp(tCtrea"BNab+.serN/9
Ib,e+tInp(tCtrea" ois8new Ib,e+tInp(tCtrea"Bfis/9
Do! d28BDo!/ois.readIb,e+tB/9
Cyste".o(t.printlnBd2.iFN........NFd2.,/9
=
=
I(tp(t.
1)........2)
1)........2)
<ven t#o(!# Do! +lass does not i"ple"ents Ceriali0able interfa+e eEpli+itly b(t we +an
Ceriali0e Do! ob,e+t be+a(se its parent +lass ani"al already i"ple"ents Ceriali0able
interfa+e.
*ase 2:
<ven t#o(!# parent +lass does not i"ple"ents Ceriali0able we +an seriali0e +#ild ob,e+t
if +#ild +lass i"ple"ents Ceriali0able interfa+e.
At t#e ti"e of seriali0ation *% i!nores t#e val(es of instan+e variables w#i+# are
+o"in! fro" non Ceriali0able parent *% saves defa(lt val(es for t#ose variables.
At t#e ti"e of Deseriali0ation *% +#e+?s w#et#er any parent +lass is non Ceriali0able or
not. If any parent +lass is non Ceriali0able *% +reates a separate ob,e+t for every non
Ceriali0able parent and s#ares its instan+e variables to t#e +(rrent ob,e+t.
Hor t#is *% always +alls no ar! +onstr(+torBdefa(lt +onstr(+tor/ of t#at non Ceriali0able
parent #en+e every non Ceriali0able parent s#o(ld +o"p(lsory +ontain no ar!
+onstr(+tor ot#erwise we will !et r(nti"e eE+eption.
Example B:
i"port ,ava.io.U9
+lass Ani"al

34)

7
int i81)9
Ani"alB/7
Cyste".o(t.printlnBNAni"al +onstr(+tor +alledN/9
=
=
+lass Do! eEtends Ani"al i"ple"ents Ceriali0able
7
int ,82)9
Do!B/7
Cyste".o(t.printlnBNDo! +onstr(+tor +alledN/9
=
=
+lass Ceriali0able@RTIn#eritan+e
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption7
Do! d18new Do!B/9
d1.i8$$$9
d1.,8&&&9
HileI(tp(tCtrea" fos8new HileI(tp(tCtrea"BNab+.serN/9
Ib,e+tI(tp(tCtrea" oos8new Ib,e+tI(tp(tCtrea"Bfos/9
oos.writeIb,e+tBd1/9
Cyste".o(t.printlnBNDeseriali0ation startedN/9
HileInp(tCtrea" fis8new HileInp(tCtrea"BNab+.serN/9
Ib,e+tInp(tCtrea" ois8new Ib,e+tInp(tCtrea"Bfis/9
Do! d28BDo!/ois.readIb,e+tB/9
Cyste".o(t.printlnBd2.iFN.........NFd2.,/9
=
=
!utput:
Ani"al +onstr(+tor +alled
Do! +onstr(+tor +alled
Deseriali0ation started
Ani"al +onstr(+tor +alled
1).........&&&




341

'iagram:



















342

*olle$tions
An array is an indeEed +olle+tion of fiEed no of #o"o!eneo(s data ele"ents. Bor/
An array represents a !ro(p of ele"ents of sa"e data type.
T#e "ain advanta!e of array is we +an represent #(!e no of ele"ents by (sin! sin!le
variable. Co t#at readability of t#e +ode will be i"proved.
Limitations of !,je$tTU arra(:
1/ Arrays are fiEed in si0e t#at is on+e we +reated an array t#ere is no +#an+e of in+reasin!
Bor/ de+reasin! t#e si0e based on o(r reV(ire"ent #en+e to (se arrays +on+ept
+o"p(lsory we s#o(ld ?now t#e si0e in advan+e w#i+# "ay not possible always.
2/ Arrays +an #old only #o"o!eneo(s data ele"ents.
Example:
Ct(dentD> s8new Ct(dentD1))))>9
sD)>8new Ct(dentB/9JJvalid
sD1>8new '(sto"erB/9JJinvalidB+o"pile ti"e error/
*ompile time error:
Test.,ava.7. +annot find sy"bol
Cy"bol. +lass '(sto"er
Lo+ation. +lass Test
sD1>8new '(sto"erB/9
3/ 6(t we +an resolve t#is proble" by (sin! ob,e+t type arrayBIb,e+tD>/.
Example:
Ib,e+tD> o8new Ib,e+tD1))))>9
oD)>8new Ct(dentB/9
oD1>8new '(sto"erB/9
4/ Arrays +on+ept is not i"ple"ented based on so"e data str(+t(re #en+e ready4"ade
"et#ods s(pport we +anAt eEpert. Hor every reV(ire"ent we #ave to write t#e +ode
eEpli+itly.
To over+o"e t#e above li"itations we s#o(ld !o for +olle+tions +on+ept.
1/ 'olle+tions are !rowable in nat(re t#at is based on o(r reV(ire"ent we +an in+rease
Bor/ de+rease t#e si0e #en+e "e"ory point of view +olle+tions +on+ept is re+o""ended
to (se.
2/ 'olle+tions +an #old bot# #o"o!eneo(s and #etero!eneo(s ob,e+ts.
3/ <very +olle+tion +lass is i"ple"ented based on so"e standard data str(+t(re #en+e for
every reV(ire"ent ready4"ade "et#od s(pport is available bein! a pro!ra""er we +an
(se t#ese "et#ods dire+tly wit#o(t writin! t#e f(n+tionality on o(r own.



343

'ifferen$es ,et%een 7rra(s and *olle$tions&
7rra(s *olle$tions
1/ Arrays are fiEed in si0e. 1/ 'olle+tions are !rowable in nat(re.
2/ %e"ory point of view arrays are not
re+o""ended to (se.
2/ %e"ory point of view +olle+tions are
#i!#ly re+o""ended to (se.
3/ \erfor"an+e point of view arrays are
re+o""ended to (se.
3/ \erfor"an+e point of view +olle+tions
are not re+o""ended to (se.
4/ Arrays +an #old only #o"o!eneo(s
data type ele"ents.
4/ 'olle+tions +an #old bot#
#o"o!eneo(s and #etero!eneo(s
ele"ents.
5/ T#ere is no (nderlyin! data str(+t(re
for arrays and #en+e t#ere is no
ready"ade "et#od s(pport.
5/ <very +olle+tion +lass is i"ple"ented
based on so"e standard data str(+t(re
and #en+e ready"ade "et#od s(pport
is available.
6/ Arrays +an #old bot# pri"itives and
ob,e+t types.
6/ 'olle+tions +an #old only ob,e+ts b(t
not pri"itives.
*olle$tion: If we want to represent a !ro(p of ob,e+ts as sin!le entity t#en we s#o(ld !o for
+olle+tions.
*olle$tion frame%or+: It defines several +lasses and interfa+es to represent a !ro(p of ob,e+ts
as a sin!le entity.
0ava *??
'olle+tion 'ontainers
'olle+tion fra"ewor? CTLBCtandard Te"plate Library/
V:/ine; +e( interfa$es of $olle$tion frame%or+:
1. 'olle+tion 2. List 3. Cet
4. CortedCet 5. :avi!ableCet 6. _(e(e
7. %ap $. Corted%ap &. :avi!able%ap
*olle$tion:
1/ If we want to represent a !ro(p of Kindivid(al ob,e+tsL as a sin!le entity t#en we s#o(ld
!o for +olle+tion.
2/ In !eneral we +an +onsider +olle+tion as root interfa+e of entire +olle+tion fra"ewor?.
3/ 'olle+tion interfa+e defines t#e "ost +o""on "et#ods w#i+# +an be appli+able for any
+olle+tion ob,e+t.
List:
1/ It is t#e +#ild interfa+e of 'olle+tion.
2/ If we want to represent a !ro(p of individ(al ob,e+ts as a sin!le entity w#ere Kd(pli+ates
are allow and insertion order "(st be preservedL t#en we s#o(ld !o for List interfa+e.




344

'iagram:

e+tor and Cta+? +lasses are reen!ineered in 1.2 versions to i"ple"ent List interfa+e.
2et:
1/ It is t#e +#ild interfa+e of 'olle+tion.
2/ If we want to represent a !ro(p of individ(al ob,e+ts as sin!le entity Kw#ere d(pli+ates
are not allow and insertion order is not preservedL t#en we s#o(ld !o for Cet interfa+e.
'iagram:

2orted2et:
1/ It is t#e +#ild interfa+e of Cet.
2/ If we want to represent a !ro(p of K(niV(e ob,e+tsL a++ordin! to so"e sortin! order
t#en we s#o(ld !o for CortedCet.
/aviga,le2et:
1/ It is t#e +#ild interfa+e of CortedCet.
2/ It provides several "et#ods for navi!ation p(rposes.
Zueue:
1/ It is t#e +#ild interfa+e of 'olle+tion.
2/ If we want to represent a !ro(p of individ(al ob,e+ts prior to pro+essin! t#en we s#o(ld
!o for V(e(e +on+ept.





345

'iagram:

/ote: All t#e above interfa+es B'olle+tion- List- Cet- CortedCet- :avi!ableCet- and _(e(e/ "eant
for representin! a !ro(p of individ(al ob,e+ts.
If we want to represent a !ro(p of ob,e+ts as ?ey4val(e pairs t#en we s#o(ld !o for %ap.
=ap:
1/ %ap is not +#ild interfa+e of 'olle+tion.
2/ If we want to represent a !ro(p of ob,e+ts as ?ey4val(e pairs t#en we s#o(ld !o for %ap
interfa+e.
3/ D(pli+ate ?eys are not allowed b(t val(es +an be d(pli+ated.
'iagram:

2orted=ap:
1/ It is t#e +#ild interfa+e of %ap.
2/ If we want to represent a !ro(p of ob,e+ts as ?ey val(e pairs Ka++ordin! to so"e sortin!
order of ?eysL t#en we s#o(ld !o for Corted%ap.
/aviga,le=ap:
1/ It is t#e +#ild interfa+e of Corted%ap and defines several "et#ods for navi!ation
p(rposes.



346

"#at is t#e differen$e ,et%een *olle$tion and *olle$tions&
K'olle+tion is an Kinterfa+eL w#i+# +an be (sed to represent a !ro(p of ob,e+ts as a
sin!le entity. @#ereas K'olle+tions is an (tility +lassL present in ,ava.(til pa+?a!e to
define several (tility "et#ods for 'olle+tion ob,e+ts.
*olle$tion<<<<<<<<<<<<<<<<<<<<interfa$e
*olle$tions<<<<<<<<<<<<<<<<<<$lass
In +olle+tion fra"ewor? t#e followin! are le!a+y +#ara+ters.
1/ <n("erationBI/
2/ Di+tionaryBA'/
3/ e+torB'/
4/ Cta+?B'/
5/ Sas#tableB'/
6/ \ropertiesB'/
'iagram:

'iagram:

*olle$tion interfa$e:
If we want to represent a !ro(p of individ(al ob,e+ts t#en we s#o(ld !o for 'olle+tion
interfa+e. T#is interfa+e defines t#e "ost +o""on !eneral "et#ods w#i+# +an be
appli+able for any 'olle+tion ob,e+t.
T#e followin! is t#e list of "et#ods present in 'olle+tion interfa+e.
1/ boolean addBIb,e+t o/9

347

2/ boolean addAllB'olle+tion +/9
3/ boolean re"oveBIb,e+t o/9
4/ boolean re"oveAllBIb,e+t o/9
5/ boolean retainAllB'olle+tion +/9
To re"ove all ob,e+ts eE+ept t#ose present in +.
6/ oid +learB/9
7/ boolean +ontainsBIb,e+t o/9
$/ boolean +ontainsAllB'olle+tion +/9
&/ boolean is<"ptyB/9
1)/ Int si0eB/9
11/ Ib,e+tD> toArrayB/9
12/ Iterator iteratorB/9
T#ere is no +on+rete +lass w#i+# i"ple"ents 'olle+tion interfa+e dire+tly.
List interfa$e:
It is t#e +#ild interfa+e of 'olle+tion.
If we want to represent a !ro(p of individ(al ob,e+ts w#ere d(pli+ates are allow and
insertion order is preserved. T#en we s#o(ld !o for List.
@e +an differentiate d(pli+ate ob,e+ts and we +an "aintain insertion order by "eans of
indeE #en+e KindeE play very i"portant role in ListL.
List interfa+e defines t#e followin! spe+ifi+ "et#ods.
1/ boolean addBint indeE-Ib,e+t o/9
2/ boolean addAllBint indeE-'olle+tio +/9
3/ Ib,e+t !etBint indeE/9
4/ Ib,e+t re"oveBint indeE/9
5/ Ib,e+t setBint indeE-Ib,e+t new/9JJto repla+e
6/ Int indeEIfBIb,e+t o/9
Ret(rns indeE of first o++(rren+e of KoL.
7/ Int lastIndeEIfBIb,e+t o/9
$/ ListIterator listIteratorB/9
7rra(List:
1/ T#e (nderlyin! data str(+t(re is resi0able array Bor/ !rowable array.
2/ D(pli+ate ob,e+ts are allowed.
3/ Insertion order preserved.
4/ Setero!eneo(s ob,e+ts are allowed.
5/ :(ll insertion is possible.
*onstru$tors:
1; 7rra(List aMne% 7rra(List:;E

34$

'reates an e"pty ArrayList ob,e+t wit# defa(lt initial +apa+ity K1)L if ArrayList rea+#es
its "aE +apa+ity t#en a new ArrayList ob,e+t will be +reated wit#
:ew +apa+ity8B+(rrent +apa+ityU3J2/F1
2; 7rra(List aMne% 7rra(List:int initial$apa$it(;E
'reates an e"pty ArrayList ob,e+t wit# t#e spe+ified initial +apa+ity.
3; 7rra(List aMne% 7rra(List:$olle$tion $;E
'reates an eV(ivalent ArrayList ob,e+t for t#e !iven 'olle+tion t#at is t#is +onstr(+tor
"eant for inter +onversation between +olle+tion ob,e+ts. T#at is to dan+e between
+olle+tion ob,e+ts.
'emo program for 7rra(List:
i"port ,ava.(til.U9
+lass ArrayListDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
ArrayList a8new ArrayListB/9
a.addBNAN/9
a.addB1)/9
a.addBNAN/9
a.addBn(ll/9
Cyste".o(t.printlnBa/9JJDA- 1)- A- n(ll>
a.re"oveB2/9
Cyste".o(t.printlnBa/9JJDA- 1)- n(ll>
a.addB2-N"N/9
a.addBNnN/9
Cyste".o(t.printlnBa/9JJDA- 1)- "- n(ll- n>
=
=
;s(ally we +an (se +olle+tion to #old and transfer ob,e+ts to provide s(pport for t#is
reV(ire"ent every +olle+tion +lass i"ple"ents Ceriali0able and 'loneable interfa+es.
ArrayList and e+tor +lasses i"ple"ents Rando"A++ess interfa+e so t#at any rando"
ele"ent we +an a++ess wit# t#e sa"e speed.
Rando"A++ess interfa+e present in (til pa+?a!e and doesnAt +ontain any "et#ods. It is a
"ar?er interfa+e.
'ifferen$es ,et%een 7rra(List and -e$tor&
7rra(List -e$tor
1/ :o "et#od is syn+#roni0ed 1/ <very "et#od is syn+#roni0ed
2/ At a ti"e "(ltiple T#reads are allow to 2/ At a ti"e only one T#read is allow to

34&

operate on ArrayList ob,e+t and #en+e
ArrayList ob,e+t is not T#read safe.
operate on e+tor ob,e+t and #en+e
e+tor ob,e+t is T#read safe.
3/ Relatively perfor"an+e is #i!# be+a(se
T#reads are not reV(ired to wait.
3/ Relatively perfor"an+e is low be+a(se
T#reads are reV(ired to wait.
4/ It is non le!a+y and introd(+ed in 1.2v 4/ It is le!a+y and introd(+ed in 1.)v
Getting s(n$#roni4ed version of 7rra(List o,je$t:
'olle+tions +lass defines t#e followin! "et#od to ret(rn syn+#roni0ed version of List.
3u,li$ stati$ List s(n$#roni4edList:list l;E
Example:


Ci"ilarly we +an !et syn+#roni0ed version of Cet and %ap ob,e+ts by (sin! t#e followin!
"et#ods.
1; pu,li$ stati$ 2et s(n$#roni4ed2et:2et s;E
2; pu,li$ stati$ =ap s(n$#roni4ed=ap:=ap m;E
ArrayList is t#e best +#oi+e if o(r freV(ent operation is retrieval.
ArrayList is t#e worst +#oi+e if o(r freV(ent operation is insertion Bor/ deletion in t#e
"iddle be+a(se it reV(ires several internal s#ift operations.
'iagram:

Lin+edList.
1/ T#e (nderlyin! data str(+t(re is do(ble Lin?edList
2/ If o(r freV(ent operation is insertion Bor/ deletion in t#e "iddle t#en Lin?edList is t#e
best +#oi+e.
3/ If o(r freV(ent operation is retrieval operation t#en Lin?edList is worst +#oi+e.
4/ D(pli+ate ob,e+ts are allowed.
5/ Insertion order is preserved.
6/ Setero!eneo(s ob,e+ts are allowed.
7/ :(ll insertion is possible.

35)

$/ I"ple"ents Ceriali0able and 'loneable interfa+es b(t not Rando"A++ess.
'iagram:

;s(ally we +an (se Lin?edList to i"ple"ent Cta+?s and _(e(es to provide s(pport for
t#is reV(ire"ent Lin?edList +lass defines t#e followin! 6 spe+ifi+ "et#ods.
1/ void addHirstBIb,e+t o/9
2/ void addLastBIb,e+t o/9
3/ Ib,e+t !etHirstB/9
4/ Ib,e+t !etLastB/9
5/ Ib,e+t re"oveHirstB/9
6/ Ib,e+t re"oveLastB/9
@e +an apply t#ese "et#ods only on Lin?edList ob,e+t.
*onstru$tors:
1/ Lin?edList l8new Lin?edListB/9
'reates an e"pty Lin?edList ob,e+t.
2/ Lin?edList l8new Lin?edListB'olle+tion +/9
To +reate an eV(ivalent Lin?edList ob,e+t for t#e !iven +olle+tion.
Example:
i"port ,ava.(til.U9
+lass Lin?edListDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Lin?edList l8new Lin?edListB/9
l.addBNb#as?arN/9
l.addB3)/9
l.addBn(ll/9
l.addBNb#as?arN/9
Cyste".o(t.printlnBl/9JJDb#as?ar- 3)- n(ll- b#as?ar>
l.setB)-NsoftwareN/9
Cyste".o(t.printlnBl/9JJDsoftware- 3)- n(ll- b#as?ar>
l.setB)-Nven?yN/9
Cyste".o(t.printlnBl/9JJDven?y- 3)- n(ll- b#as?ar>
l.re"oveLastB/9

351

Cyste".o(t.printlnBl/9JJDven?y- 3)- n(ll>
l.addHirstBNvvvN/9
Cyste".o(t.printlnBl/9JJDvvv- ven?y- 3)- n(ll>
=
=
-e$tor:
1/ T#e (nderlyin! data str(+t(re is resi0able array Bor/ !rowable array.
2/ D(pli+ate ob,e+ts are allowed.
3/ Insertion order is preserved.
4/ Setero!eneo(s ob,e+ts are allowed.
5/ :(ll insertion is possible.
6/ I"ple"ents Ceriali0able- 'loneable and Rando"A++ess interfa+es.
<very "et#od present in e+tor is syn+#roni0ed and #en+e e+tor is T#read safe.
-e$tor spe$ifi$ met#ods:
8o add o,je$ts:
1/ addBIb,e+t o/944444'olle+tion
2/ addBint indeE-Ib,e+t o/944444List
3/ add<le"entBIb,e+t o/944444e+tor
8o remove elements:
1/ re"oveBIb,e+t o/944444444'olle+tion
2/ re"oveBint indeE/944444444444444List
3/ re"ove<le"entBIb,e+t o/94444e+tor
4/ re"ove<le"entAtBint indeE/944444e+tor
5/ re"oveAll<le"entsB/944444e+tor
6/ +learB/94444444'olle+tion
8o get o,je$ts:
1/ Ib,e+t !etBint indeE/9444444444444444List
2/ Ib,e+t ele"entAtBint indeE/944444e+tor
3/ Ib,e+t first<le"entB/944444444444444e+tor
4/ Ib,e+t last<le"entB/9444444444444444e+tor
!t#er met#ods:
1/ Int si0eB/9JJSow "any ob,e+ts are added
2/ Int +apa+ityB/9JJTotal +apa+ity
3/ <n("eration ele"entsB/9
*onstru$tors:
1; -e$tor vMne% -e$tor:;E
'reates an e"pty e+tor ob,e+t wit# defa(lt initial +apa+ity 1).

352

In+e e+tor rea+#es its "aEi"(" +apa+ity t#en a new e+tor ob,e+t will be +reated
wit# do(ble +apa+ity. T#at is Knew+apa+ity8+(rrent+apa+ityU2L.
2; -e$tor vMne% -e$tor:int initial$apa$it(;E
3; -e$tor vMne% -e$tor:int initial$apa$it(H int in$remental$apa$it(;E
4; -e$tor vMne% -e$tor:*olle$tion $;E
Example:
i"port ,ava.(til.U9
+lass e+torDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
e+tor v8new e+torB/9
Cyste".o(t.printlnBv.+apa+ityB//9JJ1)
forBint i819iZ81)9iFF/
7
v.add<le"entBi/9
=
Cyste".o(t.printlnBv.+apa+ityB//9JJ1)
v.add<le"entBNAN/9
Cyste".o(t.printlnBv.+apa+ityB//9JJ2)
Cyste".o(t.printlnBv/9JJD1- 2- 3- 4- 5- 6- 7- $- &- 1)- A>
=
=
2ta$+:
1/ It is t#e +#ild +lass of e+tor.
2/ @#enever last in first o(t order reV(ired t#en we s#o(ld !o for Cta+?.
*onstru$tor:
It +ontains only one +onstr(+tor.
2ta$+ sM ne% 2ta$+:;E
=et#ods:
1/ Ib,e+t p(s#BIb,e+t o/9
To insert an ob,e+t into t#e sta+?.
2/ Ib,e+t popB/9
To re"ove and ret(rn top of t#e sta+?.
3/ Ib,e+t pee?B/9
To ret(rn top of t#e sta+? wit#o(t re"oval.
4/ boolean e"ptyB/9
Ret(rns tr(e if Cta+? is e"pty.

353

5/ Int sear+#BIb,e+t o/9
Ret(rns offset if t#e ele"ent is available ot#erwise ret(rns K41L
Example:
i"port ,ava.(til.U9
+lass Cta+?De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cta+? s8new Cta+?B/9
s.p(s#BNAN/9
s.p(s#BN6N/9
s.p(s#BN'N/9
Cyste".o(t.printlnBs/9JJDA- 6- '>
Cyste".o(t.printlnBs.popB//9JJ'
Cyste".o(t.printlnBs/9JJDA- 6>
Cyste".o(t.printlnBs.pee?B//9JJ6
Cyste".o(t.printlnBs.sear+#BNAN//9JJ2
Cyste".o(t.printlnBs.sear+#BN1N//9JJ41
Cyste".o(t.printlnBs.e"ptyB//9JJfalse
=
=
8#e 3 $ursors of java:
If we want to !et ob,e+ts one by one fro" t#e +olle+tion t#en we s#o(ld !o for +(rsor.
T#ere are 3 types of +(rsors available in ,ava. T#ey are.
1/ <n("eration
2/ Iterator
3/ ListIterator
Enumeration:
1/ @e +an (se <n("eration to !et ob,e+ts one by one fro" t#e le!a+y +olle+tion ob,e+ts.
2/ @e +an +reate <n("eration ob,e+t by (sin! ele"entsB/ "et#od.
Enumeration eMv9elements:;E
e+tor Ib,e+t
<n("eration interfa+e defines t#e followin! two "et#ods
1; pu,li$ ,oolean #as=oreElements:;E
2; pu,li$ !,je$t nextElement:;E
Example:
i"port ,ava.(til.U9
+lass <n("erationDe"o
7

354

p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
e+tor v8new e+torB/9
forBint i8)9iZ81)9iFF/
7
v.add<le"entBi/9
=
Cyste".o(t.printlnBv/9JJD)- 1- 2- 3- 4- 5- 6- 7- $- &- 1)>
<n("eration e8v.ele"entsB/9
w#ileBe.#as%ore<le"entsB//
7
Inte!er i8BInte!er/e.neEt<le"entB/9
ifBi`288)/
Cyste".o(t.printlnBi/9JJ) 2 4 6 $ 1)
=
Cyste".o(t.printBv/9JJD)- 1- 2- 3- 4- 5- 6- 7- $- &- 1)>
=
=
Limitations of Enumeration:
1/ @e +an apply <n("eration +on+ept only for le!a+y +lasses and it is not a (niversal
+(rsor.
2/ 6y (sin! <n("eration we +an !et only read a++ess and we +anAt perfor" re"ove
operations.
3/ To over+o"e t#ese li"itations s(n people introd(+ed Iterator +on+ept in 1.2v.
Iterator:
1/ @e +an (se Iterator to !et ob,e+ts one by one fro" any +olle+tion ob,e+t.
2/ @e +an apply Iterator +on+ept for any +olle+tion ob,e+t and it is a (niversal +(rsor.
3/ @#ile iteratin! t#e ob,e+ts by Iterator we +an perfor" bot# read and re"ove
operations.
@e +an !et Iterator ob,e+t by (sin! iteratorB/ "et#od of 'olle+tion interfa+e.
Iterator itrM$9iterator:;E
Iterator interfa+e defines t#e followin! 3 "et#ods.
1; pu,li$ ,oolean #as/ext:;E
2; pu,li$ o,je$t next:;E
3; pu,li$ void remove:;E
Example:
i"port ,ava.(til.U9
+lass IteratorDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
ArrayList a8new ArrayListB/9
forBint i8)9iZ81)9iFF/
7

355

a.addBi/9
=
Cyste".o(t.printlnBa/9JJD)- 1- 2- 3- 4- 5- 6- 7- $- &- 1)>
Iterator itr8a.iteratorB/9
w#ileBitr.#as:eEtB//
7
Inte!er i8BInte!er/itr.neEtB/9
ifBi`288)/
Cyste".o(t.printlnBi/9JJ)- 2- 4- 6- $- 1)
else
itr.re"oveB/9
=
Cyste".o(t.printlnBa/9JJD)- 2- 4- 6- $- 1)>
=
=
Limitations of Iterator:
1/ 6ot# en("eration and Iterator are sin!le dire+tion +(rsors only. T#at is we +an always
"ove only forward dire+tion and we +anAt "ove to t#e ba+?ward dire+tion.
2/ @#ile iteratin! by Iterator we +an perfor" only read and re"ove operations and we
+anAt perfor" repla+e"ent and addition of new ob,e+ts.
3/ To over+o"e t#ese li"itations s(n people introd(+ed listIterator +on+ept.
ListIterator:
1/ ListIterator is t#e +#ild interfa+e of Iterator.
2/ 6y (sin! listIterator we +an "ove eit#er to t#e forward dire+tion Bor/ to t#e ba+?ward
dire+tion t#at is it is a bi4dire+tional +(rsor.
3/ @#ile iteratin! by listIterator we +an perfor" repla+e"ent and addition of new ob,e+ts
in addition to read and re"ove operations
6y (sin! listIterator "et#od we +an +reate listIterator ob,e+t.
ListIterator itrMl9listiterator:;E
ListIterator interfa+e defines t#e followin! & "et#ods.
1/ p(bli+ boolean #as:eEtB/9
2/ p(bli+ Ib,e+t neEtB/9 forward
3/ p(bli+ int neEtIndeEB/9
4/ p(bli+ boolean #as\revio(sB/9
5/ p(bli+ Ib,e+t previo(sB/9 ba+?ward
6/ p(bli+ int previo(sIndeEB/9
7/ p(bli+ void re"oveB/9
$/ p(bli+ void setBIb,e+t o/9
&/ p(bli+ void addBIb,e+t new/9
Example:
i"port ,ava.(til.U9
+lass ListIteratorDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/

356

7
Lin?edList l8new Lin?edListB/9
l.addBNbala?ris#naN/9
l.addBNven?iN/9
l.addBN+#ir(N/9
l.addBNna!N/9
Cyste".o(t.printlnBl/9JJDbala?ris#na- ven?i- +#ir(- na!>
ListIterator itr8l.listIteratorB/9
w#ileBitr.#as:eEtB//
7
Ctrin! s8BCtrin!/itr.neEtB/9
ifBs.eV(alsBNven?iN//
7
itr.re"oveB/9
=
=
Cyste".o(t.printlnBl/9JJDbala?ris#na- +#ir(- na!>
=
=
*ase 1:
ifBs.eV(alsBN+#ir(N//
7
itr.setBN+#ranN/9
=
!utput:
Dbala?ris#na- ven?i- +#ir(- na!>
Dbala?ris#na- ven?i- +#ran- na!>
*ase 2:
ifBs.eV(alsBNna!N//
7
itr.addBN+#it(N/9
=
!utput:
Dbala?ris#na- ven?i- +#ir(- na!>
Dbala?ris#na- ven?i- +#ir(- na!- +#it(>
T#e "ost powerf(l +(rsor is listIterator b(t its li"itation is it is appli+able only for KList
ob,e+tsL.
*ompression of Enumeration Iterator and ListIterator&
3ropert( Enumeration Iterator ListIterator
1/ Is it le!a+yW yes no no
2/ It is appli+able
forW
Inly le!a+y
+lasses.
Appli+able for any
+olle+tion ob,e+t.
Appli+able for only list
ob,e+ts.
3/ %o"entW Cin!le dire+tion
+(rsorBforward/
Cin!le dire+tion
+(rsorBforward
6i4dire+tional.

357

4/ Sow to !et itW 6y (sin!
ele"entsB/
"et#od.
6y (sin!
iteratorB/"et#od.
6y (sin! listIteratorB/
"et#od.
5/ A++essibilityW Inly read. 6ot# read and
re"ove.
ReadJre"oveJrepla+eJadd.
6/ "et#ods #as%ore<le"entB/
neEt<le"entB/
#as:eEtB/
neEtB/
re"oveB/
& "et#ods.
2et interfa$e:
1/ It is t#e +#ild interfa+e of 'olle+tion.
2/ If we want to represent a !ro(p of individ(al ob,e+ts w#ere d(pli+ates are not allow and
insertion order is not preserved t#en we s#o(ld !o for Cet interfa+e.
'iagram:

Cet interfa+e does not +ontain any new "et#od we #ave to (se only 'olle+tion interfa+e
"et#ods.
6as#2et:
1/ T#e (nderlyin! data str(+t(re is Sas#table.
2/ Insertion order is not preserved and it is based on #as# +ode of t#e ob,e+ts.
3/ D(pli+ate ob,e+ts are not allowed.
4/ If we are tryin! to insert d(pli+ate ob,e+ts we wonAt !et +o"pile ti"e error and r(nti"e
error addB/ "et#od si"ply ret(rns false.
5/ Setero!eneo(s ob,e+ts are allowed.
6/ :(ll insertion is possible.
7/ I"ple"ents Ceriali0able and 'loneable interfa+es b(t not Rando"A++ess.
*onstru$tors:
1; 6as#2et #Mne% 6as#2et:;E
'reates an e"pty Sas#Cet ob,e+t wit# defa(lt initial +apa+ity 16 and defa(lt fill ratio
).75Bfill ratio is also ?nown as load fa+tor/.
2; 6as#2et #Mne% 6as#2et:int initial$apa$it(;E
'reates an e"pty Sas#Cet ob,e+t wit# t#e spe+ified initial +apa+ity and defa(lt fill ratio
).75.

35$

3; 6as#2et #Mne% 6as#2et:int initial$apa$it(Hfloat fillratio;E
4; 6as#2et #Mne% 6as#2et:*olle$tion $;E
Example:
i"port ,ava.(til.U9
+lass Sas#CetDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Sas#Cet #8new Sas#CetB/9
#.addBN6N/9
#.addBN'N/9
#.addBNDN/9
#.addBN1N/9
#.addBn(ll/9
#.addB1)/9
Cyste".o(t.printlnB#.addBN1N//9JJfalse
Cyste".o(t.printlnB#/9JJDn(ll- D- 6- '- 1)- 1>
=
=
Lin+ed6as#2et:
1/ It is t#e +#ild +lass of Sas#Cet.
2/ Lin?edSas#Cet is eEa+tly sa"e as Sas#Cet eE+ept t#e followin! differen+es.
6as#2et Lin+ed6as#2et
1/ T#e (nderlyin! data str(+t(re is
Sas#table.
1/ T#e (nderlyin! data str(+t(re is a
+o"bination of Lin?edList and
Sas#table.
2/ Insertion order is not preserved. 2/ Insertion order is preserved.
3/ Introd(+ed in 1.2 v. 3/ Introd(+ed in 1.4v.
In t#e above pro!ra" if we are repla+in! Sas#Cet wit# Lin?edSas#Cet t#e o(tp(t is D6-
'- D- 1- n(ll- 1)>.T#at is insertion order is preserved.
Example:
i"port ,ava.(til.U9
+lass Lin?edSas#CetDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Lin?edSas#Cet #8new Lin?edSas#CetB/9
#.addBN6N/9
#.addBN'N/9

35&

#.addBNDN/9
#.addBN1N/9
#.addBn(ll/9
#.addB1)/9
Cyste".o(t.printlnB#.addBN1N//9JJfalse
Cyste".o(t.printlnB#/9JJD6- '- D- 1- n(ll- 1)>
=
=
/ote: Lin?edSas#Cet and Lin?edSas#%ap +o""only (sed for i"ple"entin! K+a+#e
appli+ationsL w#ere insertion order "(st be preserved and d(pli+ates are not allowed.
2orted2et:
1/ It is +#ild interfa+e of Cet.
2/ If we want to represent a !ro(p of K(niV(e ob,e+tsL a++ordin! to so"e sortin! order
t#en we s#o(ld !o for CortedCet interfa+e.
3/ T#at sortin! order +an be eit#er defa(lt nat(ral sortin! Bor/ +(sto"i0ed sortin! order.
CortedCet interfa+e define t#e followin! 6 spe+ifi+ "et#ods.
1/ Ib,e+t firstB/9
2/ Ib,e+t lastB/9
3/ CortedCet #eadCetBIb,e+t o/9
Ret(rns t#e CortedCet w#ose ele"ents are Z8o.
4/ CortedCet tailCetBIb,e+t o/9

It ret(rns t#e CortedCet w#ose ele"ents are T8o.
5/ CortedCet s(bsetBIb,e+t o1-Ib,e+t o2/9
Ret(rns t#e CortedCet w#ose ele"ents are T8o1b(t Zo2.
6/ 'o"parator +o"paratorB/9
Ret(rns t#e 'o"parator ob,e+t t#at des+ribes (nderlyin! sortin! te+#niV(e.
If we are followin! defa(lt nat(ral sortin! order t#en t#is "et#od ret(rns n(ll.
'iagram:



36)


8ree2et:
1/ T#e (nderlyin! data str(+t(re is balan+ed tree.
2/ D(pli+ate ob,e+ts are not allowed.
3/ Insertion order is not preserved and it is based on so"e sortin! order of ob,e+ts.
4/ Setero!eneo(s ob,e+ts are not allowed if we are tryin! to insert #etero!eneo(s ob,e+ts
t#en we will !et 'lass'ast<E+eption.
5/ :(ll insertion is possibleBonly on+e/.
*onstru$tors:
1; 8ree2et tMne% 8ree2et:;E
'reates an e"pty TreeCet ob,e+t w#ere all ele"ents will be inserted a++ordin! to
defa(lt nat(ral sortin! order.
2; 8ree2et tMne% 8ree2et:*omparator $;E
'reates an e"pty TreeCet ob,e+t w#ere all ob,e+ts will be inserted a++ordin! to
+(sto"i0ed sortin! order spe+ified by 'o"parator ob,e+t.
3; 8ree2et tMne% 8ree2et:2orted2et s;E
4; 8ree2et tMne% 8ree2et:*olle$tion $;E
Example 1:
i"port ,ava.(til.U9
+lass TreeCetDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
TreeCet t8new TreeCetB/9
t.addBNAN/9
t.addBNaN/9
t.addBN6N/9
t.addBN1N/9
t.addBNLN/9
JJt.addBnew Inte!erB1)//9JJ'lass'ast<E+eption
JJt.addBn(ll/9JJ:(ll\ointer<E+eption
Cyste".o(t.printlnBt/9JJDA- 6- L- 1- a>
=
=
/ull a$$eptan$e:
Hor t#e e"pty TreeCet as t#e 1
st
ele"ent Kn(llL insertion is possible b(t after insertin!
t#at n(ll if we are tryin! to insert any ot#er we will !et :(ll\ointer<E+eption.

361

Hor t#e non e"pty TreeCet if we are tryin! to insert n(ll t#en we will !et
:(ll\ointer<E+eption.
Example 2:
i"port ,ava.(til.U9
+lass TreeCetDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
TreeCet t8new TreeCetB/9
t.addBnew Ctrin!6(fferBNAN//9
t.addBnew Ctrin!6(fferBN1N//9
t.addBnew Ctrin!6(fferBNLN//9
t.addBnew Ctrin!6(fferBN6N//9
Cyste".o(t.printlnBt/9
=
=
!utput:
R(nti"e <E+eption.
<E+eption in t#read N"ainN ,ava.lan!.'lass'ast<E+eption. ,ava.lan!.Ctrin!6(ffer +annot
be +ast to ,ava.lan!.'o"parable
If we are dependin! on defa(lt nat(ral sortin! order +o"p(lsory t#e ob,e+ts s#o(ld be
#o"o!eneo(s and 'o"parable ot#erwise we will !et 'lass'ast<E+eption.
An ob,e+t is said to be 'o"parable if and only if t#e +orrespondin! +lass i"ple"ents
'o"parable interfa+e.
Ctrin! +lass and all wrapper +lasses i"ple"ents 'o"parable interfa+e b(t Ctrin!6(ffer
+lass doesnAt i"ple"ent 'o"parable interfa+e #en+e in t#e above pro!ra" we are
!ettin! 'lass'ast<E+eption.
*ompara,le interfa$e:
'o"parable interfa+e present in ,ava.lan! pa+?a!e and +ontains only one "et#od
+o"pareToB/ "et#od.
pu,li$ int $ompare8o:!,je$t o,j;E
Example:
o,j19$ompare8o:o,j2;E
'iagram:


362



Example 3:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBNAN.+o"pareToBN1N//9JJ425
Cyste".o(t.printlnBN1N.+o"pareToBNGN//9JJ15
Cyste".o(t.printlnBNAN.+o"pareToBNAN//9JJ)
JJCyste".o(t.printlnBNAN.+o"pareToBnew Inte!erB1)///9JJTest.,ava.$.
+o"pareToB,ava.lan!.Ctrin!/ in ,ava.lan!.Ctrin! +annot be applied to B,ava.lan!.Inte!er/
JJCyste".o(t.printlnBNAN.+o"pareToBn(ll//9JJ:(ll\ointer<E+eption
=
=
If we are dependin! on defa(lt nat(ral sortin! order t#en internally *% will (se
+o"pareToB/ "et#od to arran!e ob,e+ts in sortin! order.
Example 4:
i"port ,ava.(til.U9
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
TreeCet t8new TreeCetB/9
t.addB1)/9
t.addB)/9
t.addB15/9
t.addB1)/9
Cyste".o(t.printlnBt/9JJD)- 1)- 15>
=
=








363

$ompare8o:; met#od anal(sis:

If we are not satisfyin! wit# defa(lt nat(ral sortin! order Bor/ if defa(lt nat(ral sortin!
order is not available t#en we +an define o(r own +(sto"i0ed sortin! by 'o"parator
ob,e+t.
'o"parable "eant for defa(lt nat(ral sortin! order.
'o"parator "eant for +(sto"i0ed sortin! order.
*omparator interfa$e:
'o"parator interfa+e present in ,ava.(til pa+?a!e t#is interfa+e defines t#e followin! 2
"et#ods.
1; pu,li$ int $ompare:!,je$t o,j1H!,je$t !,j2;E
'iagram:


2; pu,li$ ,oolean eAuals:!,je$to,j;E

@#enever we are i"ple"entin! 'o"parator interfa+e we #ave to provide
i"ple"entation only for $ompare:; "et#od.
I"ple"entin! eV(alsB/ "et#od is optional be+a(se it is already available fro" Ib,e+t
+lass t#ro(!# in#eritan+e.
ReAuirement: @rite a pro!ra" to insert inte!er ob,e+ts into t#e TreeCet w#ere t#e sortin!
order is des+endin! order.
3rogram:
i"port ,ava.(til.U9
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
TreeCet t8new TreeCetBnew %y'o"paratorB//9444444444444B1/

364

t.addB1)/9
t.addB)/9
t.addB15/9
t.addB5/9
t.addB2)/9
Cyste".o(t.printlnBt/9JJD2)- 15- 1)- 5- )>
=
=
+lass %y'o"parator i"ple"ents 'o"parator
7
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/
7
Inte!er i18BInte!er/ob,19
Inte!er i28BInte!er/ob,29
ifBi1Zi2/
ret(rn F19
else ifBi1Ti2/
ret(rn 41))9
else ret(rn )9
=
=
At line K1L if we are not passin! 'o"parator ob,e+t t#en *% will always +alls
+o"pareToB/ "et#od w#i+# is "eant for defa(lt nat(ral sortin! orderBas+endin!
order/#en+e in t#is +ase t#e o(tp(t is D)- 5- 1)- 15- 2)>.
At line K1L if we are passin! 'o"parator ob,e+t t#en *% +alls +o"pareB/ "et#od of
%y'o"parator +lass w#i+# is "eant for +(sto"i0ed sortin! orderBdes+endin! order/
#en+e in t#is +ase t#e o(tp(t is D2)- 15- 1)- 5- )>.
'iagram:

-arious alternative implementations of $ompare:; met#od:
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/

365

7
Inte!er i18BInte!er/ob,19
Inte!er i28BInte!er/ob,29
JJret(rn i1.+o"pareToBi2/9JJD)- 5- 1)- 15- 2)>
JJret(rn 4i1.+o"pareToBi2/9JJD2)- 15- 1)- 5- )>
JJret(rn i2.+o"pareToBi1/9JJD2)- 15- 1)- 5- )>
JJret(rn 4i2.+o"pareToBi1/9JJD)- 5- 1)- 15- 2)>
JJret(rn 419JJD2)- 5- 15- )- 1)>JJreverse of insertion order
JJret(rn F19JJD1)- )- 15- 5- 2)>JJinsertion order
JJret(rn )9JJD1)>and all t#e re"ainin! ele"ents treated as d(pli+ate.
=
ReAuirement: @rite a pro!ra" to insert Ctrin! ob,e+ts into t#e TreeCet w#ere t#e sortin! order
is reverse of alp#abeti+al order.
3rogram:
i"port ,ava.(til.U9
+lass TreeCetDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
TreeCet t8new TreeCetBnew %y'o"paratorB//9
t.addBNRo,aN/9
t.addBNC#obaRaniN/9
t.addBNRa,aG("ariN/9
t.addBN^an!a6#avaniN/9
t.addBNRa"(la""aN/9
Cyste".o(t.printlnBt/9JJDC#obaRani- Ro,a- Ra"(la""a- Ra,aG("ari-
^an!a6#avani>
=
=
+lass %y'o"parator i"ple"ents 'o"parator
7
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/
7
Ctrin! s18ob,1.toCtrin!B/9
Ctrin! s28BCtrin!/ob,29
JJret(rn s2.+o"pareToBs1/9
ret(rn 4s1.+o"pareToBs2/9
=

366

=
ReAuirement: @rite a pro!ra" to insert Ctrin!6(ffer ob,e+ts into t#e TreeCet w#ere t#e sortin!
order is alp#abeti+al order.
3rogram:
i"port ,ava.(til.U9
+lass TreeCetDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
TreeCet t8new TreeCetBnew %y'o"paratorB//9
t.addBnew Ctrin!6(fferBNAN//9
t.addBnew Ctrin!6(fferBN1N//9
t.addBnew Ctrin!6(fferBNGN//9
t.addBnew Ctrin!6(fferBNLN//9
Cyste".o(t.printlnBt/9JJ DA- G- L- 1>
=
=
+lass %y'o"parator i"ple"ents 'o"parator
7
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/
7
Ctrin! s18ob,1.toCtrin!B/9
Ctrin! s28ob,2.toCtrin!B/9
ret(rn s1.+o"pareToBs2/9
=
=
/ote: @#enever we are definin! o(r own +(sto"i0ed sortin! by 'o"parator t#en t#e ob,e+ts
need not be 'o"parable.
Example: Ctrin!6(ffer
ReAuirement: @rite a pro!ra" to insert Ctrin! and Ctrin!6(ffer ob,e+ts into t#e TreeCet w#ere
t#e sortin! order is in+reasin! len!t# order. If 2 ob,e+ts #avin! t#e sa"e len!t# t#en +onsider
t#ey alp#abeti+al order.
3rogram:
i"port ,ava.(til.U9
+lass TreeCetDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7

367

TreeCet t8new TreeCetBnew %y'o"paratorB//9
t.addBNAN/9
t.addBnew Ctrin!6(fferBNA6'N//9
t.addBnew Ctrin!6(fferBNAAN//9
t.addBNEEN/9
t.addBNA6'DN/9
t.addBNAN/9
Cyste".o(t.printlnBt/9JJDA- AA- EE- A6'- A6'D>
=
=
+lass %y'o"parator i"ple"ents 'o"parator
7
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/
7
Ctrin! s18ob,1.toCtrin!B/9
Ctrin! s28ob,2.toCtrin!B/9
int l18s1.len!t#B/9
int l28s2.len!t#B/9
ifBl1Zl2/
ret(rn 419
else ifBl1Tl2/
ret(rn 19
else
ret(rn s1.+o"pareToBs2/9
=
=
/ote: If we are dependin! on defa(lt nat(ral sortin! order t#en t#e ob,e+ts s#o(ld be
K#o"o!eneo(s and +o"parableL ot#erwise we will !et 'lass'ast<E+eption. If we are definin!
o(r own sortin! by 'o"parator t#en ob,e+ts Kneed not be #o"o!eneo(s and +o"parableL.
*ompara,le vs *omparator:
Hor predefined 'o"parable +lasses defa(lt nat(ral sortin! order is already available if
we are not satisfied wit# defa(lt nat(ral sortin! order t#en we +an define o(r own
+(sto"i0ed sortin! order by 'o"parator.
Hor predefined non 'o"parable +lasses Dli?e Ctrin!6(ffer> defa(lt nat(ral sortin! order
is not available we +an define o(r own sortin! order by (sin! 'o"parator ob,e+t.
Hor o(r own +lasses Dli?e '(sto"er- Ct(dent- and <"ployee> we +an define defa(lt
nat(ral sortin! order by (sin! 'o"parable interfa+e. T#e person w#o is (sin! o(r +lass-

36$

if #e is not satisfied wit# defa(lt nat(ral sortin! order t#en #e +an define #is own sortin!
order by (sin! 'o"parator ob,e+t.
Example:
i"port ,ava.(til.U9
+lass <"ployee i"ple"ents 'o"parable
7
Ctrin! na"e9
int eid9
<"ployeeBCtrin! na"e-int eid/
7
t#is.na"e8na"e9
t#is.eid8eid9
=
p(bli+ Ctrin! toCtrin!B/
7
ret(rn na"eFN4444NFeid9
=
p(bli+ int +o"pareToBIb,e+t o/
7
int eid18t#is.eid9
int eid28BB<"ployee/o/.eid9
ifBeid1Zeid2/
7
ret(rn 419
=
else ifBeidTeid2/
7
ret(rn 19
=
else ret(rn )9
=
=
+lass 'o"p'o"p
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
<"ployee e18new <"ployeeBNna!N-1))/9
<"ployee e28new <"ployeeBNbalaia#N-2))/9

36&

<"ployee e38new <"ployeeBN+#ir(N-5)/9
<"ployee e48new <"ployeeBNven?iN-15)/9
<"ployee e58new <"ployeeBNna!N-1))/9
TreeCet t18new TreeCetB/9
t1.addBe1/9
t1.addBe2/9
t1.addBe3/9
t1.addBe4/9
t1.addBe5/9
Cyste".o(t.printlnBt1/9JJD+#ir(44445)- na!44441))- ven?i444415)- balaia#44442))>
TreeCet t28new TreeCetBnew %y'o"paratorB//9
t2.addBe1/9
t2.addBe2/9
t2.addBe3/9
t2.addBe4/9
t2.addBe5/9
Cyste".o(t.printlnBt2/9JJDbalaia#44442))- +#ir(44445)- na!44441))- ven?i444415)>
=
=
+lass %y'o"parator i"ple"ents 'o"parator
7
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/
7
<"ployee e18B<"ployee/ob,19
<"ployee e28B<"ployee/ob,29
Ctrin! s18e1.na"e9
Ctrin! s28e2.na"e9
ret(rn s1.+o"pareToBs2/9
=
=
*ompression of *ompara,le and *omparator&
*ompara,le *omparator
1/ 'o"parable "eant for defa(lt nat(ral
sortin! order.
1/ 'o"parator "eant for +(sto"i0ed
sortin! order.
2/ \resent in ,ava.lan! pa+?a!e. 2/ \resent in ,ava.(til pa+?a!e.
3/ 'ontains only one "et#od.
+o"pareToB/ "et#od.
3/ 'ontains 2 "et#ods.
'o"pareB/ "et#od.
<V(alsB/ "et#od.
4/ Ctrin! +lass and all wrapper 4/ :o predefined +lass i"ple"ents

37)

'lasses i"ple"ents 'o"parable
interfa+e.
'o"parator.
*ompression of 2et implemented $lass o,je$ts:
3ropert( 6as#2et Lin+ed6as#2et 8ree2et
1/ ;nderlyin!
Data str(+t(re.
Sas#table. Lin?edList
FSas#table.
6alan+ed Tree.
2/ Insertion order. :ot preserved. \reserved. :ot preserved Bby
defa(lt/.
3/ D(pli+ate ob,e+ts. :ot allowed. :ot allowed. :ot allowed.
4/ Cortin! order. :ot appli+able. :ot appli+able. Appli+able.
5/ Setero!eneo(s
ob,e+ts.
Allowed. Allowed. :ot allowed.
6/ :(ll insertion. Allowed. Allowed. Hor t#e e"pty
TreeCet as t#e 1
st

ele"ent n(ll
insertion is possible
in all ot#er +ases we
will !et :\<.
=ap:
1/ If we want to represent a !ro(p of ob,e+ts as K?ey4val(eL pair t#en we s#o(ld !o for
%ap interfa+e.
2/ 6ot# ?ey and val(e are ob,e+ts only.
3/ D(pli+ate ?eys are not allowed b(t val(es +an be d(pli+ated.
4/ <a+# ?ey4val(e pair is +alled Kone entryL.
'iagram:


'iagram:

371


%ap interfa+e is not +#ild interfa+e of 'olle+tion and #en+e we +anAt apply 'olle+tion
interfa+e "et#ods #ere.
%ap interfa+e defines t#e followin! spe+ifi+ "et#ods.
1/ Ib,e+t p(tBIb,e+t ?ey-Ib,e+t val(e/9
To add an entry to t#e %ap- if ?ey is already available t#en t#e old val(e repla+ed wit#
new val(e and old val(e will be ret(rned.
Example:
i"port ,ava.(til.U9
+lass %ap
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Sas#%ap "8new Sas#%apB/9
".p(tBN1))N-Nvi,ayN/9
Cyste".o(t.printlnB"/9JJ71))8vi,ay=
".p(tBN1))N-Nb#as?arN/9
Cyste".o(t.printlnB"/9JJ71))8b#as?ar=
=
=
2/ void p(tAllB%ap "/9
3/ Ib,e+t !etBIb,e+t ?ey/9
4/ Ib,e+t re"oveBIb,e+t ?ey/9
It re"oves t#e entry asso+iated wit# spe+ified ?ey and ret(rns t#e +orrespondin! val(e.
5/ boolean +ontainsGeyBIb,e+t ?ey/9
6/ boolean +ontainsal(eBIb,e+t val(e/9
7/ boolean is<"ptyB/9
$/ Int si0eB/9
&/ void +learB/9
1)/ Cet ?eyCetB/9
T#e set of ?eys we are !ettin!.

372

11/ 'olle+tion val(esB/9
T#e set of val(es we are !ettin!.
12/ Cet entryCetB/9
T#e set of entryset we are !ettin!.
Entr( interfa$e:
<a+# ?ey4val(e pair is +alled one entry wit#o(t eEistin! %ap ob,e+t t#ere is no +#an+e of
eEistin! entry ob,e+t #en+e interfa+e entry is define inside %ap interfa+eBinner
interfa+e/.
Example:
interfa+e %ap
7
.................9
.................9
.................9
interfa+e <ntry
7
Ib,e+t !etGeyB/9
Ib,e+t !etal(eB/9 on <ntry we +an apply t#ese 3 "et#ods.
Ib,e+t setal(eBIb,e+t new/9
=
=
6as#=ap.
1/ T#e (nderlyin! data str(+t(re is Sas#table.
2/ D(pli+ate ?eys are not allowed b(t val(es +an be d(pli+ated.
3/ Insertion order is not preserved and it is based on #as# +ode of t#e ?eys.
4/ Setero!eneo(s ob,e+ts are allowed for bot# ?ey and val(e.
5/ :(ll is allowed for ?eysBonly on+e/ and for val(esBany n("ber/.
'ifferen$es ,et%een 6as#=ap and 6as#ta,le&
6as#=ap 6as#ta,le
1/ :o "et#od is syn+#roni0ed. 1/ <very "et#od is syn+#roni0ed.
2/ %(ltiple T#reads +an operate
si"(ltaneo(sly on Sas#%ap ob,e+t and
#en+e it is not T#read safe.
2/ %(ltiple T#reads +anAt operate
si"(ltaneo(sly on Sas#table ob,e+t
and #en+e Sas#table ob,e+t is T#read
safe.
3/ Relatively perfor"an+e is #i!#. 3/ Relatively perfor"an+e is low.
4/ :(ll is allowed for bot# ?ey and val(e. 4/ :(ll is not allowed for bot# ?ey and
val(e ot#erwise we will !et
:(ll\ointer<E+eption.
5/ It is non le!a+y and introd(+ed in 1.2v. 5/ It is le!a+y and introd(+ed in 1.)v.

373


6o% to get s(n$#roni4ed version of 6as#=ap:
6y defa(lt Sas#%ap ob,e+t is not syn+#roni0ed. 6(t we +an !et syn+#roni0ed version by
(sin! t#e followin! "et#od of 'olle+tions +lass.
pu,li$ stati$ =ap s(n$#roni4ed=ap:=ap m1;
*onstru$tors:
1; 6as#=ap mMne% 6as#=ap:;E
'reates an e"pty Sas#%ap ob,e+t wit# defa(lt initial +apa+ity 16 and defa(lt fill ratio
K)75L.
2; 6as#=ap mMne% 6as#=ap:int initial$apa$it(;E
3; 6as#=ap m Mne% 6as#=ap:int initial$apa$it(H float fillratio;E
4; 6as#=ap mMne% 6as#=ap:=ap m;E


Example:
i"port ,ava.(til.U9
+lass Sas#%apDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Sas#%ap "8new Sas#%apB/9
".p(tBN+#iran,eeviN-7))/9
".p(tBNbalaia#N-$))/9
".p(tBNven?ates#N-2))/9
".p(tBNna!ar,(naN-5))/9
Cyste".o(t.printlnB"/9JJ7na!ar,(na85))- ven?ates#82))- balaia#8$))-
+#iran,eevi87))=
Cyste".o(t.printlnB".p(tBN+#iran,eeviN-1))//9JJ7))
Cet s8".?eyCetB/9
Cyste".o(t.printlnBs/9JJDna!ar,(na- ven?ates#- balaia#- +#iran,eevi>
'olle+tion +8".val(esB/9
Cyste".o(t.printlnB+/9JJD5))- 2))- $))- 1))>
Cet s18".entryCetB/9
Cyste".o(t.printlnBs1/9JJDna!ar,(na85))- ven?ates#82))- balaia#8$))-
+#iran,eevi81))>
Iterator itr8s1.iteratorB/9
w#ileBitr.#as:eEtB//
7

374

%ap.<ntry "18B%ap.<ntry/itr.neEtB/9

Cyste".o(t.printlnB"1.!etGeyB/FN......NF"1.!etal(eB//9JJna!ar,(na......5))
JJven?ates#......2))
JJbalaia#......$))
JJ+#iran,eevi......1))
ifB"1.!etGeyB/.eV(alsBNna!ar,(naN//
7
"1.setal(eB1)))/9
=
=
Cyste".o(t.printlnB"/9JJ7na!ar,(na81)))- ven?ates#82))- balaia#8$))-
+#iran,eevi81))=
=
=
Lin+ed6as#=ap:
6as#=ap Lin+ed6as#=ap
1/ T#e (nderlyin! data str(+t(re is
Sas#table.
1/ T#e (nderlyin! data str(+t(re is a
+o"bination of Sas#tableF Lin?edList.
2/ Insertion order is not preserved. 2/ Insertion order is preserved.
3; introd(+ed in 1.2.v. 3/ Introd(+ed in 1.4v.
/ote: in t#e above pro!ra" if we are repla+in! Sas#%ap wit# Lin?edSas#%ap t#en t#e o(tp(t
is 7+#iran,eevi81))- balaia#......$))- ven?ates#......2))- na!ar,(na......1)))= t#at is insertion
order is preserved.
/ote: in !eneral we +an (se Lin?edSas#Cet and Lin?edSas#%ap for i"ple"entin! +a+#e
appli+ations.
Identit(6as#=ap:
1/ It is eEa+tly sa"e as Sas#%ap eE+ept t#e followin! differen+es.
2/ In t#e +ase of Sas#%ap *% will always (se K.eV(alsB/L"et#od to identify d(pli+ate
?eys.
3/ 6(t in t#e +ase of IdentitySas#%ap *% will (se88 Bdo(ble eV(al operator/ to identify
d(pli+ate ?eys.
Example:
i"port ,ava.(til.U9
+lass Sas#%apDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Sas#%ap "8new Sas#%apB/9

375

Inte!er i18new Inte!erB1)/9
Inte!er i28new Inte!erB1)/9
".p(tBi1-NpavanN/9
".p(tBi2-N?alyanN/9
Cyste".o(t.printlnB"/9
=
=
In t#e above pro!ra" i1 and i2 are d(pli+ate ?eys be+a(se i1.eV(alsBi2/ ret(rns tr(e.
In t#e above pro!ra" if we repla+e Sas#%ap wit# IdentitySas#%ap t#en i1 and i2 are
not d(pli+ate ?eys be+a(se i188i2 is false #en+e in t#is +ase t#e o(tp(t is 71)8pavan-
1)8?alyan=.
Cyste".o(t.printlnB".!etB1)//9JJn(ll
1)88i1444444false
1)88i2444444false
"ea+6as#=ap:
It is eEa+tly sa"e as Sas#%ap eE+ept t#e followin! differen+es.
In t#e +ase of nor"al Sas#%ap- an ob,e+t is not eli!ible for ^' even t#o(!# it doesnAt
#ave any referen+es if it is asso+iated wit# Sas#%ap. T#at is Sas#%ap do"inates
!arba!e +olle+tor.
6(t in t#e +ase of @ea?Sas#%ap if an ob,e+t does not #ave any referen+es t#en itAs
always eli!ible for ^' even t#o(!# it is asso+iated wit# @ea?Sas#%ap t#at is !arba!e
+olle+tor do"inates @ea?Sas#%ap.
Example:
i"port ,ava.(til.U9
+lass @ea?Sas#%apDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption
7
@ea?Sas#%ap "8new @ea?Sas#%apB/9
Te"p t8new Te"pB/9

".p(tBt-Nb#as?arN/9
Cyste".o(t.printlnB"/9JJ7Te"p8b#as?ar=
t8n(ll9
Cyste".!+B/9
T#read.sleepB5)))/9
Cyste".o(t.printlnB"/9JJ7=
=

376

=
+lass Te"p
7
p(bli+ Ctrin! toCtrin!B/
7
ret(rn NTe"pN9
=
p(bli+ void finali0eB/
7
Cyste".o(t.printlnBNfinali0eB/ "et#od +alledN/9
=
=
!utput:
7Te"p8b#as?ar=
finali0eB/ "et#od +alled
7=
'iagram:

In t#e above pro!ra" if we repla+e @ea?Sas#%ap wit# nor"al Sas#%ap t#en ob,e+t
wonAt be destroyed by t#e !arba!e +olle+tor in t#is t#e o(tp(t is
7Te"p8b#as?ar=
7Te"p8b#as?ar=
2orted=ap:
It is t#e +#ild interfa+e of %ap.
If we want to represent a !ro(p of ?ey4val(e pairs a++ordin! to so"e sortin! order of
?eys t#en we s#o(ld !o for Corted%ap.
Cortin! is possible only based on t#e ?eys b(t not based on val(es.
Corted%ap interfa+e defines t#e followin! 6 spe+ifi+ "et#ods.

377

1/ Ib,e+t firsyGeyB/9
2/ Ib,e+t lastGeyB/9
3/ Corted%ap #ead%apBIb,e+t ?ey/9
4/ Corted%ap tail%apBIb,e+t ?ey/9
5/ Corted%ap s(b%apBIb,e+t ?ey1-Ib,e+t ?ey2/9
6/ 'o"parator +o"paratorB/9
8ree=ap:
1/ T#e (nderlyin! data str(+t(re is R<D46LA'G Tree.
2/ D(pli+ate ?eys are not allowed b(t val(es +an be d(pli+ated.
3/ Insertion order is not preserved and all entries will be inserted a++ordin! to so"e
sortin! order of ?eys.
4/ If we are dependin! on defa(lt nat(ral sortin! order ?eys s#o(ld be #o"o!eneo(s and
'o"parable ot#erwise we will !et 'lass'ast<E+eption.
5/ If we are definin! o(r own sortin! order by 'o"parator t#en ?eys +an be #etero!eneo(s
and non 'o"parable.
6/ T#ere are no restri+tions on val(es t#ey +an be #etero!eneo(s and non 'o"parable.
7/ Hor t#e e"pty Tree%ap as first entry n(ll ?ey is allowed b(t after insertin! t#at entry if
we are tryin! to insert any ot#er entry we will !et :(ll\ointer<E+eption.
$/ Hor t#e non e"pty Tree%ap if we are tryin! to insert an entry wit# n(ll ?ey we will !et
:(ll\ointer<E+eption.
&/ T#ere are no restri+tions for n(ll val(es.
*onstru$tors:
1/ Tree%ap t8new Tree%apB/9
Hor defa(lt nat(ral sortin! order.
2/ Tree%ap t8new Tree%apB'o"parator +/9
Hor +(sto"i0ed sortin! order.
3/ Tree%ap t8new Tree%apBCorted%ap "/9
4/ Tree%ap t8new Tree%apB%ap "/9
Example 1:
i"port ,ava.(til.U9
+lass Tree%apDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Tree%ap t8new Tree%apB/9
t.p(tB1))-N111N/9
t.p(tB1)3-NaaaN/9
t.p(tB1)1-NPPPN/9

37$

t.p(tB1)4-1)6/9
t.p(tB1)7-n(ll/9
JJt.p(tBNHHHN-NPPPN/9JJ'lass'ast<E+eption
JJt.p(tBn(ll-NEEEN/9JJ:(ll\ointer<E+eption
Cyste".o(t.printlnBt/9JJ71))8111- 1)18PPP- 1)38aaa- 1)481)6- 1)78n(ll=
=
=
Example 2:
i"port ,ava.(til.U9
+lass Tree%apDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Tree%ap t8new Tree%apBnew %y'o"paratorB//9
t.p(tBNPPPN-1)/9
t.p(tBNAAAN-2)/9
t.p(tBN111N-3)/9
t.p(tBNLLLN-4)/9
Cyste".o(t.printlnBt/9JJ711183)- PPP81)- LLL84)- AAA82)=
=
=
+lass %y'o"parator i"ple"ents 'o"parator
7
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/
7
Ctrin! s18ob,1.toCtrin!B/9
Ctrin! s28ob,2.toCtrin!B/9
ret(rn s2.+o"pareToBs1/9
=
=
6as#ta,le:
1/ T#e (nderlyin! data str(+t(re is Sas#table.
2/ Insertion order is not preserved and it is based on #as# +ode of t#e ?eys.
3/ Setero!eneo(s ob,e+ts are allowed for bot# ?eys and val(es.
4/ :(ll ?ey Bor/ n(ll val(e is not allowed ot#erwise we will !et :(ll\ointer<E+eption.
5/ D(pli+ate ?eys are allowed b(t val(es +an be d(pli+ated.
*onstru$tors:
1/ Sas#table #8new Sas#tableB/9

37&

'reates an e"pty Sas#table ob,e+t wit# defa(lt initial+apa+ity 11 and defa(lt fill ratio
).75.
2/ Sas#table #8new Sas#tableBint initial+apa+ity/9
3/ Sas#table #8new Sas#tableBint initial+apa+ity-float fillratio/9
4/ Sas#table #8new Sas#table B%ap "/9
Example:
i"port ,ava.(til.U9
+lass Sas#tableDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Sas#table #8new Sas#tableB/9
#.p(tBnew Te"pB5/-NAN/9
#.p(tBnew Te"pB2/-N6N/9
#.p(tBnew Te"pB6/-N'N/9
#.p(tBnew Te"pB15/-NDN/9
#.p(tBnew Te"pB23/-N<N/9
#.p(tBnew Te"pB16/-NHN/9
Cyste".o(t.printlnB#/9JJ768'- 168H- 58A- 158D- 286- 238<=
=
=
+lass Te"p
7
int i9
Te"pBint i/
7
t#is.i8i9
=
p(bli+ int #as#'odeB/
7
ret(rn i9
=
p(bli+ Ctrin! toCtrin!B/
7
ret(rn iFNN9
=
=
'iagram:

3$)


/ote: if we +#an!e #as'odeB/ "et#od of Te"p +lass as follows.
p(bli+ int #as#'odeB/
7
ret(rn i`&9
=
T#en t#e o(tp(t is 7168H- 158D- 68'- 238<- 58A- 286=.
'iagram:

/ote: if we +#an!e initial +apa+ity as 25.
6as#ta,le #Mne% 6as#ta,le:25;E
'iagram:

3$1


3roperties:
1/ \roperties +lass is t#e +#ild +lass of Sas#table.
2/ If anyt#in! w#i+# +#an!es freV(ently s(+# type of val(es not re+o""ended to #ard+ode
in ,ava appli+ation be+a(se for every +#an!e we #ave to re+o"pile- reb(ild and
redeployed t#e appli+ation and even server restart also reV(ired so"eti"es it +reates a
bi! b(siness i"pa+t to t#e +lient.
3/ C(+# type of variable t#in!s we #ave to #ard+ode in property files and we #ave to read
t#e val(es fro" t#e property files.
4/ T#e "ain advanta!e in t#is approa+# is if t#ere is any +#an!e in property files
a(to"ati+ally t#ose +#an!es will be available to ,ava appli+ation ,(st redeploy"ent is
eno(!#.
5/ 6y (sin! \roperties ob,e+t we +an read and #old properties fro" property files into ,ava
appli+ation.
*onstru$tor:
3roperties pMne% 3roperties:;E
In properties bot# ?ey and val(e Ks#o(ld be Ctrin! type onlyL.
=et#ods:
1/ Ctrin! !et\rpertyBCtrin! propertyna"e/ 9
Ret(rns t#e val(e asso+iated wit# spe+ified property.
2/ Ctrin! setpropertyBCtrin! propertyna"e-Ctrin! propertyval(e/9
To set a new property.

3$2

3/ <n("eration property:a"esB/9
4/ void loadBInp(tCtrea" is/9JJAny Inp(tCtrea" we +an pass.
To load \roperties fro" property files into ,ava \roperties ob,e+t.
5/ void storeBI(tp(tCtrea" os-Ctrin! +o""ent/9JJAny I(tp(tCtrea" we +an pass.
To store t#e properties fro" \roperties ob,e+t into properties file.
'iagram:

Example:
i"port ,ava.(til.U9
i"port ,ava.io.U9
+lass \ropertiesDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows <E+eption
7
\roperties p8new \ropertiesB/9
HileInp(tCtrea" fis8new HileInp(tCtrea"BNab+.propertiesN/9
p.loadBfis/9
Cyste".o(t.printlnBp/9JJ7(ser8s+ott- password8ti!er- ven?i8$$$$=
Ctrin! s8p.!et\ropertyBNven?iN/9
Cyste".o(t.printlnBs/9JJ$$$$
p.set\ropertyBNna!N-N&&&&&&&N/9
<n("eration e8p.property:a"esB/9
w#ileBe.#as%ore<le"entsB//
7
Ctrin! s18BCtrin!/e.neEt<le"entB/9
Cyste".o(t.printlnBs1/9JJna!
JJ(ser
JJpassword
JJven?i
=
HileI(tp(tCtrea" fos8new HileI(tp(tCtrea"BNab+.propertiesN/9
p.storeBfos-N(pdated by b#as?ar for s+,p de"o +lassN/9
=

3$3

=
3ropert( file:

195 en#an$ements :Zueue interfa$e;
1/ If we want to represent a !ro(p of individ(al ob,e+ts prior B#appenin! before so"et#in!
else/ to pro+essin! t#en we s#o(ld !o for _(e(e interfa+e.
'iagram:

2/ ;s(ally _(e(e follows first in first out order b(t based on o(r reV(ire"ent we +an
i"ple"ent o(r own order also.
3/ Hro" 1.5v onwards Lin?edList also i"ple"ents _(e(e interfa+e.
4/ Lin?edList based i"ple"entation of _(e(e always follows first in first o(t order.
Zueue interfa$e met#ods:
1/ boolean afterBIb,e+t o/9
To add an ob,e+t to t#e _(e(e.
2/ Ib,e+t pollB/ 9
To re"ove and ret(rn #ead ele"ent of t#e _(e(e- if _(e(e is e"pty t#en we will !et
n(ll.
3/ Ib,e+t re"oveB/9
To re"ove and ret(rn #ead ele"ent of t#e _(e(e. If _(e(e is e"pty t#en t#is "et#od
raises R(nti"e <E+eption sayin! :oC(+#<le"ent<E+eption.
4/ Ib,e+t pee?B/9
To ret(rn #ead ele"ent of t#e _(e(e wit#o(t re"oval- if _(e(e is e"pty t#is "et#od
ret(rns n(ll.
5/ Ib,e+t ele"entB/9
It ret(rns #ead ele"ent of t#e _(e(e and if _(e(e is e"pty t#en it will raise R(nti"e
<E+eption sayin! :oC(+#<le"ent<E+eption.
3riorit(Zueue:

3$4

1/ @e +an (se \riority_(e(e to represent a !ro(p of individ(al ob,e+ts prior to pro+essin!
a++ordin! to so"e priority.
2/ T#e priority order +an be eit#er defa(lt nat(ral sortin! order Bor/ +(sto"i0ed sortin!
order spe+ified by 'o"parator ob,e+t.
3/ If we are dependin! on defa(lt nat(ral sortin! order t#en t#e ob,e+ts "(st be
#o"o!eneo(s and 'o"parable ot#erwise we will !et 'lass'ast<E+eption.
4/ If we are definin! o(r own +(sto"i0ed sortin! order by 'o"parator t#en t#e ob,e+ts
need not be #o"o!eneo(s and 'o"parable.
5/ D(pli+ate ob,e+ts are not allowed.
6/ Insertion order is not preserved b(t all ob,e+ts will be inserted a++ordin! to so"e
priority.
7/ :(ll is not allowed even as t#e 1
st
ele"ent for e"pty \riority_(e(e.
*onstru$tors:
1/ \riority_(e(e V8new \riority_(e(eB/9
'reates an e"pty \riority_(e(e wit# defa(lt initial +apa+ity 11 and defa(lt nat(ral
sortin! order.
2/ \riority_(e(e V8new \riority_(e(eBint initial+apa+ity-'o"parator +/9
3/ \riority_(e(e V8new \riority_(e(eBint initial+apa+ity/9
4/ \riority_(e(e V8new \riority_(e(eB'olle+tion +/9
5/ \riority_(e(e V8new \riority_(e(eBCortedCet s/9

Example 1:
i"port ,ava.(til.U9
+lass \riority_(e(eDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\riority_(e(e V8new \riority_(e(eB/9
JJCyste".o(t.printlnBV.pee?B//9JJn(ll
JJCyste".o(t.printlnBV.ele"entB//9JJ:oC(+#<le"ent<E+eption
forBint i8)9iZ81)9iFF/
7
V.offerBi/9
=
Cyste".o(t.printlnBV/9JJD)- 1- 2- 3- 4- 5- 6- 7- $- &- 1)>
Cyste".o(t.printlnBV.pollB//9JJ)
Cyste".o(t.printlnBV/9JJD1- 3- 2- 7- 4- 5- 6- 1)- $- &>
=

3$5

=
/ote: Co"e platfor"s "ay not provide proper s(pports for \riority_(e(e DwindowsP\>.
Example 2:
i"port ,ava.(til.U9
+lass \riority_(e(eDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\riority_(e(e V8new \riority_(e(eB15-new %y'o"paratorB//9
V.offerBNAN/9
V.offerBN1N/9
V.offerBNLN/9
V.offerBN6N/9
Cyste".o(t.printlnBV/9JJD1- 6- L- A>
=
=
+lass %y'o"parator i"ple"ents 'o"parator
7
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/
7
Ctrin! s18BCtrin!/ob,19
Ctrin! s28ob,2.toCtrin!B/9
ret(rn s2.+o"pareToBs1/9
=
=
196v En#an$ements :/aviga,le2et and /aviga,le=ap;
/aviga,le2et:
1/ It is t#e +#ild interfa+e of CortedCet.
2/ It provides several "et#ods for navi!ation p(rposes.
'iagram:


3$6


:avi!ableCet interfa+e defines t#e followin! "et#ods.
1/ +eilin!Be/9
It ret(rns t#e lowest ele"ent w#i+# is T8e.
2/ #i!#erBe/9
It ret(rns t#e lowest ele"ent w#i+# is Te.
3/ floorBe/9
It ret(rns #i!#est ele"ent w#i+# is Z8e.
4/ lowerBe/9
It ret(rns #ei!#t ele"ent w#i+# is Ze.
5/ pollHirst B/9
Re"ove and ret(rn 1
st
ele"ent.
6/ pollLast B/9
Re"ove and ret(rn last ele"ent.
7/ des+endin!Cet B/9
Ret(rns CortedCet in reverse order.





'iagram:

Example:
i"port ,ava.(til.U9
+lass :avi!ableCetDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
TreeCetZInte!erT t8new TreeCetZInte!erTB/9
t.addB1)))/9
t.addB2)))/9
t.addB3)))/9

3$7

t.addB4)))/9
t.addB5)))/9
Cyste".o(t.printlnBt/9JJD1)))- 2)))- 3)))- 4)))- 5)))>
Cyste".o(t.printlnBt.+eilin!B2)))//9JJ2)))
Cyste".o(t.printlnBt.#i!#erB2)))//9JJ3)))
Cyste".o(t.printlnBt.floorB3)))//9JJ3)))
Cyste".o(t.printlnBt.lowerB3)))//9JJ2)))
Cyste".o(t.printlnBt.pollHirstB//9JJ1)))
Cyste".o(t.printlnBt.pollLastB//9JJ5)))
Cyste".o(t.printlnBt.des+endin!CetB//9JJD4)))- 3)))- 2)))>
Cyste".o(t.printlnBt/9JJD2)))- 3)))- 4)))>
=
=
/aviga,le=ap:
It is t#e +#ild interfa+e of Corted%ap and it defines several "et#ods for navi!ation
p(rpose.





'iagram:

:avi!able%ap interfa+e defines t#e followin! "et#ods.
1/ +eilin!GeyBe/9
2/ #i!#erGeyBe/9
3/ floorGeyBe/9
4/ lowerGeyBe/9
5/ pollHirst<ntryB/9
6/ pollLast<ntryB/9
7/ des+endin!%apB/9

3$$

Example:
i"port ,ava.(til.U9
+lass :avi!able%apDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Tree%apZCtrin!-Ctrin!T t8new Tree%apZCtrin!-Ctrin!TB/9
t.p(tBNbN-NbananaN/9
t.p(tBN+N-N+atN/9
t.p(tBNaN-NappleN/9
t.p(tBNdN-Ndo!N/9
t.p(tBN!N-N!(nN/9
Cyste".o(t.printlnBt/9JJ7a8apple- b8banana- +8+at- d8do!- !8!(n=
Cyste".o(t.printlnBt.+eilin!GeyBN+N//9JJ+
Cyste".o(t.printlnBt.#i!#erGeyBNeN//9JJ!
Cyste".o(t.printlnBt.floorGeyBNeN//9JJd
Cyste".o(t.printlnBt.lowerGeyBNeN//9JJd
Cyste".o(t.printlnBt.pollHirst<ntryB//9JJa8apple
Cyste".o(t.printlnBt.pollLast<ntryB//9JJ!8!(n
Cyste".o(t.printlnBt.des+endin!%apB//9JJ7d8do!- +8+at- b8banana=
Cyste".o(t.printlnBt/9JJ7b8banana- +8+at- d8do!=
=
=
'iagram:

*olle$tions $lass:
'olle+tions +lass defines several (tility "et#ods for +olle+tion ob,e+ts.
2orting t#e elements of a List:
'olle+tions +lass defines t#e followin! "et#ods to perfor" sortin! t#e ele"ents of a
List.
pu,li$ stati$ void sort:List l;E

3$&

To sort t#e ele"ents of List a++ordin! to defa(lt nat(ral sortin! order in t#is +ase t#e
ele"ents s#o(ld be #o"o!eneo(s and +o"parable ot#erwise we will !et
'lass'ast<E+eption.
T#e List s#o(ld not +ontain n(ll ot#erwise we will !et :(ll\ointer<E+eption.
pu,li$ stati$ void sort:List lH*omparator $;E
To sort t#e ele"ents of List a++ordin! to +(sto"i0ed sortin! order.
3rogram 1: To sort ele"ents of List a++ordin! to nat(ral sortin! order.
i"port ,ava.(til.U9
+lass 'olle+tionsDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
ArrayList l8new ArrayListB/9
l.addBN1N/9
l.addBNAN/9
l.addBNGN/9
l.addBN:N/9
JJl.addBnew Inte!erB1)//9JJ'lass'ast<E+eption
JJl.addBn(ll/9JJ:(ll\ointer<E+eption
Cyste".o(t.printlnBN6efore sortin! .NFl/9JJD1- A- G- :>
'olle+tions.sortBl/9
Cyste".o(t.printlnBNAfter sortin! .NFl/9JJDA- G- :- 1>
=
=
3rogram 2: To sort ele"ents of List a++ordin! to +(sto"i0ed sortin! order.
i"port ,ava.(til.U9
+lass 'olle+tionsDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
ArrayList l8new ArrayListB/9
l.addBN1N/9
l.addBNAN/9
l.addBNGN/9
l.addBNLN/9
l.addBnew Inte!erB1)//9
JJl.addBn(ll/9JJ:(ll\ointer<E+eption
Cyste".o(t.printlnBN6efore sortin! .NFl/9JJD1- A- G- L- 1)>

3&)

'olle+tions.sortBl-new %y'o"paratorB//9
Cyste".o(t.printlnBNAfter sortin! .NFl/9JJD1- L- G- A- 1)>
=
=
+lass %y'o"parator i"ple"ents 'o"parator
7
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/
7
Ctrin! s18BCtrin!/ob,19
Ctrin! s28ob,2.toCtrin!B/9
ret(rn s2.+o"pareToBs1/9
=
=
2ear$#ing t#e elements of a List:
'olle+tions +lass defines t#e followin! "et#ods to sear+# t#e ele"ents of a List.
pu,li$ stati$ int ,inar(2ear$#:List lH!,je$t o,j;E
If t#e List is sorted a++ordin! to defa(lt nat(ral sortin! order t#en we #ave to (se t#is
"et#od.
pu,li$ stati$ int ,inar(2ear$#:List lH!,je$t o,jH*omparator $;E
If t#e List is sorted a++ordin! to 'o"parator t#en we #ave to (se t#is "et#od.


3rogram 1: To sear+# ele"ents of List.
i"port ,ava.(til.U9
+lass 'olle+tionsCear+#De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
ArrayList l8new ArrayListB/9
l.addBN1N/9
l.addBNAN/9
l.addBN%N/9
l.addBNGN/9
l.addBNaN/9
Cyste".o(t.printlnBl/9JJD1- A- %- G- a>
'olle+tions.sortBl/9
Cyste".o(t.printlnBl/9JJDA- G- %- 1- a>
Cyste".o(t.printlnB'olle+tions.binaryCear+#Bl-N1N//9JJ3

3&1

Cyste".o(t.printlnB'olle+tions.binaryCear+#Bl-N*N//9JJ42
=
=
'iagram:

3rogram 2:
i"port ,ava.(til.U9
+lass 'olle+tionsCear+#De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
ArrayList l8new ArrayListB/9
l.addB15/9
l.addB)/9
l.addB2)/9
l.addB1)/9
l.addB5/9
Cyste".o(t.printlnBl/9JJD15- )- 2)- 1)- 5>
'olle+tions.sortBl-new %y'o"paratorB//9
Cyste".o(t.printlnBl/9JJD2)- 15- 1)- 5- )>
Cyste".o(t.printlnB'olle+tions.binaryCear+#Bl-1)-new %y'o"paratorB///9JJ2
Cyste".o(t.printlnB'olle+tions.binaryCear+#Bl-13-new %y'o"paratorB///9JJ43
Cyste".o(t.printlnB'olle+tions.binaryCear+#Bl-17//9JJ46
=
=
+lass %y'o"parator i"ple"ents 'o"parator
7
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/
7
Inte!er i18BInte!er/ob,19
Inte!er i28BInte!er/ob,29
ret(rn i2.+o"pareToBi1/9
=
=
'iagram:

3&2


*on$lusions:
1/ Internally t#ese sear+# "et#ods will (se binary sear+# al!orit#".
2/ C(++essf(l sear+# ret(rns index (ns(++essf(l sear+# ret(rns insertion point.
3/ Insertion point is t#e lo+ation w#ere we +an pla+e t#e ele"ent in t#e sorted list.
4/ 6efore +allin! binaryCear+#B/ "et#od +o"p(lsory t#e list s#o(ld be sorted ot#erwise we
will !et (npredi+table res(lts.
5/ If t#e list is sorted a++ordin! to 'o"parator t#en at t#e ti"e of sear+# operation also we
s#o(ld pass t#e sa"e 'o"parator ob,e+t ot#erwise we will !et (npredi+table res(lts.
/ote:
Hor t#e list of n ele"ents wit# respe+t to binary Cear+#B/ "et#od.
C(++essf(l sear+# ran!e is. ) to n41.
;ns(++essf(l sear+# res(lts ran!e is. 4BnF1/to 41.
Total res(lt ran!e is. 4BnF1/to n41.







Example:

Reversing t#e elements of List:
pu,li$ stati$ void reverse:List l;E
reverse:; vs reverse!rder:; met#od
@e +an (se reverseB/ "et#od to reverse t#e ele"ents of List.
@#ere as we +an (se reverseIrderB/ "et#od to !et reversed 'o"parator.

3&3


3rogram: To reverse ele"ents of list.
i"port ,ava.(til.U9
+lass 'olle+tionsReverseDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
ArrayList l8new ArrayListB/9
l.addB15/9
l.addB)/9
l.addB2)/9
l.addB1)/9
l.addB5/9
Cyste".o(t.printlnBl/9JJD15- )- 2)- 1)- 5>
'olle+tions.reverseBl/9
Cyste".o(t.printlnBl/9JJD5- 1)- 2)- )- 15>
=
=
7rra(s $lass:
Arrays +lass defines several (tility "et#ods for arrays.
2orting t#e elements of arra(:
pu,li$ stati$ void sort:primitiveTU p;EJJany pri"itive data type we +an !ive
To sort t#e ele"ents of pri"itive array a++ordin! to defa(lt nat(ral sortin! order.
pu,li$ stati$ void sort:o,je$tTU o;E
To sort t#e ele"ents of ob,e+tD> array a++ordin! to defa(lt nat(ral sortin! order.
In t#is +ase ob,e+ts s#o(ld be #o"o!eneo(s and 'o"parable.
pu,li$ stati$ void sort:o,je$tTU oH*omparator $;E
To sort t#e ele"ents of ob,e+tD> array a++ordin! to +(sto"i0ed sortin! order.
/ote: @e +an sort ob,e+tD> array eit#er by defa(lt nat(ral sortin! order Bor/ +(sto"i0ed sortin!
order b(t we +an sort pri"itive arrays only by defa(lt nat(ral sortin! order.
3rogram: To sort ele"ents of array.
i"port ,ava.(til.U9
+lass ArrayCortDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/

3&4

7
intD> a871)-5-2)-11-6=9
Cyste".o(t.printlnBNpri"itive array before sortin!N/9
forBint a1.a/
7
Cyste".o(t.printlnBa1/9
=
Arrays.sortBa/9
Cyste".o(t.printlnBNpri"itive array after sortin!N/9
forBint a1. a/
7
Cyste".o(t.printlnBa1/9
=
Ctrin!D> s87NAN-N1N-N6N=9
Cyste".o(t.printlnBNIb,e+t array before sortin!N/9
forBCtrin! s1. s/
7
Cyste".o(t.printlnBs1/9
=
Arrays.sortBs/9
Cyste".o(t.printlnBNIb,e+t array after sortin!N/9
forBCtrin! s1.s/
7
Cyste".o(t.printlnBs1/9
=
Arrays.sortBs-new %y'o"paratorB//9
Cyste".o(t.printlnBNIb,e+t array after sortin! by 'o"parator.N/9
forBCtrin! s1. s/
7
Cyste".o(t.printlnBs1/9
=
=
=
+lass %y'o"parator i"ple"ents 'o"parator
7
p(bli+ int +o"pareBIb,e+t ob,1-Ib,e+t ob,2/
7
Ctrin! s18ob,1.toCtrin!B/9

3&5

Ctrin! s28ob,2.toCtrin!B/9
ret(rn s2.+o"pareToBs1/9
=
=
2ear$#ing t#e elements of arra(:
Arrays +lass defines t#e followin! "et#ods to sear+# ele"ents of array.
1; pu,li$ stati$ int ,inar(2ear$#:primitiveTU pHprimitive +e(;E
2; pu,li$ stati$ int ,inar(2ear$#:!,je$tTU pH o,je$t +e(;E
3; pu,li$ stati$ int ,inar(2ear$#:!,je$tTU pH!,je$t +e(H*omparator $;E
All r(les of Arrays +lass binaryCear+#B/ "et#od are eEa+tly sa"e as 'olle+tions +lass
binaryCear+#B/ "et#od.
3rogram: To sear+# ele"ents of array.
i"port ,ava.(til.U9
+lass ArraysCear+#De"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
intD> a871)-5-2)-11-6=9
Arrays.sortBa/9
Cyste".o(t.printlnBArrays.binaryCear+#Ba-6//9JJ1
Cyste".o(t.printlnBArrays.binaryCear+#Ba-14//9JJ45
Ctrin!D> s87NAN-N1N-N6N=9
Arrays.sortBs/9
Cyste".o(t.printlnBArrays.binaryCear+#Bs-N1N//9JJ2
Cyste".o(t.printlnBArrays.binaryCear+#Bs-NCN//9JJ43
Arrays.sortBs-new %y'o"paratorB//9
Cyste".o(t.printlnBArrays.binaryCear+#Bs-N1N-new %y'o"paratorB///9JJ)
Cyste".o(t.printlnBArrays.binaryCear+#Bs-NCN-new %y'o"paratorB///9JJ42
Cyste".o(t.printlnBArrays.binaryCear+#Bs-N:N//9JJ44B(npredi+table res(lt/
=
=
*onverting arra( to List:
Arrays +lass defines t#e followin! "et#od to view array as List.
pu,li$ stati$ List asList :!,je$tTU o;E
Ctri+tly spea?in! we are not +reatin! an independent List ob,e+t ,(st we are viewin!
array in List for".

3&6

6y (sin! List referen+e if we are perfor"in! any +#an!e a(to"ati+ally t#ese +#an!es will
be refle+ted to array referen+e si"ilarly by (sin! array referen+e if we are perfor"in!
any +#an!e a(to"ati+ally t#ese +#an!es will be refle+ted to t#e List referen+e.
6y (sin! List referen+e if we are tryin! to perfor" any operation w#i+# varies t#e si0e
t#en we will !et r(nti"e eE+eption sayin! .nsupported!perationEx$eption.
6y (sin! List referen+e if we are tryin! to insert #etero!eneo(s ob,e+ts we will !et
r(nti"e eE+eption sayin! 7rra(2toreEx$eption.
3rogram: To view array in List for".
i"port ,ava.(til.U9
+lass ArraysAsListDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!D> s87NAN-N1N-N6N=9
List l8Arrays.asListBs/9
Cyste".o(t.printlnBl/9JJDA- 1- 6>
sD)>8NGN9
Cyste".o(t.printlnBl/9JJDG- 1- 6>
l.setB1-NLN/9
forBCtrin! s1. s/
Cyste".o(t.printlnBs1/9JJG-L-6
JJl.addBNb#as?arN/9JJ;ns(pportedIperation<E+eption
JJl.re"oveB2/9JJ;ns(pportedIperation<E+eption
JJl.setB1-new Inte!erB1)//9JJArrayCtore<E+eption
=
=

'iagram:






3&7

















Generi$s
7genda:
1; Introdu$tion
2; Generi$ *lasses
3; 1ounded 8(pes
4; Generi$ met#ods and %ild $ard $#ara$ter
5; *ommuni$ation %it# non generi$ $ode
6; *on$lusions
Introdu$tion:
*ase 1:

3&$

Arrays are always type safe t#at is we +an provide t#e !(arantee for t#e type of
ele"ents present inside array.
Hor eEa"ple if o(r pro!ra""in! reV(ire"ent is to #old Ctrin! type of ob,e+ts it is
re+o""ended to (se Ctrin! array. In t#e +ase of strin! array we +an add only strin! type
of ob,e+ts by "ista?e if we are tryin! to add any ot#er type we will !et +o"pile ti"e
error.
Example:

T#at is we +an always provide !(arantee for t#e type of ele"ents present inside array
and #en+e arrays are safe to (se wit# respe+t to type t#at is arrays are type safe.
6(t +olle+tions are not type safe t#at is we +anAt provide any !(arantee for t#e type of
ele"ents present inside +olle+tion.
Hor eEa"ple if o(r pro!ra""in! reV(ire"ent is to #old only strin! type of ob,e+ts it is
never re+o""ended to !o for ArrayList.
6y "ista?e if we are tryin! to add any ot#er type we wonAt !et any +o"pile ti"e error
b(t t#e pro!ra" "ay fail at r(nti"e.







Example:


3&&

Sen+e we +anAt provide !(arantee for t#e type of ele"ents present inside +olle+tions
t#at is $olle$tions are not safe to use %it# respe$t to t(pe.
*ase 2: In t#e +ase of array at t#e ti"e of retrieval it is not reV(ired to perfor" any type
+astin!.
Example:

6(t in t#e +ase of +olle+tion at t#e ti"e of retrieval +o"p(lsory we s#o(ld perfor" type
+astin! ot#erwise we will !et +o"pile ti"e error.
Example:

T#at is in +olle+tions type +astin! is bi!!er #eada+#e.
To over+o"e t#e above proble"s of +olle+tionsBtype4safety- type +astin!/s(n people
introd(+ed !eneri+s +on+ept in 1.5v #en+e t#e "ain ob,e+tives of !eneri+s are.
1/ To provide type safety to t#e +olle+tions.
2/ To resolve type +astin! proble"s.
To #old only strin! type of ob,e+ts we +an +reate a !eneri+ version of ArrayList as
follows.
Example:

4))


Hor t#is ArrayList we +an add only strin! type of ob,e+ts by "ista?e if we are tryin! to
add any ot#er type we will !et +o"pile ti"e error t#at is t#ro(!# !eneri+s we are
!ettin! type safety.
At t#e ti"e of retrieval it is not reV(ired to perfor" any type +astin! we +an assi!n
ele"ents dire+tly to strin! type variables.
Example:

T#at is t#ro(!# !eneri+ syntaE we +an resolve type +astin! proble"s.
*on$lusion1:
\oly"orp#is" +on+ept is appli+able only for t#e base type b(t not for para"eter
typeD(sa!e of parent referen+e to #old +#ild ob,e+t is +alled poly"orp#is">.
Example:

*on$luson2:
Hor t#e para"eter type we +an (se any +lass or interfa+e b(t not pri"itive val(eBtype/.
Example:


4)1

Generi$ $lasses:
;ntil1.4v ArrayList +lass is de+lared as follows.
Example:
+lass ArrayList
7
addBIb,e+t o/9
Ib,e+t !etBint indeE/9
=
addB/ "et#od +an ta?e ob,e+t as t#e ar!("ent and #en+e we +an add any type of ob,e+t
to t#e ArrayList. D(e to t#is we are not !ettin! type safety.
T#e ret(rn type of !etB/ "et#od is ob,e+t #en+e at t#e ti"e of retrieval +o"p(lsory we
s#o(ld perfor" type +astin!.
6(t in 1.5v a !eneri+ version of ArrayList +lass is de+lared as follows.
Example:

6ased on o(r reV(ire"ent 8 will be repla+ed wit# o(r provided type. Hor <Ea"ple
To #old only strin! type of ob,e+ts we +an +reate ArrayList ob,e+t as follows.
Example:
7rra(ListL2tringN lMne% 7rra(ListL2tringN:;E
Hor t#is reV(ire"ent +o"piler +onsidered ArrayList +lass is
Example:
+lass ArrayListZCtrin!T
7
addBCtrin! s/9
Ctrin! !etBint indeE/9
=
addB/ "et#od +an ta?e only strin! type as ar!("ent #en+e we +an add only strin! type
of ob,e+ts to t#e List. 6y "ista?e if we are tryin! to add any ot#er type we will !et
+o"pile ti"e error.
Example:

4)2


Sen+e t#ro(!# !eneri+s we are !ettin! type safety.
At t#e ti"e of retrieval it is not reV(ired to perfor" any type +astin! we +an assi!n its
val(es dire+tly to strin! variables.
Example:

6ased on o(r reV(ire"ent we +an +reate o(r own !eneri+ +lasses also.
Example:
+lass A++o(ntZTT
7=
A++o(ntZ^oldT !18new A++o(ntZ^oldTB/9
A++o(ntZCilverT !28new A++o(ntZCilverTB/9
Example:
+lass ;D^eneri+sZTT
7
T ob,9
;D^eneri+sBT ob,/
7
t#is.ob,8ob,9
=

4)3

p(bli+ void s#owB/
7
Cyste".o(t.printlnBNT#e type of ob,e+t is .NFob,.!et'lassB/.!et:a"eB//9
=
p(bli+ T !etIb,e+tB/
7
ret(rn ob,9
=
=
+lass ^eneri+sDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
;D^eneri+sZInte!erT !18new ;D^eneri+sZInte!erTB1)/9
!1.s#owB/9
Cyste".o(t.printlnB!1.!etIb,e+tB//9
;D^eneri+sZCtrin!T !28new ;D^eneri+sZCtrin!TBNb#as?arN/9
!2.s#owB/9
Cyste".o(t.printlnB!2.!etIb,e+tB//9
;D^eneri+sZDo(bleT !38new ;D^eneri+sZDo(bleTB1).5/9
!3.s#owB/9
Cyste".o(t.printlnB!3.!etIb,e+tB//9
=
=
!utput:
T#e type of ob,e+t is. ,ava.lan!.Inte!er
1)
T#e type of ob,e+t is. ,ava.lan!. Ctrin!
6#as?ar
T#e type of ob,e+t is. ,ava.lan!. Do(ble
1).5
1ounded t(pes:
@e +an bo(nd t#e type para"eter for a parti+(lar ran!e by (sin! eEtends ?eyword s(+#
types are +alled bo(nded types.
Example 1:
+lass TestZTT
7=
Test ZInte!erT t18new Test Z Inte!erTB/9

4)4

Test ZCtrin!T t28new Test Z Ctrin!TB/9
Sere as t#e type para"eter we +an pass any type and t#ere are no restri+tions #en+e it
is (nbo(nded type.
Example 2:
+lass TestZT eEtends PT
7=
If E is a +lass t#en as t#e type para"eter we +an pass eit#er E or its +#ild +lasses.
If E is an interfa+e t#en as t#e type para"eter we +an pass eit#er E or its i"ple"entation
+lasses.
Example 1:

Example 2:

@e +anAt define bo(nded types by (sin! i"ple"ents and s(per ?eyword.
Example:

6(t i"ple"ents ?eyword p(rpose we +an repla+e wit# eEtends ?eyword.
As t#e type para"eter we +an (se any valid ,ava identifier b(t it +onvention to (se 8
always.
Example:


4)5

@e +an pass any no of type para"eters need not be one.
Example:

6as#=apLIntegerH2tringN #Mne% 6as#=apLIntegerH2tringN:;E
@e +an define bo(nded types even in +o"bination also.
Example 1:
+lass TestZT eEtends :("bercR(nnableT
7=Bvalid/
As t#e type para"eter we +an pass any type w#i+# eEtends :("ber +lass and
i"ple"ents R(nnable interfa+e.
Example 2:
+lass TestZT eEtends :("bercR(nnablec'o"parableT
7=Bvalid/
Example 3:
+lass TestZT eEtends :("bercCtrin!T
7=Binvalid/
@e +anAt eEtend "ore t#an one +lass at a ti"e.
Example 4:
+lass TestZT eEtends R(nnablec'o"parableT
7=Bvalid/
Example 5:
+lass TestZT eEtends R(nnablec:("berT
7=Binvalid/
@e #ave to ta?e 1
st
+lass followed by interfa+e.
Generi$ met#ods and %ild<$ard $#ara$ter :&;:
met#od!ne:7rra(ListL2tringN l;: T#is "et#od is appli+able for ArrayList of only Ctrin! type.
Example:
l.addBNAN/9
l.addBn(ll/9
l.addB1)/9JJBinvalid/
@it#in t#e "et#od we +an add only Ctrin! type of ob,e+ts and n(ll to t#e List.
met#od!ne:7rra(ListL&N l;: @e +an (se t#is "et#od for ArrayList of any type b(t wit#in t#e
"et#od we +anAt add anyt#in! to t#e List eE+ept n(ll.
Example:
l.addBn(ll/9JJBvalid/

4)6

l.addBNAN/9JJBinvalid/
l.addB1)/9JJBinvalid/
T#is "et#od is (sef(l w#enever we are perfor"in! only read operation.
met#od!ne:7rra(ListL& Extends xN l;:
If E is a +lass t#en t#is "et#od is appli+able for ArrayList of eit#er E type or its +#ild
+lasses.
If E is an interfa+e t#en t#is "et#od is appli+able for ArrayList of eit#er E type or its
i"ple"entation +lasses.
In t#is +ase also wit#in t#e "et#od we +anAt add anyt#in! to t#e List eE+ept n(ll.
met#od!ne:7rra(ListL& super xN l;:
If E is a +lass t#en t#is "et#od is appli+able for ArrayList of eit#er E type or its s(per
+lasses.
If E is an interfa+e t#en t#is "et#od is appli+able for ArrayList of eit#er E type or s(per
+lasses of i"ple"entation +lass of E.
6(t wit#in t#e "et#od we +an add E type ob,e+ts and n(ll to t#e List.
"#i$# of t#e follo%ing de$larations are allo%ed&
1/ ArrayListZCtrin!T l18new ArrayListZCtrin!TB/9JJBvalid/
2/ ArrayListZWT l28new ArrayListZCtrin!TB/9JJBvalid/
3/ ArrayListZWT l38new ArrayListZInte!erTB/9JJBvalid/
4/ ArrayListZW eEtends :("berT l48new ArrayListZInte!erTB/9JJBvalid/
5/ ArrayListZW eEtends :("berT l58new ArrayListZCtrin!TB/9Binvalid/
!utput:
'o"pile ti"e error.
Test.,ava.1). in+o"patible types
Ho(nd . ,ava.(til.ArrayListZ,ava.lan!.Ctrin!T
ReV(ired. ,ava.(til.ArrayListZW eEtends ,ava.lan!.:("berT
ArrayListZW eEtends :("berT l58new ArrayListZCtrin!TB/9
6/ ArrayListZWT l68new ArrayListZW eEtends :("berTB/9
!utput:
'o"pile ti"e error
Test.,ava.11. (neEpe+ted type
fo(nd . W eEtends ,ava.lan!.:("ber
reV(ired. +lass or interfa+e wit#o(t bo(nds
ArrayListZWT l68new ArrayListZW eEtends :("berTB/9
7/ ArrayListZWT l78new ArrayListZWTB/9
!utput:
Test.,ava.12. (neEpe+ted type
Ho(nd .W

4)7

ReV(ired. +lass or interfa+e wit#o(t bo(nds
ArrayListZWT l78new ArrayListZWTB/9
@e +an de+lare t#e type para"eter eit#er at +lass level or "et#od level.
'e$laring t(pe parameter at $lass level:
+lass TestZTT
7
@e +an (se anyw#ere t#is QTQ.
=
'e$laring t(pe parameter at met#od level:
@e #ave to de+lare ,(st before ret(rn type.
Example:
p(bli+ ZTT void "et#odIne1BT t/7=JJvalid
p(bli+ ZT eEtends :("berT void "et#odIne2BT t/7=JJvalid
p(bli+ ZT eEtends :("berc'o"parableT void "et#odIne3BT t/7=JJvalid
p(bli+ ZT eEtends :("berc'o"parablecR(nnableT void "et#odIne4BT t/7=JJvalid
p(bli+ ZT eEtends :("bercT#readT void "et#odIneBT t/7=JJinvalid
!utput:
'o"pile ti"e error.
Test.,ava.7. interfa+e eEpe+ted #ere
p(bli+ ZT eEtends :("bercT#readT void "et#odIneBT t/7=JJvalid
p(bli+ ZT eEtends R(nnablec:("berT void "et#odIneBT t/7=JJinvalid
!utput:
'o"pile ti"e error.
Test.,ava.$. interfa+e eEpe+ted #ere
p(bli+ ZT eEtends R(nnablec:("berT void "et#odIneBT t/7=JJvalid
*ommuni$ation %it# non generi$ $ode:
To provide +o"patibility wit# old version s(n people +o"pra"i0ed t#e +on+ept of
!eneri+s in very few areaAs t#e followin! is one s(+# area.
Example:
i"port ,ava.(til.U9
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
ArrayListZCtrin!T l8new ArrayListZCtrin!TB/9
l.addBNAN/9
JJl.addB1)/9JJ'.<.+annot find sy"bol-"et#od addBint/
"et#odIneBl/9

4)$

l.addB1).5/9JJ'.<.+annot find sy"bol-"et#od addBdo(ble/
Cyste".o(t.printlnBl/9JJDA- 1)- 1).5- tr(e>
=
p(bli+ stati+ void "et#odIneBArrayList l/
7
l.addB1)/9
l.addB1).5/9
l.addBtr(e/9
=
=
/ote:
^eneri+s +on+ept is appli+able only at +o"pile ti"e- at r(nti"e t#ere is no s(+# type of
+on+ept. Sen+e t#e followin! de+larations are eV(al.
7rra(List lMne% 7rra(ListL2tringN:;E
7rra(List lMne% 7rra(ListLIntegerN:;E 7ll are eAual9
7rra(List lMne% 7rra(List:;E
Example 1:
i"port ,ava.(til.U9
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
ArrayList l8new ArrayListZCtrin!TB/9
l.addB1)/9
l.addB1).5/9
l.addBtr(e/9
Cyste".o(t.printlnBl/9JJ D1)- 1).5- tr(e>
=
=
Example 2:
i"port ,ava.(til.U9
+lass Test
7
p(bli+ void "et#odIneBArrayListZCtrin!T l/7=
p(bli+ void "et#odIneBArrayListZInte!erT l/7=
=
!utput:
'o"pile ti"e error.

4)&

Test.,ava.4. na"e +las#. "et#odIneB,ava.(til.ArrayListZ,ava.lan!.Ctrin!T/ and "e
t#odIneB,ava.(til.ArrayListZ,ava.lan!.Inte!erT/ #ave t#e sa"e eras(re
p(bli+ void "et#odIneBArrayListZCtrin!T l/7=
T#e followin! 2 de+larations are eV(al.
7rra(ListL2tringN l1Mne% 7rra(List:;E
7rra(ListL2tringN l2Mne% 7rra(ListL2tringN:;E
Hor t#ese ArrayList ob,e+ts we +an add only Ctrin! type of ob,e+ts.
Example:
l1.addBNAN/9JJvalid
l1.addB1)/9 JJinvalid

















Inner *lasses
Co"eti"es we +an de+lare a +lass inside anot#er +lass s(+# type of +lasses are +alled
inner +lasses.
'iagram:

41)


C(n people introd(+ed inner +lasses in 1.1 version as part of KEvent6andlingL to resolve
^;I b(!s.
6(t be+a(se of powerf(l feat(res and benefits of inner +lasses slowly t#e pro!ra""ers
starts (sin! in re!(lar +odin! also.
@it#o(t eEistin! one type of ob,e+t if t#ere is no +#an+e of eEistin! anot#er type of
ob,e+t t#en we s#o(ld !o for inner +lasses.
Example: @it#o(t eEistin! ;niversity ob,e+t t#ere is no +#an+e of eEistin! Depart"ent ob,e+t
#en+e we #ave to define Depart"ent +lass inside ;niversity +lass.
Example1:

Example 2: @it#o(t eEistin! 6an? ob,e+t t#ere is no +#an+e of eEistin! A++o(nt ob,e+t #en+e
we #ave to define A++o(nt +lass inside 6an? +lass.
Example:

Example 3: @it#o(t eEistin! %ap ob,e+t t#ere is no +#an+e of eEistin! <ntry ob,e+t #en+e <ntry
interfa+e is define inside %ap interfa+e.



Example:

411


'iagram:

/ote: T#e relations#ip between o(ter +lass and inner +lass is not IC4A relations#ip and it is Sas4
A relations#ip.
6ased on t#e p(rpose and position of de+laration all inner +lasses are divided into 4
types. T#ey are.
1; /ormal or Regular inner $lasses
2; =et#od Lo$al inner $lasses
3; 7non(mous inner $lasses
4; 2tati$ nested $lasses9
19 /ormal :or; Regular inner $lass: If we are de+larin! any na"ed +lass inside anot#er +lass
dire+tly wit#o(t stati+ "odifier s(+# type of inner +lasses are +alled nor"al or re!(lar inner
+lasses.
Example:
+lass I(ter
7
+lass Inner
7
=
=





!utput:

412


Example:
+lass I(ter
7
+lass Inner
7
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBNo(ter +lass "ain "et#odN/9
=
=
!utput:

Inside inner +lass we +anAt de+lare stati+ "e"bers. Sen+e it is not possible to de+lare
"ainB/ "et#od and we +anAt invo?e inner +lass dire+tly fro" t#e +o""end pro"pt.
Example:
+lass I(ter
7
+lass Inner
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBNinner +lass "ain "et#odN/9
=
=
=

413

!utput:
<.Ys+,pT,ava+ I(ter.,ava
I(ter.,ava.5. inner +lasses +annot #ave stati+ de+larations
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7$$essing inner $lass $ode from stati$ area of outer $lass:
Example:
+lass I(ter
7
+lass Inner
7
p(bli+ void "et#odIneB/7
Cyste".o(t.printlnBNinner +lass "et#odN/9
=
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7

=
=
7$$essing inner $lass $ode from instan$e area of outer $lass:
Example:
+lass I(ter
7
+lass Inner
7
p(bli+ void "et#odIneB/
7
Cyste".o(t.printlnBNinner +lass "et#odN/9
=
=
p(bli+ void "et#odTwoB/
7
Inner i8new InnerB/9

414

i."et#odIneB/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
I(ter o8new I(terB/9
o."et#odTwoB/9
=
=
!utput:
<.Ys+,pT,ava+ I(ter.,ava
<.Ys+,pT,ava I(ter
Inner +lass "et#od
7$$essing inner $lass $ode from outside of outer $lass:
Example:
+lass I(ter
7
+lass Inner
7
p(bli+ void "et#odIneB/
7
Cyste".o(t.printlnBNinner +lass "et#odN/9
=
=
=
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
new I(terB/.new InnerB/."et#odIneB/9
=
=
!utput:
Inner +lass "et#od






415


Hro" inner +lass we +an a++ess all "e"bers of o(ter +lass Bbot# stati+ and non4stati+-
private and non private "et#ods and variables/ dire+tly.
Example:
+lass I(ter
7
int E81)9
stati+ int y82)9
+lass Inner7
p(bli+ void "et#odIneB/
7
Cyste".o(t.printlnBE/9JJ1)
Cyste".o(t.printlnBy/9JJ2)
=
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
new I(terB/.new InnerB/."et#odIneB/9
=
=
@it#in t#e inner +lass Lt#isL always refers +(rrent inner +lass ob,e+t. To refer +(rrent
o(ter +lass ob,e+t we #ave to (se Kouter $lass name9t#isL.
Example:
+lass I(ter
7
int E81)9
+lass Inner
7
int E81))9
p(bli+ void "et#odIneB/

416

7
int E81)))9
Cyste".o(t.printlnBE/9JJ1)))
Cyste".o(t.printlnBt#is.E/9JJ1))
Cyste".o(t.printlnBI(ter.t#is.E/9JJ1)
=
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
new I(terB/.new InnerB/."et#odIneB/9
=
=
T#e appli+able "odifiers for o(ter +lasses are.
1; pu,li$
2; default
3; final
4; a,stra$t
5; stri$tfp
6(t for t#e inner +lasses in addition to t#is t#e followin! "odifiers also allowed.
'iagram:

=et#od lo$al inner $lasses:
Co"eti"es we +an de+lare a +lass inside a "et#od s(+# type of inner +lasses are +alled
"et#od lo+al inner +lasses.
T#e "ain ob,e+tive of "et#od lo+al inner +lass is to define "et#od spe+ifi+ repeatedly
reV(ired f(n+tionality.
@e +an a++ess "et#od lo+al inner +lass only wit#in t#e "et#od w#ere we de+lared it.
T#at is fro" o(tside of t#e "et#od we +anAt a++ess. As t#e s+ope of "et#od lo+al inner
+lasses is very less- t#is type of inner +lasses are "ost rarely (sed type of inner +lasses.
Example:
+lass Test
7
p(bli+ void "et#odIneB/

417

7
+lass Inner
7
p(bli+ void s("Bint i-int ,/
7
Cyste".o(t.printlnBNT#e s(".NFBiF,//9
=
=
Inner i8new InnerB/9
i.s("B1)-2)/9
9999999999999
i.s("B1))-2))/9
999999999999999
i.s("B1)))-2)))/9
99999999999999999
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
new TestB/."et#odIneB/9
=
=
!utput:
T#e s(". 3)
T#e s(". 3))
T#e s(". 3)))
If we are de+larin! inner +lass inside instan+e "et#od t#en we +an a++ess bot# stati+
and non stati+ "e"bers of o(ter +lass dire+tly.
6(t if we are de+larin! inner +lass inside stati+ "et#od t#en we +an a++ess only stati+
"e"bers of o(ter +lass dire+tly and we +anAt a++ess instan+e "e"bers dire+tly.
Example:
+lass Test
7
int E81)9
stati+ int y82)9
p(bli+ void "et#odIneB/
7
+lass Inner
7

41$

p(bli+ void "et#odTwoB/
7
Cyste".o(t.printlnBE/9JJ1)
Cyste".o(t.printlnBy/9JJ2)
=
=
Inner i8new InnerB/9
i."et#odTwoB/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
new TestB/."et#odIneB/9
=
=
If we de+lare "et#odIneB/ "et#od as stati+ t#en we will !et +o"pile ti"e error sayin!
Knon4stati+ variable E +annot be referen+ed fro" a stati+ +onteEtL.
Hro" "et#od lo+al inner +lass we +anAt a++ess lo+al variables of t#e "et#od in w#i+# we
de+lared it. 6(t if t#at lo+al variable is de+lared as final t#en we wonAt !et any +o"pile
ti"e error.
Example:
+lass Test
7
int E81)9
p(bli+ void "et#odIneB/
7
int y82)9
+lass Inner
7
p(bli+ void "et#odTwoB/
7
Cyste".o(t.printlnBE/9JJ1)
Cyste".o(t.printlnBy/9 JJ*9E: lo+al variable y is a++essed fro"
wit#in inner +lass9 needs to be de+lared final.
=
=
Inner i8new InnerB/9
i."et#odTwoB/9
=

41&

p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
new TestB/."et#odIneB/9
=
=
If we de+lared y as final t#en we wonAt !et any +o"pile ti"e error.
'onsider t#e followin! de+laration.
+lass Test
7
int i81)9
stati+ int ,82)9
p(bli+ void "et#odIneB/
7
int ?83)9
final int l84)9
+lass Inner
7
p(bli+ void "et#odTwoB/
7
Cyste".o(t.printlnBi/9
Cyste".o(t.printlnB,/9 line 1
Cyste".o(t.printlnB?/9
Cyste".o(t.printlnBl/9
=
=
Inner i8new InnerB/9
i."et#odTwoB/9
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
new TestB/."et#odIneB/9
=
=
7t line 1 %#i$# of t#e follo%ing varia,les %e $an a$$ess&

If %e de$lare met#od!ne:; met#od as stati$ t#en %#i$# varia,les %e $an a$$ess at line
1&


42)


If we de+lare "et#odTwoB/ as stati+ t#en we will !et +o"pile ti"e error be+a(se we
+anAt de+lare stati+ "e"bers inside inner +lasses.
T#e only appli+able "odifiers for "et#od lo+al inner +lasses are.
1; final
2; a,stra$t
3; stri$tfp
6y "ista?e if we are de+larin! any ot#er "odifier we will !et +o"pile ti"e error.
7non(mous inner $lasses:
Co"eti"es we +an de+lare inner +lass wit#o(t na"e s(+# type of inner +lasses are
+alled anony"o(s inner +lasses.
T#e "ain ob,e+tive of anony"o(s inner +lasses is Kjust for instant useL.
T#ere are 3 types of anony"o(s inner +lasses
1; 7non(mous inner $lass t#at extends a $lass9
2; 7non(mous inner $lass t#at implements an interfa$e9
3; 7non(mous inner $lass t#at defined inside met#od arguments9
7non(mous inner $lass t#at extends a $lass:
+lass \op'orn
7
p(bli+ void tasteB/
7
Cyste".o(t.printlnBNspi+yN/9
=
=
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\op'orn p8new \op'ornB/
7
p(bli+ void tasteB/
7
Cyste".o(t.printlnBNsaltyN/9
=
=E
p.tasteB/9JJsalty
\op'orn p18new \op'ornB/9

421

p1.tasteB/9JJspi+y
=
=
7nal(sis:
1; 3op*orn pMne% 3op*orn:;E
@e are ,(st +reatin! a \op'orn ob,e+t.
2; 3op*orn pMne% 3op*orn:;
F
YE
@e are +reatin! +#ild +lass wit#o(t na"e for t#e \op'orn +lass and for t#at +#ild +lass
we are +reatin! an ob,e+t wit# \arent \op'orn referen+e.
3; 3op*orn pMne% 3op*orn:;
F
pu,li$ void taste:;
F
2(stem9out9println:]salt(];E
Y
YE
1/ @e are +reatin! +#ild +lass for \op'orn wit#o(t na"e.
2/ @e are overridin! tasteB/ "et#od.
3/ @e are +reatin! ob,e+t for t#at +#ild +lass wit# parent referen+e.
/ote: Inside Anony"o(s inner +lasses we +an ta?e or de+lare new "et#ods b(t o(tside of
anony"o(s inner +lasses we +anAt +all t#ese "et#ods dire+tly be+a(se we are dependin! on
parent referen+e.Dparent referen+e +an be (sed to #old +#ild +lass ob,e+t b(t by (sin! t#at
referen+e we +anAt +all +#ild spe+ifi+ "et#ods>. T#ese "et#ods ,(st for internal p(rpose only.
Example 1:
+lass \op'orn
7
p(bli+ void tasteB/
7
Cyste".o(t.printlnBNspi+yN/9
=
=
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\op'orn p8new \op'ornB/

422

7
p(bli+ void tasteB/
7
"et#odIneB/9JJvalid +allBinternal p(rpose/
Cyste".o(t.printlnBNsaltyN/9
=
p(bli+ void "et#odIneB/
7
Cyste".o(t.printlnBN+#ild spe+ifi+ "et#odN/9
=
=9
JJp."et#odIneB/9JJ#ere we +an not +allBo(tside inner +lass/
p.tasteB/9JJsalty
\op'orn p18new \op'ornB/9
p1.tasteB/9JJspi+y
=
=
!utput:
'#ild spe+ifi+ "et#od
Calty
Cpi+y
Example 2:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
T#read t8new T#readB/
7
p(bli+ void r(nB/
7
forBint i8)9iZ1)9iFF/
7
Cyste".o(t.printlnBN+#ild t#readN/9
=
=
=9
t.startB/9
forBint i8)9iZ1)9iFF/

423

7
Cyste".o(t.printlnBN"ain t#readN/9
=
=
=
7non(mous Inner *lass t#at implements an interfa$e:
Example:
+lass Inner'lassesDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
R(nnable r8new R(nnableB/JJ#ere we are not +reatin! for R(nnable interfa+e-
we are +reatin! i"ple"ents +lass ob,e+t.
7
p(bli+ void r(nB/
7
forBint i8)9iZ1)9iFF/
7
Cyste".o(t.printlnBN'#ild t#readN/9
=
=
=9
T#read t8new T#readBr/9
t.startB/9
forBint i8)9iZ1)9iFF/
7
Cyste".o(t.printlnBN%ain t#readN/9
=
=
=
7non(mous Inner *lass t#at define inside met#od arguments:
Example:
+lass Test
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
new T#readB
new R(nnableB/

424

7
p(bli+ void r(nB/
7
forBint i8)9iZ1)9iFF/
7
Cyste".o(t.printlnBN+#ild t#readN/9
=
=
=/.startB/9
forBint i8)9iZ1)9iFF/
7
Cyste".o(t.printlnBN"ain t#readN/9
=
=
=
!utput:
T#is o(tp(t belon!s to eEa"ple 2- anony"o(s inner +lass t#at i"ple"ents an interfa+e
eEa"ple and anony"o(s inner +lass t#at define inside "et#od ar!("ents eEa"ple.
%ain t#read
%ain t#read
%ain t#read
%ain t#read
%ain t#read
%ain t#read
%ain t#read
%ain t#read
%ain t#read
%ain t#read
'#ild t#read
'#ild t#read
'#ild t#read
'#ild t#read
'#ild t#read
'#ild t#read
'#ild t#read
'#ild t#read
'#ild t#read
'#ild t#read

425

'ifferen$e ,et%een general $lass and anon(mous inner $lasses:
General *lass 7non(mous Inner 'lass
1/ A !eneral +lass +an eEtends only one
+lass at a ti"e.
1/ If+o(r+e anony"o(s inner +lass also
+an eEtends only one +lass at a ti"e.
2/ A !eneral +lass +an i"ple"ent any no.
If interfa+es at a ti"e.
2/ 6(t anony"o(s inner +lass +an
i"ple"ent only one interfa+e at a
ti"e.
3/ A !eneral +lass +an eEtends a +lass and
+an i"ple"ent an interfa+e
si"(ltaneo(sly.
3/ 6(t anony"o(s inner +lass +an eEtends
a +lass or +an i"ple"ents an interfa+e
b(t not bot# si"(ltaneo(sly.
2tati$ nested $lasses:
Co"eti"es we +an de+lare inner +lasses wit# stati+ "odifier s(+# type of inner +lasses
are +alled stati+ nested +lasses.
In t#e +ase of nor"al or re!(lar inner +lasses wit#o(t eEistin! o(ter +lass ob,e+t t#ere is
no +#an+e of eEistin! inner +lass ob,e+t.
6(t in t#e +ase of stati+ nested +lass wit#o(t eEistin! o(ter +lass ob,e+t t#ere "ay be a
+#an+e of eEistin! stati+ nested +lass ob,e+t.
Example:
+lass Test
7
stati+ +lass :ested
7
p(bli+ void "et#odIneB/
7
Cyste".o(t.printlnBNnested +lass "et#odN/9
=
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Test.:ested t8new Test.:estedB/9
t."et#odIneB/9
=
=

Inside stati+ nested +lasses we +an de+lare stati+ "e"bers in+l(din! "ainB/ "et#od
also. Sen+e it is possible to invo?e stati+ nested +lass dire+tly fro" t#e +o""and
pro"pt.

Example:

426

+lass Test
7
stati+ +lass :ested
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBNnested +lass "ain "et#odN/9
=
=
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Cyste".o(t.printlnBNo(ter +lass "ain "et#odN/9
=
=
!utput:
<.YC'*\T,ava+ Test.,ava
<.YC'*\T,ava Test
I(ter +lass "ain "et#od
<.YC'*\T,ava Test3:ested
:ested +lass "ain "et#od
Hro" t#e nor"al inner +lass we +an a++ess bot# stati+ and non stati+ "e"bers of o(ter
+lass b(t fro" stati+ nested +lass we +an a++ess only stati+ "e"bers of o(ter +lass.
Example:
+lass Test
7
int E81)9
stati+ int y82)9
stati+ +lass :ested
7
p(bli+ void "et#odIneB/
7
Cyste".o(t.printlnBE/9JJ'.<.non4stati+ variable E +annot be referen+ed
fro" a stati+ +onteEt
Cyste".o(t.printlnBy/9
=
=
=
*ompression ,et%een normal or regular $lass and stati$ nested $lass&

427

/ormal Wregular inner $lass 2tati$ nested $lass
1/ @it#o(t eEistin! o(ter +lass ob,e+t
t#ere is no +#an+e of eEistin! inner
+lass ob,e+t. T#at is inner +lass ob,e+t is
always asso+iated wit# o(ter +lass
ob,e+t.
1/ @it#o(t eEistin! o(ter +lass ob,e+t
t#ere "ay be a +#an+e of eEistin! stati+
nested +lass ob,e+t. T#at is stati+
nested +lass ob,e+t is not asso+iated
wit# o(ter +lass ob,e+t.
2/ Inside nor"al or re!(lar inner +lass we
+anAt de+lare stati+ "e"bers.
2/ Inside stati+ nested +lass we +an
de+lare stati+ "e"bers.
3/ Inside nor"al inner +lass we +anAt
de+lare "ainB/ "et#od and #en+e we
+anAt invo?e re!(lar inner +lass dire+tly
fro" t#e +o""and pro"pt.
3/ Inside stati+ nested +lass we +an
de+lare "ainB/ "et#od and #en+e we
+an invo?e stati+ nested +lass dire+tly
fro" t#e +o""and pro"pt.
4/ Hro" t#e nor"al or re!(lar inner +lass
we +an a++ess bot# stati+ and non
stati+ "e"bers of o(ter +lass dire+tly.
4/ Hro" stati+ nested +lass we +an a++ess
only stati+ "e"bers of o(ter +lass
dire+tly.





















42$

Internationali4ation
T#e pro+ess of desi!nin! a web appli+ation s(+# t#at it s(pports vario(s +o(ntries-
vario(s lan!(a!es wit#o(t perfor"in! any +#an!es in t#e appli+ation is +alled
Internationali0ation.
@e +an i"ple"ent Internationali0ation by (sin! t#e followin! +lasses. T#ey are.
1/ Lo+ale
2/ :("berHor"at
3/ DateHor"at
19 Lo$ale: A Lo+ale ob,e+t +an be (sed to represent a !eo!rap#i+ B+o(ntry/ lo+ation Bor/
lan!(a!e.
Lo+ale +lass present in java9util pa$+age.
It is a final +lass and dire+t +#ild +lass of Ib,e+t i"ple"ents 'loneable and Ceriali0able
Interfa+es.
6o% to $reate a Lo$ale o,je$t:
@e +an +reate a Lo+ale ob,e+t by (sin! t#e followin! +onstr(+tors of Lo+ale +lass.
1/ Lo+ale l8new Lo+aleBCtrin! lan!(a!e/9
2/ Lo+ale l8new Lo+aleBCtrin! lan!(a!e-Ctrin! +o(ntry/9
Lo+ale +lass already defines so"e predefined Lo+ale +onstants. @e +an (se t#ese
+onstants dire+tly.
Example:
Lo+ale. ;G
Lo+ale. ;C
Lo+ale. ITALa
Lo+ale. 'SI:A
Important met#ods of Lo$ale $lass:
1/ p(bli+ stati+ Lo+ale !etDefa(ltB/
2/ p(bli+ stati+ void setDefa(ltBLo+ale l/
3/ p(bli+ Ctrin! !etLan!(a!eB/
4/ p(bli+ Ctrin! !etDisplayLan!(a!eBLo+ale l/
5/ p(bli+ Ctrin! !et'o(ntryB/
6/ p(bli+ Ctrin! !etDisplay'o(ntryBLo+ale l/
7/ p(bli+ stati+ Ctrin!D> !etICILan!(a!esB/
$/ p(bli+ stati+ Ctrin!D> !etICI'o(ntriesB/
&/ p(bli+ stati+ Lo+aleD> !etAvailableLo+alesB/
Example for Lo$ale:
i"port ,ava.(til.U9
+lass Lo+aleDe"o7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Lo+ale l18Lo+ale.!etDefa(ltB/9
JJCyste".o(t.printlnBl1.!et'o(ntryB/FN.....NFl1.!etLan!(a!eB//9

42&

JJCyste".o(t.printlnBl1.!etDisplay'o(ntryB/FN.....NFl1.!etDisplayLan!(a!eB//9
Lo+ale l28new Lo+aleBNpaN-NI:N/9
Lo+ale.setDefa(ltBl2/9
Ctrin!D> s38Lo+ale.!etICILan!(a!esB/9
forBCtrin! s4.s3/
7
JJCyste".o(t.printBNICI lan!(a!e is .N/9
JJCyste".o(t.printlnBs4/9
=
Ctrin!D> s48Lo+ale.!etICI'o(ntriesB/9
forBCtrin! s5.s4/
7
Cyste".o(t.printBNICI 'o(ntry is.N/9
Cyste".o(t.printlnBs5/9
=
Lo+aleD> s8Lo+ale.!etAvailableLo+alesB/9
forBLo+ale s1.s/
7
JJCyste".o(t.printBNAvailable lo+ales is.N/9
JJCyste".o(t.printlnBs1.!etDisplay'o(ntryB/FN......NFs1.!etDisplayLan!(a!eB//9
===
/um,erFormat:
ario(s +o(ntries follow vario(s styles to represent n("ber.
Example:
1-23-456.7$&444444444444I:DIA
123-456.7$&4444444444444;C
123.456-7$&4444444444444ITALa
6y (sin! :("berHor"at +lass we +an for"at a n("ber a++ordin! to a parti+(lar Lo+ale.
:("berHor"at +lass present in ,ava.TeEt pa+?a!e and it is an abstra+t +lass.
Sen+e we +anAt +reate an ob,e+t by (sin! +onstr(+tor.
:("berHor"at nf8new :("berHor"atB/9 44444444invalid
Getting /um,erFormat o,je$t for t#e default Lo$ale:
:("berHor"at +lass defines t#e followin! "et#ods for t#is.

Getting /um,erFormat o,je$t for t#e spe$ifi$ Lo$ale:
T#e "et#ods are eEa+tly sa"e b(t we #ave to pass t#e +orrespondin! Lo+ale ob,e+t as
ar!("ent.



43)

Example: p(bli+ stati+ :("berHor"at !et:("berInstan+eBLo+ale l/9
In+e we !ot :("berHor"at ob,e+t we +an +all t#e followin! "et#ods to for"at and
parse n("bers.
1/ p(bli+ Ctrin! for"atBlon! l/9
2/ p(bli+ Ctrin! for"atBdo(ble d/9
To +onvert a n("ber fro" ,ava for" to Lo+ale spe+ifi+ for".
1/ p(bli+ :("ber parseBCtrin! so(r+e/t#rows \arse<E+eption
To +onvert fro" Lo+ale spe+ifi+ Ctrin! for" to ,ava spe+ifi+ for".
Example:
i"port ,ava.(til.U9
i"port ,ava.teEt.U9
+lass :("berHor"atDe"o
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do(ble d8123456.7$&9
:("berHor"at nf8:("berHor"at.!etInstan+eBLo+ale.ITALa/9
Cyste".o(t.printlnBNITALa for" is .NFnf.for"atBd//9
=
=
!utput:
ITALa for" is .123.456-7$&
ReAuirement: @rite a pro!ra" to print a ,ava n("ber in I:DIA- ;G- ;C and ITALa +(rren+y
for"ats.
3rogram:
i"port ,ava.(til.U9
i"port ,ava.teEt.U9
+lass :("berHor"atDe"o
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
do(ble d8123456.7$&9
Lo+ale I:DIA8new Lo+aleBNpaN-NI:N/9
:("berHor"at nf8:("berHor"at.!et'(rren+yInstan+eBI:DIA/9
Cyste".o(t.printlnBNI:DIA notation is .NFnf.for"atBd//9
:("berHor"at nf18:("berHor"at.!et'(rren+yInstan+eBLo+ale.;G/9
Cyste".o(t.printlnBN;G notation is .NFnf1.for"atBd//9
:("berHor"at nf28:("berHor"at.!et'(rren+yInstan+eBLo+ale.;C/9
Cyste".o(t.printlnBN;C notation is .NFnf2.for"atBd//9
:("berHor"at nf38:("berHor"at.!et'(rren+yInstan+eBLo+ale.ITALa/9
Cyste".o(t.printlnBNITALa notation is .NFnf3.for"atBd//9
==
!utput:
I:DIA notation is. I:R 123-456.7&
;G notation is. f123-456.7&
;C notation is. 3123-456.7&

431

ITALa notation is. g 123.456-7&
2etting =aximumH =inimumH Fra$tion and Integer digits:
:("berHor"at +lass defines t#e followin! "et#ods for t#is p(rpose.
1/ p(bli+ void set=aximumFra$tion'igitsBint n/9
2/ p(bli+ void set=inimumFra$tion'igitsBint n/9
3/ p(bli+ void set=aximumInteger'igitsBint n/9
4/ p(bli+ void set=inimumInteger'igitsBint n/9
Example:
i"port ,ava.teEt.U9
p(bli+ +lass :("berHor"at<Ea"ple
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/7
:("berHor"at nf8:("berHor"at.!etInstan+eB/9
nf.set%aEi"("Hra+tionDi!itsB3/9
Cyste".o(t.printlnBnf.for"atB123.4//9
Cyste".o(t.printlnBnf.for"atB123.4567//9
nf.set%ini"("Hra+tionDi!itsB3/9
Cyste".o(t.printlnBnf.for"atB123.4//9
Cyste".o(t.printlnBnf.for"atB123.4567//9
nf.set%aEi"("Inte!erDi!itsB3/9
Cyste".o(t.printlnBnf.for"atB1.234//9
Cyste".o(t.printlnBnf.for"atB123456.7$&//9
nf.set%ini"("Inte!erDi!itsB3/9
Cyste".o(t.printlnBnf.for"atB1.234//9
Cyste".o(t.printlnBnf.for"atB123456.7$&//9
==
!utput:
123.4
123.457
123.4))
123.457
1.234
456.7$&
))1.234
456.7$&
'ateFormat: ario(s +o(ntries follow vario(s styles to represent Date. @e +an for"at t#e date
a++ordin! to a parti+(lar lo+ale by (sin! DateHor"at +lass.
DateHor"at +lass present in ,ava.teEt pa+?a!e and it is an abstra+t +lass.
Getting 'ateFormat o,je$t for default Lo$ale:
DateHor"at +lass defines t#e followin! "et#ods for t#is p(rpose.





432



Getting 'ateFormat o,je$t for t#e spe$ifi$ Lo$ale:
1/ p(bli+ stati+ DateHor"at !etDateInstan+eBint style- Lo+ale l/9
In+e we !ot DateHor"at ob,e+t we +an for"at and parse Date by (sin! t#e followin!
"et#ods.
1/ p(bli+ Ctrin! for"atBDate date/9
To +onvert t#e date fro" ,ava for" to lo+ale spe+ifi+ strin! for".
1/ p(bli+ Date parseBCtrin! so(r+e/t#rows \arse<E+eption
To +onvert t#e date fro" lo+ale spe+ifi+ for" to ,ava for".
ReAuirement: @rite a pro!ra" to represent +(rrent syste" date in all possible styles of (s
for"at.
3rogram:
i"port ,ava.teEt.U9
i"port ,ava.(til.U9
p(bli+ +lass DateHor"atDe"o
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnBNf(ll for" is .NFDateHor"at.!etDateInstan+eB)/.for"atBnew DateB///9
Cyste".o(t.printlnBNlon! for" is .NFDateHor"at.!etDateInstan+eB1/.for"atBnew DateB///9
Cyste".o(t.printlnBN"edi(" for" is .NFDateHor"at.!etDateInstan+eB2/.for"atBnew DateB///9
Cyste".o(t.printlnBNs#ort for" is .NFDateHor"at.!etDateInstan+eB3/.for"atBnew DateB///9
=
=
!utput:
H(ll for" is. @ednesday- *(ly 2)- 2)11
Lon! for" is. *(ly 2)- 2)11
%edi(" for" is. *(l 2)- 2)11
C#ort for" is. 7J2)J11
/ote: T#e defa(lt style is "edi(" style.
ReAuirement: @rite a pro!ra" to represent +(rrent syste" date in ;G- ;C and ITALa styles.
3rogram:
i"port ,ava.teEt.U9
i"port ,ava.(til.U9
p(bli+ +lass DateHor"atDe"o
7

433

p(bli+ stati+ void "ainBCtrin! ar!sD>/7
DateHor"at ;G8DateHor"at.!etDateInstan+eB)-Lo+ale.;G/9
DateHor"at ;C8DateHor"at.!etDateInstan+eB)-Lo+ale.;C/9
DateHor"at ITALa8DateHor"at.!etDateInstan+eB)-Lo+ale.ITALa/9
Cyste".o(t.printlnBN;G style is .NF;G.for"atBnew DateB///9
Cyste".o(t.printlnBN;C style is .NF;C.for"atBnew DateB///9
Cyste".o(t.printlnBNITALa style is .NFITALa.for"atBnew DateB///9
=
=
!utput:
;G style is. @ednesday- 2) *(ly 2)11
;C style is. @ednesday- *(ly 2)- 2)11
ITALa style is. "er+oledh 2) l(!lio 2)11
Getting 'ateFormat o,je$t to get ,ot# date and time:
DateHor"at +lass defines t#e followin! "et#ods for t#is.

Example:
i"port ,ava.teEt.U9
i"port ,ava.(til.U9
p(bli+ +lass DateHor"atDe"o
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
DateHor"at ITALa8DateHor"at.!etDateTi"eInstan+eB)-)-Lo+ale.ITALa/9
Cyste".o(t.printlnBNITALa style is.NFITALa.for"atBnew DateB///9
=
=
!utput:
ITALa style is. "er+oledh 2) l(!lio 2)11 23.21.3) ICT








434

'evelopment
0ava$: we +an (se *ava+ to +o"pile a sin!le or !ro(p of K.,ava filesL.
2(ntax.

0ava: we +an (se ,ava +o""and to r(n a sin!le K.+lass fileL.
2(ntax:

*lasspat#: 'lass pat# des+ribes t#e lo+ation w#ere t#e reV(ired K.+lass filesL are available. @e
+an set t#e +lass pat# in t#e followin! 3 ways.
1/ \er"anently by (sin! environ"ent variable K+lasspat#L. T#is +lass pat# will be
preserved after syste" restart also.
2/ Te"porary for a parti+(lar +o""and pro"pt level by (sin! KsetL +o""and.
Example:

In+e if yo( +lose t#e +o""and pro"pt a(to"ati+ally t#is +lass pat# will be lost.
3/ @e +an set t#e +lass pat# for a parti+(lar +o""and level by (sin! KM+pL Bor/ KM+lass
pat#L. T#is +lass pat# is appli+able only for t#at +o""and eEe+(tion. After eEe+(tin!
t#e +o""and t#is +lasspat# will be lost.
A"on! t#e 3 ways of settin! t#e +lass pat# t#e "ost +o""on way is settin! +lass pat#
at +o""and level by (sin! KM+pL.
Example 1:
+lass Rain
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7

435

Cyste".o(t.printlnBNRainin! of ,obs t#ese daysN/9
=
=
7nal(sis:

Example 2:

7nal(sis:


436

Example 3:
7nal(sis:

/ote: if any folder str(+t(re +reated be+a(se of pa+?a!e state"ent. It s#o(ld be resolved by
i"port state"ent only and t#e lo+ation of base pa+?a!e s#o(ld be "a?e it available in +lass
pat#.
/ote: in +lasspat# t#e order of lo+ations is very i"portant and it s#o(ld be fro" left to ri!#t.


437

Example 4:
7nal(sis:

0ar file: If several dependent +lasses present t#en it is never re+o""ended to set t#e +lasspat#
individ(al for every +o"ponent. @e #ave to !ro(p all t#ese K.+lass filesL into a sin!le ,ar file and
we #ave to "a?e t#at ,ar file available to t#e +lasspat#.
Example: All reV(ired +lasses to develop a Cervlet are !ro(ped into a sin!le ,ar file BCervlet4
api.,ar/ #en+e w#ile +o"pilin! Cervlet +lasses we #ave to "a?e t#is ,ar file available in t#e
+lasspat#.
@#at is t#e differen+e between *ar- @ar and <arW
0ar :java ar$#ive;: Represents a !ro(p of K.+lass filesL.
"ar :%e, ar$#ive;: Represents a web appli+ation w#i+# "ay +ontains Cervlets- *C\- ST%L
pa!es- *avaC+ript files et+.
Ear :Enterprise ar$#ive;: it represents an enterprise appli+ation w#i+# "ay +ontain Cervlets-
*C\- <*6AC- *%C +o"ponent et+.
In !enerally an ear file +onsists of a !ro(p of war files and ,ar files.
<ar8warF ,ar
-arious *ommands:
8o $reate a jar file:
D.Y<n("T,ar 4+vf b#as?ar.,ar 6eer.+lass Test.+lass P.+lass
D.Y<n("T,ar 4+vf b#as?ar.,ar U.+lass
8o extra$t a jar file:
D.Y<n("T,ar 4Evf b#as?ar.,ar
8o displa( ta,le of $ontents of a jar file:
D.Y<n("T,ar 4tvf b#as?ar.,ar

43$

Example 5:
p(bli+ +lass 6#as?ar'olorH(l'al+7
p(bli+ stati+ int addBint E-int y/7
ret(rn EUy9
=
p(bli+ stati+ int "(ltiplyBint E-int y/7
ret(rn 2UEUy9
==
7nal(sis:
'.YT,ava+ 6#as?ar'olorH(l'al+.,ava
'.YT,ar 4+vf b#as?ar.,ar 6#as?ar'olorH(l'al+.+lass
Example 6:
+lass 'lient7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnB6#as?ar'olorH(l'al+.addB1)-2)//9
Cyste".o(t.printlnB6#as?ar'olorH(l'al+."(ltiplyB1)-2)//9
==
7nal(sis:

/ote: @#enever we are pla+in! ,ar file in t#e +lasspat# +o"p(lsory we #ave to spe+ify t#e
na"e of t#e ,ar file also and ,(st lo+ation is not eno(!#.
2(stem properties:
Hor every syste" so"e persisten+e infor"ation is available in t#e for" of syste"
properties. T#ese "ay in+l(de na"e of t#e os- ,ava version- vendor of ,v" et+.
@e +an !et syste" properties by (sin! !et\ropertiesB/ "et#od of syste" +lass. T#e
followin! pro!ra" displays all t#e syste" properties.
Example :
i"port ,ava.(til.U9
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
JJ\roperties is a +lass in (til pa+?a!e.
JJ#ere !et\ropertesB/ "et#od ret(rns t#e \roperties ob,e+t.
\roperties p8Cyste".!et\ropertiesB/9
p.listBCyste".o(t/9
=

43&

=
6o% to set s(stem propert( from t#e $ommand prompt:
@e +an set syste" property fro" t#e +o""and pro"pt by (sin! MD option.
*ommand:

"#at is t#e differen$e ,et%een pat# and $lasspat#&
3at#: @e +an (se Kpat# variableL to spe+ify t#e lo+ation w#ere reV(ired binary eEe+(tables are
available.
If we are not settin! pat# t#en K,avaL and K*ava+L +o""ands wonAt wor?.
*lasspat#: @e +an (se K+lasspat# variableL to des+ribe lo+ation w#ere reV(ired +lass files are
available.
If we are not settin! +lasspat# t#en o(r pro!ra" wonAt +o"pile and r(n.
"#at is t#e differen$e ,et%een 0')H 0RE and 0-=&
0') :java development +it;: To develop and r(n ,ava appli+ations t#e reV(ired environ"ent is
*DG.
0RE :java runtime environment;: To r(n ,ava appli+ation t#e reV(ired environ"ent is *R<.
0-= :java virtual ma$#ine;: To eEe+(te ,ava appli+ation t#e reV(ired virt(al "a+#ine is *%.
'iagram:

*DG8*R<FDevelop"ent Tools.
*R<8*%FLibraries.
*R< is t#e part of *DG.
*v" is t#e part of *R<.
:ote. At +lient side *R< is reV(ired and at developers side *DG is reV(ired.
2#ort$ut %a( to pla$e a jar files:
If we are pla+in! ,ar file in t#e followin! lo+ation t#en it is not reV(ired to set +lasspat#
eEpli+itly.



44)

'iagram:


















441

E/.=
@e +an (se en(" to define a !ro(p of na"ed +onstants.
Example 1:
en(" %ont#
7
*A:-H<6-%AR-D<'9
=
Example 2:
en(" 6eer
7
GH-GI-R'-HI9
=
<n(" +on+ept introd(+ed in 1.5 versions.
@#en +o"pared wit# old lan!(a!es en(" ,avaAs en(" is "ore powerf(l.
6y (sin! en(" we +an define o(r own data types w#i+# are also +o"e en("erated data
types.
Internal implementation of enum:
Internally en("As are i"ple"ented by (sin! +lass +on+ept. <very en(" +onstant is a
referen+e variable to t#at en(" type ob,e+t.
<very en(" +onstant is i"pli+itly pu,li$ stati$ final always.
Example 3:

'iagram:

'e$laration and usage of enum:
Example 4:
en(" 6eer
7
GH-GI-R'-HI9JJ#ere se"i+olon is optional.
=
+lass Test
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7

442

6eer b186eer.GH9
Cyste".o(t.printlnBb1/9
=
=
!utput:
D.Y<n("T,ava Test
GH
:ote. <very en(" +onstant internally stati+ #en+e we +an a++ess by (sin! Ken(" na"eL.
Enum vs s%it$# statement:
;ntil 1.4 versions t#e allowed types for t#e swit+# state"ent are byte- s#ort- +#ar int.
6(t fro" 1.5 version onwards in addition to t#is t#e +orrespondin! wrapper +lasses and
en(" type also allowed. T#at is fro" 1.5 version onwards we +an (se en(" type as
ar!("ent to swit+# state"ent.
'iagram:

Example:
en(" 6eer
7
GH-GI-R'-HI9
=
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
6eer b186eer.R'9
swit+#Bb1/7
+ase GH.
Cyste".o(t.printlnBNit is +#ildrens brandN/9
brea?9
+ase GI.
Cyste".o(t.printlnBNit is too liteN/9
brea?9
+ase R'.

443

Cyste".o(t.printlnBNit is too #otN/9
brea?9
+ase HI.
Cyste".o(t.printlnBNb(y one !et oneN/9
brea?9
defa(lt.
Cyste".o(t.printlnBNot#er brands are not !oodN/9
=
==
!utput:
D.Y<n("T,ava Test
It is too #ot
If we are passin! en(" type as ar!("ent to swit+# state"ent t#en every +ase label
s#o(ld be a valid en(" +onstant ot#erwise we will !et +o"pile ti"e error.
Example:
en(" 6eer
7
GH-GI-R'-HI9
=
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
6eer b186eer.R'9
swit+#Bb1/7
+ase GH.
+ase R'.
+ase GALaA:I.
===
!utput:
'o"pile ti"e error.
D.Y<n("T,ava+ Test.,ava
Test.,ava.11. (nV(alified en("eration +onstant na"e reV(ired
+ase GALaA:I.
@e +an de+lare en(" eit#er o(tside t#e +lass or wit#in t#e +lass b(t not inside a
"et#od. If we de+lare en(" o(tside t#e +lass t#e allowed "odifiers are.
1/ p(bli+
2/ defa(lt
3/ stri+tfp.
If we de+lare en(" inside a +lass t#en t#e allowed "odifiers are.

444

1/ p(bli+ private
2/ defa(lt F prote+ted
3/ stri+tfp stati+
Example:

Enum vs in#eritan$e:
<very en(" in ,ava is t#e dire+t +#ild +lass of ,ava.lan!.<n(" +lass #en+e it is not
possible to eEtends any ot#er en(".
<very en(" is i"pli+itly final #en+e we +anAt +reate +#ild en(".
6e+a(se of above reasons we +an +on+l(de in#eritan+e +on+ept is not appli+able for
en("As eEpli+itly.
6(t en(" +an i"ple"ent any no. If interfa+es si"(ltaneo(sly.
Example:

Example:

0ava9lang9Enum: <very en(" in ,ava is t#e dire+t +#ild +lass of ,ava.lan!.<n(". T#e power of
en(" is in#eritin! fro" t#is +lass only.

445

It is abstra+t +lass and it is dire+t +#ild +lass of KIb,e+t +lassL it i"ple"ents 2eriali4a,le
and *ompara,le.
values:; met#od: <very en(" i"pli+itly +ontains a stati+ val(esB/ "et#od to list all +onstants of
en(".
Example: 6eerD> b86eer.val(esB/9
ordinal:; met#od: @it#in en(" t#e order of +onstants is i"portant we +an spe+ify by its ordinal
val(e.
@e +an find ordinal val(eBindeE val(e/ of en(" +onstant by (sin! ordinalB/ "et#od.
Example: p(bli+ int ordinalB/9
Example:
en(" 6eer
7
GH-GI-R'-HI9
=
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
6eerD> b86eer.val(esB/9
forB6eer b1.b/JJt#is is for<a+# loop.
7
Cyste".o(t.printlnBb1FN.......NFb1.ordinalB//9
===
!utput:
D.Y<n("T,ava Test
GH.......)
GI.......1
R'.......2
HI.......3
2pe$ialt( of java enum: @#en +o"pared wit# old lan!(a!es en(" ,avaAs en(" is "ore
powerf(l be+a(se in addition to +onstants we +an ta?e nor"al variables- +onstr(+tors- "et#ods
et+ w#i+# "ay not possible in old lan!(a!es.
Inside en(" we +an de+lare "ain "et#od and even we +an invo?e en(" dire+tly fro"
t#e +o""and pro"pt.
Example:
en(" His#7
^ILD-A\ILI-CTAR9
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnBNen(" "ainB/ "et#od +alledN/9
==

446

!utput:
D.Y<n("T,ava His#
en(" "ainB/ "et#od +alled
In addition to +onstants if we are ta?in! any eEtra "e"bers li?e "et#ods t#en t#e list of
+onstants s#o(ld be in t#e 1
st
line and s#o(ld ends wit# se"i+olon.
If we are ta?in! any eEtra "e"ber t#en en(" s#o(ld +ontain at least one +onstant. Any
way an e"pty en(" is always valid.
Example:


Enum vs $onstru$tor: <n(" +an +ontain +onstr(+tor. <very en(" +onstant represents an ob,e+t
of t#at en(" +lass w#i+# is stati+ #en+e all en(" +onstants will be +reated at t#e ti"e of +lass
loadin! a(to"ati+ally and #en+e +onstr(+tor will be eEe+(ted at t#e ti"e of en(" +lass loadin!
for every en(" +onstants.
Example:
en(" 6eer7
GH-GI-R'-HI9
6eerB/7
Cyste".o(t.printlnBN'onstr(+tor +alled.N/9
=
=
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
6eer b86eer.GH9
Cyste".o(t.printlnBN#ello.N/9
==
!utput:
D.Y<n("T,ava Test
'onstr(+tor +alled.
'onstr(+tor +alled.
'onstr(+tor +alled.

447

'onstr(+tor +alled.
Sello.
@e +anAt +reate en(" ob,e+t eEpli+itly and #en+e we +anAt invo?e +onstr(+tor dire+tly.
Example:
en(" 6eer7
GH-GI-R'-HI9
6eerB/7
Cyste".o(t.printlnBN+onstr(+tor +alledN/9
=
=
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
6eer b8new 6eerB/9
Cyste".o(t.printlnBb/9
==
!utput:
'o"pile ti"e error.
D.Y<n("T,ava+ Test.,ava
Test.,ava.&. en(" types "ay not be instantiated
6eer b8new 6eerB/9
Example:

en(" 6eer
7
GHB1))/-GIB7)/-R'B65/-HoB&)/-GALaA:I9
int pri+e9
6eerBint pri+e/7
t#is.pri+e8pri+e9
=
6eerB/
7
t#is.pri+e81259
=
p(bli+ int !et\ri+eB/
7
ret(rn pri+e9
=

44$

=
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
6eerD> b86eer.val(esB/9
forB6eer b1.b/
7
Cyste".o(t.printlnBb1FN.......NFb1.!et\ri+eB//9
===
Inside en(" we +an ta?e bot# instan+e and stati+ "et#ods b(t it is not possible to ta?e
abstra+t "et#ods.
*ase 1:
<very en(" +onstant represents an ob,e+t #en+e w#atever t#e "et#ods we +an apply
on t#e nor"al ob,e+ts we +an apply t#e sa"e "et#ods on en(" +onstants also.
"#i$# of t#e follo%ing expressions are valid&
1/ 6eer.GH886eer.R'4444444444444444444444444444T false
2/ 6eer.GH.eV(alsB6eer.R'/ 4444444444444444444Tfalse
3/ 6eer.GHZ6eer.R'444444444444444444444444444444Tinvalid
4/ 6eer.GH.ordinalB/Z6eer.R'.ordinalB/444444Tvalid
*ase 2:
Example 1:
pa+?a!e pa+?19
p(bli+ en(" His#
7
CTAR-^;\\a9
=
Example 2:
pa+?a!e pa+?29
JJi"port stati+ pa+?1.His#.U9
i"port stati+ pa+?1.His#.CTAR9
+lass A
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
Cyste".o(t.printlnBCTAR/9
=
=
1/ I"port pa+?1.U9 4444444444444444444444444444Tinvalid
2/ I"port pa+?1.His#9 4444444444444444444444444Tinvalid
3/ i"port stati+ pa+?1.His#.U9 444444444444444Tvalid

44&

4/ i"port stati+ pa+?1.His#.CTAR9 4444444444Tvalid
Example 3:
pa+?a!e pa+?39
JJi"port pa+?1.His#9
i"port pa+?1.U9
JJi"port stati+ pa+?1.His#.^;\\a9
i"port stati+ pa+?1.His#.U9
+lass 6
7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
His# f8His#.CTAR9
Cyste".o(t.printlnB^;\\a/9
=
=
*ase 3:
en(" 'olor
7
6L;<-R<D
7
p(bli+ void infoB/7
Cyste".o(t.printlnBNDan!ero(s +olorN/9
=
=-^R<<:9
p(bli+ void infoB/
7
Cyste".o(t.printlnBN;niversal +olorN/9
==
+lass Test7
p(bli+ stati+ void "ainBCtrin! ar!sD>/7
'olorD> +8'olor.val(esB/9
forB'olor +1.+/
7
+1.infoB/9
===
!utput:
;niversal +olor
Dan!ero(s +olor
;niversal +olor

45)

Regular expression
A Re!(lar <Epression is a eEpression w#i+# represents a !ro(p of Ctrin!s a++ordin! to a
parti+(lar pattern.
Example:
@e +an write a Re!(lar <Epression to represent all valid "ail ids.
@e +an write a Re!(lar <Epression to represent all valid "obile n("bers.
8#e main important appli$ation areas of Regular Expression are:
To i"ple"ent validation lo!i+.
To develop \attern "at+#in! appli+ations.
To develop translators li?e +o"pilers- interpreters et+.
To develop di!ital +ir+(its.
To develop +o""(ni+ation proto+ols li?e T'\JI\- ;D\ et+.
Example:
i"port ,ava.(til.re!eE.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
int +o(nt8)9
\attern p8\attern.+o"pileBNabN/9
%at+#er "8p."at+#erBNabbbabbabaN/9
w#ileB".findB//
7
+o(ntFF9
Cyste".o(t.printlnB".startB/FN444444NF".endB/FN444444NF".!ro(pB//9
=
Cyste".o(t.printlnBNT#e no of o++(ren+es .NF+o(nt/9
=
=
!utput:
)4444442444444ab
44444446444444ab
7444444&444444ab
T#e no of o++(rren+es. 3
3attern $lass:
A \attern ob,e+t represents K+o"piled version of Re!(lar <EpressionL.
@e +an +reate a \attern ob,e+t by (sin! +o"pileB/ "et#od of \attern +lass.

451

pu,li$ stati$ 3attern $ompile:2tring regex;E
Example:
3attern pM3attern9$ompile:]a,];E
/ote: if we refer A\I we will !et "ore infor"ation abo(t pattern +lass.
=at$#er:
A %at+#er ob,e+t +an be (sed to "at+# +#ara+ter seV(en+es a!ainst a Re!(lar
<Epression. @e +an +reate a %at+#er ob,e+t by (sin! "at+#erB/ "et#od of \attern
+lass.
pu,li$ =at$#er mat$#er:2tring target;E
=at$#er mMp9mat$#er:]a,,,a,,a,a];E
Important met#ods of =at$#er $lass:
1; ,oolean find:;E
It atte"pts to find neEt "at+# and ret(rns tr(e if it is available ot#erwise ret(rns false.
2; int start:;E
Ret(rns t#e start indeE of t#e "at+#.
3; int end:;E
Ret(rns t#e offsetBeV(ali0e/ after t#e last +#ara+ter "at+#ed.Bor/
Ret(rns t#e end indeE of t#e "at+#ed.
4; 2tring group:;E
Ret(rns t#e "at+#ed \attern.
/ote: \attern and %at+#er +lasses are available in java9util9regex pa+?a!e.
*#ara$ter $lasses:
Dab+>4444444444444444444<it#er XaA or XbA or X+A
DRab+> 44444444444444444<E+ept XaA and XbA and X+A
Da40> 44444444444444444444Any lower +ase alp#abet sy"bol
DA41> 44444444444444444444Any (pper +ase alp#abet sy"bol
Da40A41> 4444444444444444Any alp#abet sy"bol
D)4&> 44444444444444444444Any di!it fro" ) to &
Da40A41)4&> 444444444444Any alp#an("eri+ +#ara+ter
Example:
i"port ,ava.(til.re!eE.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\attern p8\attern.+o"pileBNEN/9
%at+#er "8p."at+#erBNa1b7[05N/9
w#ileB".findB//

452

7
Cyste".o(t.printlnB".startB/FN4444444NF".!ro(pB//9
=
=
=
!utput:

3redefined $#ara$ter $lasses:
Ys444444444444444444444spa+e +#ara+ter
Yd444444444444444444444Any di!it fro" o to &Do4&>
Yw444444444444444444444Any word +#ara+terDa40A41)4&>
. 444444444444444444444Any +#ara+ter in+l(din! spe+ial +#ara+ters.
Example:
i"port ,ava.(til.re!eE.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\attern p8\attern.+o"pileBNEN/9
%at+#er "8p."at+#erBNa1b7[05N/9
w#ileB".findB//
7
Cyste".o(t.printlnB".startB/FN4444444NF".!ro(pB//9
=
=
=
!utput:


453

Zuantifiers:
_(antifiers +an be (sed to spe+ify no of +#ara+ters to "at+#.
a44444444444444444444444<Ea+tly one XaA
aF4444444444444444444444At least one XaA
aU4444444444444444444444Any no of aAs in+l(din! 0ero n("ber
aW 4444444444444444444444At "ost one XaA
Example:
i"port ,ava.(til.re!eE.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\attern p8\attern.+o"pileBNEN/9
%at+#er "8p."at+#erBNabaabaaabN/9
w#ileB".findB//
7
Cyste".o(t.printlnB".startB/FN4444444NF".!ro(pB//9
=
=
=
!utput:

3attern $lass split:; met#od:
\attern +lass +ontains splitB/ "et#od to split t#e !iven strin! a!ainst a re!(lar
eEpression.
Example 1:
i"port ,ava.(til.re!eE.U9
+lass Re!(lar<EpressionDe"o
7

454

p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\attern p8\attern.+o"pileBNYYsN/9
Ctrin!D> s8p.splitBNb#as?ar software sol(tionsN/9
forBCtrin! s1.s/
7
Cyste".o(t.printlnBs1/9JJb#as?ar
JJsoftware
JJsol(tions
=
=
=
Example 2:
i"port ,ava.(til.re!eE.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\attern p8\attern.+o"pileBNYY.N/9 Bor/D.>
Ctrin!D> s8p.splitBNwww.d(!ra,obs.+o"N/9
forBCtrin! s1.s/
7
Cyste".o(t.printlnBs1/9JJwww
JJd(!ra,obs
JJ+o"
=
=
=
2tring $lass split:; met#od:
Ctrin! +lass also +ontains splitB/ "et#od to split t#e !iven strin! a!ainst a re!(lar
eEpression.
Example:
i"port ,ava.(til.re!eE.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin! s8Nwww.d(r!a,obs.+o"N9

455

Ctrin!D> s18s.splitBNYY.N/9
forBCtrin! s2.s1/
7
Cyste".o(t.printlnBs2/9JJwww
JJd(r!a,obs
JJ+o"
=
=
=
/ote:
Ctrin! +lass splitB/ "et#od +an ta?e re!(lar eEpression as ar!("ent w#ere as pattern
+lass splitB/ "et#od +an ta?e tar!et strin! as t#e ar!("ent.
2tring8o+eni4er.
T#is +lass present in ,ava.(til pa+?a!e.
It is a spe+ially desi!ned +lass to perfor" strin! to?eni0ation.
Example 1:
i"port ,ava.(til.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
Ctrin!To?eni0er st8new Ctrin!To?eni0erBNd(r!a software sol(tionsN/9
w#ileBst.#as%oreTo?ensB//
7
Cyste".o(t.printlnBst.neEtTo?enB//9JJd(r!a
JJsoftware
JJsol(tions
=
=
=
T#e defa(lt re!(lar eEpression for t#e Ctrin!To?eni0er is spa+e.
Example 2:
i"port ,ava.(til.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7

456


JJCtrin!To?eni0er st8new Ctrin!To?eni0erBN1-&&-&$$N-N-N/9
w#ileBst.#as%oreTo?ensB//
7
Cyste".o(t.printlnBst.neEtTo?enB//9JJ1
JJ&&
JJ&$$
=
=
=
ReAuirement: @rite a re!(lar eEpression to represent all valid identifiers in yava lan!(a!e.
Rules:
T#e allowed +#ara+ters are.
1/ a to 0- A to 1- ) to &- 4-5
2/ T#e 1
st
+#ara+ter s#o(ld be alp#abet sy"bol only.
3/ T#e len!t# of t#e identifier s#o(ld be at least 2.
3rogram:
i"port ,ava.(til.re!eE.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\attern p8\attern.+o"pileBNDa40A41>Da40A41)4&45>FN/9 :or;
\attern p8\attern.+o"pileBNDa40A41>Da40A41)4&45>Da40A41)4&45>UN/9
%at+#er "8p."at+#erBar!sD)>/9
ifB".findB/cc".!ro(pB/.eV(alsBar!sD)>//
7
Cyste".o(t.printlnBNvalid identifierN/9
=
else
7
Cyste".o(t.printlnBNinvalid identifierN/9
=

=
=

457

!utput:
<.Ys+,pT,ava+ Re!(lar<EpressionDe"o.,ava
<.Ys+,pT,ava Re!(lar<EpressionDe"o ,#as+ar
alid identifier
<.Ys+,pT,ava Re!(lar<EpressionDe"o &,#as+ar
Invalid identifier
ReAuirement: @rite a re!(lar eEpression to represent all "obile n("bers.
Rules:
1/ C#o(ld +ontain eEa+tly 1) di!its.
2/ T#e 1
st
di!it s#o(ld be 7 to &.
3rogram:
i"port ,ava.(til.re!eE.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\attern p8\attern.+o"pileBND74&>D)4&>D)4&>D)4&>D)4&>D)4&>D)4&>D)4&>D)4&>D)4&>N/9
JJ\attern p8\attern.+o"pileBND74&>D)4&>7&=N/9
%at+#er "8p."at+#erBar!sD)>/9
ifB".findB/cc".!ro(pB/.eV(alsBar!sD)>//
7
Cyste".o(t.printlnBNvalid n("berN/9
=
else
7
Cyste".o(t.printlnBNinvalid n("berN/9
=
=
=
7nal(sis:
15 digits mo,ile:
D74&>D)4&>D)4&>D)4&>D)4&>D)4&>D)4&>D)4&>D)4&>D)4&> Bor/
D74&>D)4&>7&=
!utput:
<.Ys+,pT,ava+ Re!(lar<EpressionDe"o.,ava
<.Ys+,pT,ava Re!(lar<EpressionDe"o &&$&3)$27&
alid n("ber
<.Ys+,pT,ava Re!(lar<EpressionDe"o 6&$&3)$27&

45$

Invalid n("ber
15 digits :or; 11 digits:
:5&T<VUT5<VUFVY;
!utput:
<.Ys+,pT,ava+ Re!(lar<EpressionDe"o.,ava
<.Ys+,pT,ava Re!(lar<EpressionDe"o &&$&3)$27&
alid n("ber
<.Ys+,pT,ava Re!(lar<EpressionDe"o )&&$&3)$27&
alid n("ber
<.Ys+,pT,ava Re!(lar<EpressionDe"o &1&&$&3)$27&
Invalid n("ber
15 digits :5r; 11 digit :or; 12 digits:
:5PV1;&T<VUT5<VUFVY :or;
:V1;&:5&T<VUT5<VUFVY;
<.Ys+,pT,ava+ Re!(lar<EpressionDe"o.,ava
<.Ys+,pT,ava Re!(lar<EpressionDe"o &&$&3)$27&
alid n("ber
<.Ys+,pT,ava Re!(lar<EpressionDe"o )&&$&3)$27&
alid n("ber
<.Ys+,pT,ava Re!(lar<EpressionDe"o &1&&$&3)$27&
alid n("ber
<.Ys+,pT,ava Re!(lar<EpressionDe"o 6&&$&3)$27&
Invalid n("ber
ReAuirement: @rite a re!(lar eEpression to represent all %ail Ids.
3rogram:
i"port ,ava.(til.re!eE.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/
7
\attern p8\attern.+o"pileBNDa40A41>Da40A41)4&4.>U[Da40A41)4&>FBD.>Da40A41>F/FN/9
%at+#er "8p."at+#erBar!sD)>/9
ifB".findB/cc".!ro(pB/.eV(alsBar!sD)>//
7
Cyste".o(t.printlnBNvalid "ail idN/9
=
else
7

45&

Cyste".o(t.printlnBNinvalid "ail idN/9
=
=
=
!utput:
<.Ys+,pT,ava+ Re!(lar<EpressionDe"o.,ava
<.Ys+,pT,ava Re!(lar<EpressionDe"o b#as?ar$6.va?a[!"ail.+o"
alid "ail id
<.Ys+,pT,ava Re!(lar<EpressionDe"o &&&b#as?ar$6.va?a[!"ail.+o"
Invalid "ail id
<.Ys+,pT,ava Re!(lar<EpressionDe"o &&&b#as?ar$6.va?a[!"ail.+o&
Invalid "ail id
ReAuirement: @rite a pro!ra" to eEtra+t all valid "obile n("bers fro" a file.
'iagram:

3rogram:
i"port ,ava.(til.re!eE.U9
i"port ,ava.io.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
\rint@riter o(t8new \rint@riterBNo(tp(t.tEtN/9
6(fferedReader br8new 6(fferedReaderBnew HileReaderBNinp(t.tEtN//9
\attern p8\attern.+o"pileBND74&>D)4&>7&=N/9
Ctrin! line8br.readLineB/9
w#ileBlineb8n(ll/
7
%at+#er "8p."at+#erBline/9
w#ileB".findB//
7
o(t.printlnB".!ro(pB//9
=

46)

line8br.readLineB/9
=
o(t.fl(s#B/9
=
=
ReAuirement: @rite a pro!ra" to eEtra+t all %ail IDC fro" t#e Hile.
/ote: In t#e above pro!ra" repla+e "obile n("ber re!(lar eEpression wit# %AIL ID re!(lar
eEpression.
ReAuirement: @rite a pro!ra" to display all .tEt file na"es present in E:^s$jp folder.
3rogram:
i"port ,ava.(til.re!eE.U9
i"port ,ava.io.U9
+lass Re!(lar<EpressionDe"o
7
p(bli+ stati+ void "ainBCtrin!D> ar!s/t#rows II<E+eption
7
int +o(nt8)9
\attern p8\attern.+o"pileBNDa40A41)4&43.>FD.>tEtN/9
Hile f8new HileBN<.YYs+,pN/9
Ctrin!D> s8f.listB/9
forBCtrin! s1.s/
7
%at+#er "8p."at+#erBs1/9
ifB".findB/cc".!ro(pB/.eV(alsBs1//
7
+o(ntFF9
Cyste".o(t.printlnBs1/9
=
=
Cyste".o(t.printlnB+o(nt/9
=
=
!utput:
inp(t.tEt
o(tp(t.tEt
o(t(t.tEt
3

You might also like