You are on page 1of 79

Jav

aSy
ll
abus:

Sect
ion1(
Basi
cJav
a)

1)Vari
able&DataTypes
2)Loops
3)Contr
ol St
atement
s
4)Methods
5)Constr
uctor

Sect
ion2(
OOPSConcept
)

1)I
nherit
ance
2)Poly
mor phi
sm
3)AccessModi f
ier
4)Abstr
actClass&Concret
eClass
5)I
nterf
ace&I mplement
ati
onClass
6)General
izat
ion
7)Casti
ng
8)Encapsulat
ion

Sect
ion3

1)Str
ingCl ass
2)Arr
ay
3)Coll
ection
4)PatternPrograms
5)LogicalPrograms
Whati
sJav
a?

Javai
saclass-basedobject-ori
entedprogr
ammingl
anguageforbui
ldi
ngweband
deskt
opappli
cati
ons.Iti
st hemostpopul arpr
ogr
amminglanguageandthe
l
anguageofchoiceforAndr oidprogramming.

Javawasdev el
opedbySunMicrosystems(whi
chisnowt hesubsi
diar
yofOracl
e)i
n
theyear1995.JamesGosl
ingisknownast hef
atherofJava.Bef
oreJava,i
tsname
wasOak.Si nce Oakwasalr
eadyar egi
ster
edcompany,soJamesGosl i
ngandhis
team changedthenamefr
om Oakt oJava.

Pl
atf
orm:Anyhardwar
eorsoft
wareenvi
ronmenti
nwhichaprogr
am runs,i
sknown
asaplat
for
m.SinceJavahasarunt
imeenvi
ronment(
JRE)andAPI,
itiscal
leda
pl
atf
orm.

Appl
icat
ion:

1. Deskt
opAppl
i
cat
ionssuchasacr
obatr
eader
,medi
apl
ayer
,ant
ivi
rus,
etc.
2. WebAppl
i
cat
ionssuchasi
rct
c.co.
in,
jav
atpoi
nt.
com,
etc.
3. Ent
erpr
iseAppl
i
cat
ionssuchasbanki
ngappl
i
cat
ions.
4. Mobi
l
e
5. EmbeddedSy
stem
6. Smar
tCar
d
7. Robot
ics
8. Games,
etc.

Ty
pesofJav
aAppl
icat
ions

Therear
emainl
y4t
ypesofappl
i
cat
ionst
hatcanbecr
eat
edusi
ngJav
a
progr
amming:
1) St
andal
oneAppl
i
cat
ion

Standal
oneapplicat
ionsarealsoknownasdesktopappli
cationsorwindow-based
appli
cat
ions.Thesearetradi
ti
onalsoft
warethatweneedt oinst
allonever
ymachi ne.
Examplesofstandaloneappli
cati
onareMediaplay
er,anti
vir
us,etc.AWTand
Swingar eusedinJav af
orcreati
ngstandal
oneappli
cati
ons.

2) WebAppl
icat
ion

Anapplicati
onthatr
unsont heserversi
deandcr eatesady namicpageiscal
l
eda
webappl i
cati
on.Curr
entl
y,Serv
let
,JSP, St
ruts,
Spr i
ng,Hibernat
e,JSF,
etc.
technol
ogiesareusedforcreat
ingwebapplicat
ionsi nJava.

3) Ent
erpr
iseAppl
icat
ion

Anappl
icat
ionthati
sdist
ri
butedinnat
ure,suchasbanki ngappli
cat
ions,etc.i
s
cal
l
edanent er
pri
seappli
cati
on.I
thasadvantageslikehi
gh-l
evelsecuri
ty,l
oad
bal
anci
ng,andclust
eri
ng.InJava,EJBisusedf orcreat
ingenter
pri
seapplicati
ons.
4) Mobi
leAppl
icat
ion
Anappl
icati
onwhichiscr
eat
edformobil
edevi
cesiscal
l
edamobileappl
i
cat
ion.
Cur
rent
ly,Andr
oidandJavaMEareusedforcr
eat
ingmobil
eappl
i
cati
ons.
Jav
aPl
atf
orms/Edi
ti
ons
Ther
ear
e4pl
atf
ormsoredi
ti
onsofJav
a
1) Jav
aSE(
Jav
aSt
andar
dEdi
ti
on)
I
tisaJavapr ogrammi ngpl atfor
m.I tincl
udesJavaprogrammi ngAPI ssuchas
j
ava.l
ang,java.i
o,java.net,j
ava.util
,j
av a.
sql
,jav
a.mathetc.I
tincludescoretopi
cs
l
ikeOOPs, St
ring,Regex, Exception,Innercl
asses,Mul
ti
threading,I
/OStream,
Networki
ng,AWT, Swing,Reflection,Coll
ect
ion,et
c.
2) Jav
aEE(
Jav
aEnt
erpr
iseEdi
ti
on)
Iti
sanenterpr
iseplatf
ormthati
smainl
yusedtodevel
opwebandenter
pri
se
appli
cat
ions.Iti
sbuil
tontopoftheJavaSEpl
atf
orm.I
tincl
udest
opi
csli
keSer
vlet
,
JSP,WebSer v
ices,EJB,JPA,
etc.
3) Jav
aME(
Jav
aMi
croEdi
ti
on)
I
tisami
cropl
atf
ormt
hati
sdedi
cat
edt
omobi
l
eappl
i
cat
ions
4) Jav
aFX

I
tisusedt
odev
elopr
ichi
nter
netappl
i
cat
ions.I
tusesal
i
ght
wei
ghtuseri
nter
face
API.

Di
ff
erencebet
weenJDK,
JRE,
andJVM

1) JVM

JVM ( Jav
aVi rt
ualMachine)isanabst ractmachine.I
tiscal
ledav i
rt
ualmachi
ne
becausei tdoesn'
tphysi
callyexi
st.Itisaspecif
icati
onthatprovi
desarunti
me
envir
onmenti nwhichJav abytecodecanbeexecut ed.I
tcanalsorunthose
programswhi charewr i
tt
eni notherlanguagesandcompi l
edt oJavabyt
ecode.

JVMsar eavail
ableformanyhardwareandsoftwarepl
atfor
ms.JVM,JRE,andJDK
areplatf
orm dependentbecausetheconf
igur
ationofeachOSisdi
ff
erentfr
om each
other
.Howev er
, Jav a is plat
form independent. Ther
e are three noti
ons
of t he JVM: speci
fi
cati
on,i
mplementat
ion,andinst
ance.

TheJVM per
for
mst
hef
oll
owi
ngmai
ntasks:

o Loadscode
o Ver
if
iescode
o Execut
escode
o Pr
ovi
desr
unt
imeenv
ironment

2) JRE

JREi sanacronymf orJavaRunti


meEnv i
ronment.I
tisalsowr
it
tenasJavaRTE.The
JavaRunt i
meEnv ir
onmenti sasetofsoftwaretool
swhichareusedfordev
elopi
ng
Javaapplicat
ions.I
tisusedt opr
ovidetherunti
meenv i
ronment.I
tist
he
i
mpl ementati
onofJVM.I tphysi
callyexi
sts.I
tcontai
nsasetofli
brar
ies+other
fi
lesthatJVM usesatr unt
ime.

Thei
mplement
ati
onofJVM i
sal
soact
ivel
yrel
easedbyot
hercompani
esbesi
des
SunMicr
oSyst
ems.

3) JDK

JDKisanacronymforJav
aDev elopmentKi
t.TheJavaDevel
opmentKi
t(JDK)i
sa
soft
waredevel
opmentenvi
ronmentwhichisusedtodevel
opJavaappl
i
cati
onsand
appl
ets.I
tphysi
cal
l
yexist
s.Itcontai
nsJRE+dev el
opmenttool
s.

JDKisani
mplement
ati
onofanyoneoft
hebel
owgi
venJav
aPl
atf
ormsr
eleasedby
Oracl
eCor
por
ati
on:

o St
andar
dEdi
ti
onJav
aPl
atf
orm
o Ent
erpr
iseEdi
ti
onJav
aPl
atf
orm
o Mi
croEdi
ti
onJav
aPl
atf
orm

TheJDKcont ai
nsapr i
vateJavaVir
tualMachi
ne(JVM)andaf ewotherresour
ces
suchasaninterpr
eter
/loader(j
ava)
,acompil
er(j
avac)
,anarchi
ver(
jar)
,a
document
ationgenerator(Jav
adoc),et
c.t
ocompletethedevel
opmentofaJav a
Appl
i
cat
ion.

HowDownl
oadandI
nst
all
Jav
aJDK?
Fol
l
owbel
owl
i
nksst
epsf
ordownl
oadandi
nst
all
Jav
a
1) Li
nkf
orJDKDownl
oad:
htt
ps:
//www.
gur
u99.
com/
inst
all
-
j
ava.
html
2) Li
nkf
orEcl
i
pseDownl
oad:
htt
ps:
//www.
gur
u99.
com/
inst
all
-
ecl
i
pse-
jav
a.ht
m

Dat
aTy
pesi
nJav
a
Datatypesspeci
fythedi
ff
erentsi
zesandval
uest
hatcanbest
oredi
nthev
ari
abl
e.
Therearetwotypesofdat
at y
pesinJava:

1. Pr i
miti
vedatatypes:
Thepri
mit
ivedat
aty
pesi
ncl
udebool
ean,
char
,by
te,
shor
t,i
nt,
long,f
loatanddoubl
e.
2. Non- pr
imi
ti
vedat
aty
pes:
Thenon-
pri
mit
ivedat
aty
pesi
ncl
udeCl
ass,
I
nter
facesandAr
rays

Jav
aPr
imi
ti
veDat
aTy
pes

I
nJaval
anguage,
pri
miti
vedat
aty
pesaret
hebuil
dingblocksofdata
mani
pul
ati
on.
Thesearet
hemostbasi
cdat
atypesavai
lableinJaval
anguage.

Ther
ear
e8t
ypesofpr
imi
ti
vedat
aty
pes:

o bool
eandat
aty
pe
o by
tedat
aty
pe
o chardat
aty
pe
o shor
tdat
aty
pe
o i
ntdat
aty
pe
o l
ongdat
aty
pe
o f
loatdat
aty
pe
o doubl
edat
aty
pe

Dat
aTy
pe Def
aul
tVal
ue Def
aul
tsi
ze
boolean false 1bi
t
char '
\u0000' 2by
te
byte 0 1by
te
short 0 2by
te
i
nt 0 4by
te
l
ong 0L 8by
te
fl
oat 0.0f 4by
te
double 0.0d 8by
te

1) Bool
eanDat
aTy
pe

TheBool
eandat
aty
pei
susedt
ost
oreonl
ytwopossi
blev
alues:
tr
ueandfal
se.Thi
sdat
aty
pei
susedf
orsi
mpl
efl
agst
hatt
rackt
rue/
fal
se
condi
ti
ons.
TheBooleandat
aty
pespeci
fi
esonebi
tofi
nfor
mat
ion,
buti
ts"
size"can'
tbedef
ined
preci
sel
y.

Exampl
e:Bool
eanone=f
alse

2) By
teDat
aTy
pe
Thebytedataty
pei sanexampl
eofpri
miti
vedataty
pe.Itisan8-bitsi
gnedtwo'
s
complementint
eger.I
tsval
ue-
rangel
i
esbetween-128to127( i
nclusiv
e).I
ts
mini
mum v al
ueis-128andmaximum val
ueis127.I
tsdefaultv
alueis0.

Thebytedataty
peisusedtosavememor yinlar
gear
rayswheret
hememory
savi
ngsismostrequi
red.I
tsavesspacebecauseabytei
s4timessmal
l
ert
hanan
i
nteger
.Itcanal
sobeusedi npl
aceof"i
nt"dataty
pe.

Exampl
e:by
tea=10,
byt
eb=-
20

3) Shor
tDat
aTy
pe

Theshortdataty
peisa16-bitsignedtwo'scompl
ementinteger
.It
sval
ue-
rangel
i
es
bet
ween- 32,
768to32,
767(inclusive)
.It
smi ni
mum v
alueis-32,
768andmaximum
val
ueis32,767.I
tsdef
aul
tvaluei s0.
Theshor
tdatatypecanal
sobeusedtosavememor
yjustl
i
keby
tedat
aty
pe.Ashor
t
dat
atypeis2ti
messmal l
ert
hananint
eger
.

Exampl
e:shor
ts=10000,
shor
tr=-
5000

4) I
ntDat
aTy
pe
Theintdat
atypei
sa32-bi
tsignedtwo'scomplementi
nteger.I
tsv
alue-
rangel
i
es
bet
ween-2,147,
483,
648(-
2^31)to2,147,
483,
647(2^31-1)(i
ncl
usi
ve).
I
tsminimum v
aluei
s-2,
147,
483,
648andmaxi
mum v
aluei
s2,
147,
483,
647.I
tsdef
aul
t
v
alueis0.

Thei
ntdat
aty
pei
sgener
all
yusedasadef
aul
tdat
aty
pef
ori
ntegr
alv
aluesunl
essi
f
t
her
eisnopr
obl
em aboutmemor
y.

Exampl
e:i
nta=100000,
intb=-
200000

5) LongDat
aTy
pe
Thel
ongdat
aty
pei
sa64-
bitt
wo'
scompl
ementi
nteger
.It
sval
ue-
rangel
i
esbet
ween
-9,
223,
372,
036,
854,
775,
808(
-2^
63) t
o 9,
223,
372,
036,
854,
775,
807(
2^63 -
1)(
incl
usi
ve)
.
I
tsmi ni
mum v al
ueis-9,223,
372,
036,
854,775,
808andmaxi
mum val
ueis
9,223,
372,
036,854,
775,
807.Itsdef
aultval
ueis0.Thel
ongdatat
ypei
susedwhen
youneedar angeofvaluesmorethanthoseprovi
dedbyi
nt.
Exampl
e:l
onga=100000L,
longb=-
200000L

6) Fl
oatDat
aTy
pe
Thefl
oatdatatypeisasingle-
preci
sion32- bi
tIEEE754floati
ngpoint
.It
svaluer
ange
i
sunli
mited.I
tisrecommendedt ouseaf l
oat(i
nsteadofdouble)i
fyouneedtosave
memoryinlargearraysoff
loati
ngpoi ntnumber s.Thefl
oatdataty
peshouldnever
beusedforpreci
sev al
ues,suchascur rency.I
tsdefaul
tvalueis0.
0F.
Exampl
e:f
loatf
1=234.
5f

7) Doubl
eDat
aTy
pe

Thedoubl edat
at ypeisadouble-
preci
sion64-bi
tIEEE754fl
oat
ingpoint.It
svalue
rangeisunli
mited.Thedoubledatatypeisgeneral
lyusedf
ordecimalvaluesj
ust
l
ikefloat.Thedoubl edataty
pealsoshouldneverbeusedforpreci
sevalues,such
ascurrency.I
tsdefaultval
ueis0.
0d.

Exampl
e:doubl
ed1=12.
3

8) CharDat
aTy
pe

Thechardat
atypeisasingle16-
bitUni
codechar
acter
.It
svalue-
rangel
i
esbetween
'
\u0000'
(or0)t
o'\uf
fff
'(or65,
535incl
usiv
e).
Thechardatat
ypeisusedtost
ore
char
act
ers.

Exampl
e:charl
ett
erA='
A'

Whycharuses2by
tei
njav
aandwhati
s\u0000?

I
tisbecausejavausesUnicodesy
stem notASCIIcodesyst
em.The\ u0000isthe
l
owestr angeofUnicodesyst
em.Togetdetail
explanat
ionaboutUni
codevisi
tnext
page

Whati
saVar
iabl
einJav
a?
Vari
ableinJavaisadatacontainerthatstoresthedatav aluesduri
ngJavaprogr
am
execut
ion.Everyvar
iabl
eisassigneddat atypewhi chdesignatest
het y
peand
quanti
tyofvaluei
tcanhold.Variableisamemor ylocat
ionnameoft hedat
a.The
Javavari
ableshavemainlythr
eet ypes:Local,I
nstanceandSt ati
c.
I
nor
dert
ouseav
ari
abl
einapr
ogr
am y
out
oneedt
oper
for
m 2st
eps

1. Var
iabl
eDecl
arat
ion
2. Var
iabl
eIni
ti
ali
zat
ion

Var
iabl
eDecl
arat
ion:
Todecl
areav
ari
abl
e,y
oumustspeci
fyt
hedat
aty
pe&gi
vet
hev
ari
abl
eauni
que
name.
Exampl
es:
i
nta;
f
loatpi
;
doubl
ed;
chara;

Var
iabl
eIni
ti
ali
zat
ion:
Toi
nit
ial
i
zeav
ari
abl
e,y
oumustassi
gni
tav
ali
dval
ue.

Exampl
eofot
herVal
i
dIni
ti
ali
zat
ionsar
e

pi
=3.
14f
;
do=20.
22d;
a=’
v’
;

i
nta=2,
b=4,
c=6;
f
loatpi
=3.
14f
;
doubl
edo=20.
22d;
chara=’
v’
;

Jav
aVar
iabl
eTy
pes
I
nthissect
ion,
wewi
l
llear
naboutt
hev
ari
oust
ypesofJav
avar
iabl
esment
ioned
bel
ow.
• Local
var
iabl
e
• I
nst
ancev
ari
abl
e(Non-
Stat
icVar
iabl
e)
• St
ati
corCl
assv
ari
abl
e
LocalVar
iabl
es
Thesevar
iabl
esar
edecl
aredinsidethebodyofamet
hod.Thesecanbeusedwi
thi
n
thesamemethodwher
eitisbeinginit
ial
i
zed.

Someoft
hepr
oper
ti
esofaLocal
Var
iabl
eincl
ude:
1. Local
var
iabl
esar
edecl
aredi
nsi
deamet
hod,
const
ruct
or,
orbl
ock.
2. Noaccessmodi
fi
ersf
orl
ocal
var
iabl
es.
3. Thesecanbeusedonl
ywi
thi
nthesamebl
ock,
met
hod,
orconst
ruct
orwher
e
i
tisi
nit
ial
i
zed.
4. Nodef aul
tvaluesaft
eryouhavedecl
aredy
ourl
ocal
var
iabl
e.Youneedt
o
i
nit
ial
i
zey
ourdecl
aredlocalvar
iabl
e.
5. I
tcan’
tbedef
inedbyast
ati
ckey
wor
d.

Gi
venbelowistheprogram i
nwhichwehaveusedl
ocal v
ari
ablesinit
iali
zedwithi
na
methodofaclass.As“hei
ght”i
salocalv
ari
abl
eini
ti
ali
zedwiththecal cul
ate(
)
method,
thescopeofthisvari
abl
ewill
beconfi
nedwit
hinthemet hod.
publ
i
ccl
assl
ocal
{

publ
i
cvoi
dcal
cul
ate(
){

/
/ini
ti
ali
zedal
ocal
var
iabl
e"hei
ght
"inthei
ght=0;

/
/incr
ement
ingt
hev
alueofhei
ght
hei
ght=hei
ght+170;
Sy
stem.
out
.pr
int
ln(
"hei
ghti
s:"+hei
ght+"cm"
);
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
]){
/
/ai
sar
efer
enceusedt
ocal
lcal
cul
ate(
)met
hod
l
ocal
a=newl
ocal
()
;
a.
cal
cul
ate(
);
}
}
Out
put
:hei
ghti
s:170cm

I
nst
anceVar
iabl
es:

I
nst
ancevar
iabl
esaret
hosevari
ablest
hataredecl
aredinsi
deaclass.Unli
keLocal
v
ari
abl
es,
thesevar
iabl
escannotbedecl
aredwit
hinablock,met
hod, orconst
ruct
or.

Exampl
eofI
nst
anceVar
iabl
e

publ
i
ccl
assi
nst
ance{
/
/Decl
ari
ngi
nst
ancev
ari
abl
espubl
i
cintr
oll
Num;
publ
i
cSt
ri
ngname;
publ
i
cintt
otal
Mar
ks;
publ
i
cintnumber
;
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
/
/cr
eat
edobj
ect
i
nst
ancei
n=newi
nst
ance(
);
i
n.r
oll
Num =95;
i
n.name="
Bhar
at"
;
i
n.t
otal
Mar
ks=480;
/
/pr
int
ingt
hecr
eat
edobj
ect
sSy
stem.
out
.pr
int
ln(
in.
rol
l
Num)
;
Sy
stem.
out
.pr
int
ln(
in.
name)
;
Sy
stem.
out
.pr
int
ln(
in.
tot
alMar
ks)
;

/
*
* wedi
dnotassi
gnt
hev
aluet
onumbersoi
t
* wi
l
lpr
int'
0'bydef
aul
t
*
/Sy
stem.
out
.pr
int
ln(
in.
number
);
}
}
Out
put
:
95
Bhar
at480
0

St
ati
corCl
assVar
iabl
e

Unl
iketheLocal
andInst
ancevar
iabl
e(wherewecannotusest
ati
c),
wehav eanother
var
iabl
etypewhichi
sdeclar
edasstat
icandisknownas“St
ati
corClassv
ariabl
e”
Exampl
e
publ
i
ccl
assSt
ati
cVar
iabl
e{

/
/radi
usi
sdecl
aredaspr
ivat
est
ati
c
pr
ivat
est
ati
cintr
adi
us;

/
/pi
isaconst
antoft
ypedoubl
edecl
aredasst
ati
c
pr
ivat
est
ati
cfi
nal
doubl
epi
=3.
14;

publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){

/
/assi
gni
ngv
alueofr
adi
us
r
adi
us=3;

/
/cal
cul
ati
ngandpr
int
ingci
rcumf
erence
Sy
stem.
out
.pr
int
ln(
"Ci
rcumf
erenceofaci
rcl
eis:
"+2*
pi*
radi
us)
;
}
}
Out
put
:Ci
rcumf
erenceofaci
rcl
eis:
18.
84

Whati
sCl
ass?

Cl
ass:
-
>>Classi
sacombi
nat
ionofmet
hodsandv
ari
abl
es.I
tisj
ustabl
uepr
intor
t
empl
ate.
1.Cl
assisusedtost orest
ati
caswellasnon-
stat
icmember
sinsi
dei
t.
2.I
tdoesnotoccupymemor y.
3.Synt
axofclass:-
Accessmodifi
er Cl
ass Classname.
Sy
ntax:

cl
ass<cl
ass_
name>
{
f
iel
d;
met
hod;
}

Whati
sObj
ecti
nJav
a?

=Obj
ecti
sani
nst
anceofacl
ass.
=Wecancr
eatobj
ectbyusi
ng“
NEW“key
wor
d
=Anobj
ecti
nOOPSisnothi
ngbutasel
f-
cont
ainedcomponentwhi
chconsi
stsof
met
hodsandpr
oper
ti
estomakeaparti
cul
arty
peofdatausef
ul.
=Forexamplecol
orname,t
abl
e,bag,
barki
ng.Wheny ousendamessaget
oan
obj
ect
,youareaski
ngtheobj
ectt
oinvokeorexecut
eoneofitsmet
hodsasdef
ined
i
ntheclass.
From aprogr
ammingpointofv
iew,
anobjectinOOPScanincl
udeadat
ast
ruct
ure,
a
vari
abl
e,orafunct
ion.I
thasamemoryl
ocational
locat
ed.

Sy
ntax:

Cl
assname Ref
erencev
ari
abl
e = new Cl
assname
Ex.
Ani
mala =new Ani
mal
();
Whati
samet
hodi
nJav
a?

1) Amet hodisablockofcodeorcol
lect
ionofst
atement
sorasetofcode
gr
oupedt
oget
hertoperfor
m acert
aint
askoroperat
ion.

2) I ti
susedt
oachi
evethereusabi
l
ityofcode.Wewri
teamethodonceanduse
i
tmanyti
mes.Wedonotr
equir
et owri
tecodeagainandagai
n.

3) I talsopr
ovi
dest
heeasymodi
fi
cat
ionandr
eadabi
l
ityofcode,
justbyaddi
ng
orr
emovingachunkofcode.

4) Themet
hodi
sexecut
edonl
ywhenwecal
lori
nvokei
t.

5) Themosti
mpor
tantmet
hodi
nJav
aist
hemai
n()met
hod

Sy
ntax:
AccessSpeci
fi
er r
etur
nTy
pe nameOf
Met
hod(
Par
amet
erLi
st)
{
/
/met
hodbody
}

Thesy
ntaxshownabov
eincl
udes–


AccessSpeci
fi
er−I
tdefinest
heaccesst
ypeoft
hemet
hodandi
tisopt
ional
touse.

ret
urnTy
pe−Met
hodmayr
etur
nav
alue.

nameOf
Method−Thi
sisthemethodname.Themet
hodsi
gnat
ureconsi
stsoft
he
met
hodnameandt
heparameterl
ist
.
•ParameterLi
st−Theli
stofparameter
s,i
tisthety
pe,
order
,andnumberof
parametersofamethod.Theseareopt
ional
,methodmaycontai
nzer
oparamet
ers.
•methodbody−Themet
hodbodydefineswhatt
hemet
hoddoeswi
tht
he
stat
ements.
Whati
sAccessModi
fi
er?

Youmight’
vecomeacr osspubl
ic,pri
vateandprot
ect
edkey wor
dswhilepracti
cing
anyJavaprogr
ams,thesearecall
edt heAccessModif
ier
s.Asthenamesuggest s,
AccessModifi
ersi
nJav ahel
pstor estr
ictt
hescopeofaclass,
const
ructor,
vari
able,
methodordatamember .

Accessmodifi
erscanbespecif
iedsepar
atel
yforaclass,
constr
uct
ors,
fiel
ds,
and
methods.Theyareal
sorefer
redasJavaaccessspecif
ier
s,butt
hecorr
ectnamei
s
Javaaccessmodi fi
ers.

Ty
pesofAccessModi
fi
er

Ther
ear
efouraccessmodi
fi
erskey
wor
dsi
nJav
aandt
heyar
e:

Def
aul
tAccessModi
fi
er
Pr
ivat
eAccessModi
fi
er
Publ
i
cAccessModi
fi
er
Pr
otect
edAccessModi
fi
er

1) Def aul
t:Wheneveraspeci
fi
caccesslevel
isnotspeci
fi
ed,theni
tisassumed
tobe‘
def
ault
’.Thescopeoft
hedefaul
tlev
el i
swithi
nthepackage.
2) Pr i
vat
e:Whenanent
it
yispr
ivat
e,t
henthi
senti
tycannotbeaccessedout
side
thecl
ass.Apri
vat
eent
it
ycanonl
ybeaccessi
blefr
om wit
hinthecl
ass.
3) Publ i
c:Thisi
sthemostcommonaccessl evelandwhenevert
hepubl i
c
accessspecif
ieri
susedwithanenti
ty,
whi chpart
icul
arenti
tyi
saccessibl
e
thr
oughoutfr
om withi
noroutsi
detheclass,wi
thi
norout si
dethepackage,et
c.
4) Pr ot
ected:Thepr
otect
edaccesslevel
hasascopethatiswi
thi
nthepackage.
Aprot
ectedentit
yisal
soaccessi
bleout
sidethepackaget
hroughi
nher
it
edclassor
chi
l
dclass.
Jav
aCont
rolSt
atement
s:

Javacompil
erexecutest
hecodefrom t
opt obottom.Thestat
ement sinthecode
areexecut
edaccordingtot
heorderi
nwhi chtheyappear
.Howev er,
javapr ovi
des
stat
ementsthatcanbeusedtocontr
oltheflowofJavacode.Suchst at
ementsar e
call
edcont
rolfl
owstatement
s.I
tisoneoft hefundamental
featur
esofJav a,which
provi
desasmoot hfl
owofprogr
am.

Jav
apr
ovi
dest
hreet
ypesofcont
rol
flowst
atement
s.

1. Deci
sionMaki
ngst
atement
s
= i
fst
atement
s
= swi
tchst
atement
2. Loopst
atement
s
= dowhi
l
eloop
= whi
l
eloop
= f
orl
oop
= f
or-
eachl
oop
3. Jumpst
atement
s
= br
eakst
atement
= cont
inuest
atement

Deci
sion-
Maki
ngst
atement
s:

Asthenamesuggests,decisi
on-maki
ngstat
ementsdecidewhichstat
ementto
execut
eandwhen.Decision-maki
ngstat
ementsevaluat
etheBooleanexpressi
on
andcontr
oltheprogram fl
owdependingupontheresul
tofthecondit
ionprovi
ded.
Therear
etwotypesofdeci
sion-
maki
ngst
atement
sinJav
a,i
.e.
,I
fst
atementand
swit
chstat
ement.

1) I
fSt
atement
:

InJav a,
thei
fstatementisusedt oevaluat
eacondi ti
on.Thecont
roloft
heprogr
am
i
sdi vert
eddependingupont hespeci
ficcondit
ion.Thecondit
ionoftheI
fst
atement
givesaBooleanvalue,ei
thertrueorf
alse.InJava,ther
earefourty
pesofif-
statementsgivenbelow.

1. Si
mpl
eifst
atement
2. i
f-
elsest
atement
3. i
f-
else-
ifl
adder
4. Nest
edi
f-
stat
ement

1)
Simpl
eifst
atement
:

Iti
sthemostbasicstatementamongal
lcont
rolf
lowstat
ementsinJava.I
t
eval
uatesaBooleanexpressi
onandenabl
estheprogr
am toent
erablockofcodei
f
theexpressi
onev
aluatestotr
ue.

Sy
ntax

ofi
fst
atementi
sgi
venbel
ow,

i
f(
condi
ti
on){
st
atement1; /
/execut
eswhencondi
ti
oni
str
ue
}
Consi
dert
hef
oll
owi
ngexampl
einwhi
chwehav
eusedt
hei
fst
atementi
nthej
ava
code.

Exampl
e:
publ
i
ccl
assSt
udent
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
i
ntx=10;
i
nty=12;
i
f(
x+y>20){
Sy
stem.
out
.pr
int
ln(
"x+yi
sgr
eat
ert
han20"
);
}
}
}

Out
put
:x+yi
sgr
eat
ert
han20

2) i
f-
elsest
atement

The“i
f-el
sestat
ement”i
sanextensi
ont
otheif-
stat
ement,whi
chusesanot
herblock
ofcode,i
.e.
,el
sebl
ock.Theel
seblocki
sexecut
edifthecondi
ti
onofthei
f-
blockis
eval
uatedasfal
se.
Sy
ntax:
if(
condi
ti
on){
st
atement1;
//execut
eswhencondi
ti
oni
str
ue
}
el
se{
st
atement2;
//execut
eswhencondi
ti
oni
sfal
se
}
Exampl
e:
publ
i
ccl
assSt
udent
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
i
ntx=10;
i
nty=12;
i
f(
x+y<10){
Sy
stem.
out
.pr
int
ln(
"x+yi
slesst
han 10"
);
}
el
se{
Sy
stem.
out
.pr
int
ln(
"x+yi
sgr
eat
ert
han20"
);
}
}
}

Out
put
:x+yi
sgr
eat
ert
han20

3) i
f-
else-
ifl
adder
:

Thei f
-el
se-i
fstatementcontai
nstheif
-st
atementfol
lowedbymul t
ipl
eelse-
if
statements.I
not herwords,wecansaythati
tisthechainofif-
elsestat
ementsthat
createadecisiontreewheretheprogr
am mayenterintheblockofcodewher et
he
conditi
onistrue.Wecanal sodefi
neanelsestat
ementattheendoft hechai
n.

Sy
ntaxofi
f-
else-
ifst
atementi
sgi
venbel
ow.
i
f(
condi
ti
on1){
st
atement1; /
/execut
eswhencondi
ti
on1i
str
ue
}
el
sei
f(
condi
ti
on2){
st
atement2; /
/execut
eswhencondi
ti
on2i
str
ue
}
el
se{
st
atement2; /
/execut
eswhenal
lthecondi
ti
onsar
efal
se
}

Exampl
e:
publ
i
ccl
assSt
udent
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
St
ri
ngci
ty="
Del
hi"
;

i
f(
cit
y=="
Meer
ut"
){
Sy
stem.
out
.pr
int
ln(
"ci
tyi
smeer
ut"
);
}
el
sei
f(ci
ty=="
Noi
da"
){
Sy
stem.
out
.pr
int
ln(
"ci
tyi
snoi
da"
);
}
el
sei
f(
cit
y=="
Agr
a"){
Sy
stem.
out
.pr
int
ln(
"ci
tyi
sagr
a")
;
}
el
se{Sy
stem.
out
.pr
int
ln(
cit
y);
}
}
}
Out
put
:Del
hi
===================================================================
4.Nest
edi
f-
stat
ement

Innestedi
f-
stat
ement s,t
hei
fstat
ementcancont
ainai
fori
f-
elsest
atementi
nsi
de
another i
forelse-
ifstat
ement
.

Sy
ntaxofNest
edi
f-
stat
ementi
sgi
venbel
ow.

i
f(condi
ti
on1){
st
atement1;
//execut
eswhencondi
ti
on1i
str
ue
i
f(condi
ti
on2){
st
atement2;
//execut
eswhencondi
ti
on2i
str
ue
}
el
se{
st
atement2;
//execut
eswhencondi
ti
on2i
sfal
se
}
}
Exampl
e:
publ
i
ccl
assSt
udent{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){St
ri
ngaddr
ess="
Del
hi,
Indi
a";

i
f(address.
endsWit
h("I
ndi
a")
){i
f(addr
ess.cont
ains(
"Meer
ut"
))
{System.out.
pri
ntl
n("
Yourci
tyi
sMeer ut
");
}
el
sei
f(
addr
ess.
cont
ains(
"Noi
da"
)){Sy
stem.
out
.pr
int
ln(
"Yourci
tyi
sNoi
da"
);
}
el
se{Sy
stem.
out
.pr
int
ln(
addr
ess.
spl
i
t("
,"
)[
0])
;
}
}
el
se{
Sy
stem.
out
.pr
int
ln(
"Youar
enotl
i
vingi
nIndi
a")
;
}
}
}

Out
put
:Del
hi

Swi
tchSt
atement
:
InJav a,Swit
chst atementsaresimilartoi
f-
else-
ifstat
ements.Theswi t
ch
stat
ementcont ainsmulti
pleblocksofcodecalledcasesandasinglecasei s
execut edbasedont hevari
ablewhichisbeingswi t
ched.Theswit
chst atementi
s
easiert ouseinsteadofif-
else-
ifstatements.I
talsoenhancest
her eadabil
it
yofthe
program.

Poi
ntst
obenot
edaboutswi
tchst
atement
:

-
Thecasevar
iabl
escanbeint
,shor
t,by
te,
char
,orenumer
ati
on.St
ri
ngt
ypei
s
al
sosuppor
tedsi
nceversi
on7ofJava
-
Casescannotbedupl
i
cat
e
-Def
aul
tstat
ementisexecut
edwhenanyoft
hecasedoesn'
tmat
cht
hev
alue
ofexpr
essi
on.I
tisopt
ional
.
-Breakstat
ementterminat
es the swit
chblock when t
he condi
ti
on i
s
sat
isf
ied.Iti
sopti
onal
,i
fnotused,nextcasei
sexecut
ed.
-Whi
l
eusi
ngswi
tchst
atements,wemustnot
icethatt
hecaseexpressi
onwi
l
l
beoft
hesamet
ypeasthev
ariabl
e.Howev
er,i
twil
lal
sobeaconstantv
alue.
Thesy
ntaxt
ouset
heswi
tchst
atementi
sgi
venbel
ow.

swi
tch(
expr
essi
on)
{
casev
alue1:
st
atement
1;
br
eak;
.
.
.
casev
alueN:
st
atement
N;
br
eak;
def
aul
t:
def
aul
tst
atement
;
}

Exampl
e:

publ
i
ccl
assSt
udenti
mpl
ement
sCl
oneabl
e
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
i
ntnum =2;
swi
tch(
num)
{
case0:
Sy
stem.
out
.pr
int
ln(
"numberi
s0"
);
br
eak;
case1:
Sy
stem.
out
.pr
int
ln(
"numberi
s1"
);
br
eak;
def
aul
t:
Sy
stem.
out
.pr
int
ln(
num)
;
}
}
}

Out
put
:2

Const
ruct
or:
CONSTRUCTORi
saspeci
almet
hodt
hati
susedt
oini
ti
ali
zeanewl
ycr
eat
edobj
ect
andi
scal
l
edj
ustaf
tert
hememor
yisal
l
ocat
edf
ort
heobj
ect
.Itcanbeusedt
o
i
nit
ial
i
zet
heobj
ect
stodesi
redv
aluesordef
aul
tval
uesatt
het
imeofobj
ectcr
eat
ion.
I
tisnotmandat
oryf
ort
hecodert
owr
it
eaconst
ruct
orf
oracl
ass.
I
fnouser
-def
inedconst
ruct
ori
spr
ovi
dedf
oracl
ass,
compi
l
eri
nit
ial
i
zesmember
v
ari
abl
est
oit
sdef
aul
tval
ues.

Note:Iti
scalledconst
ructorbecausei tconstr
uctsthev
aluesatthetimeofobj
ect
creat
ion.Iti
snotnecessarytowr it
eaconst ructorf
oraclass.I
tisbecausej
ava
compilercreatesadef
aultconstructorifyourcl
assdoesn'thaveany.

Rul
esf
orcr
eat
ingaJav
aConst
ruct
or

1.I
thast
hesamenameast
hecl
ass
2.I
tshoul
dnotr
etur
nav
aluenotev
env
oid
3.AJav
aconst
ruct
orcannotbeabst
ract
,st
ati
c,f
inal
,andsy
nchr
oni
zed
4.Wecanhav
epr
ivat
e,pr
otect
ed,
publ
i
cordef
aul
tconst
ruct
ori
nJav
a.

Note:Const
ruct
orhast
hesamenameast
hatoft
hecl
assanddoesnothav
eany
r
eturnty
pe.
Forexampl
e,cl
assTest{
Test
(){
/
/const
ruct
orbody
}
}
Her
e,Test
()i
saconst
ruct
or.
I
thast
hesamenameast
hatoft
hecl
assanddoesn'
thav
ear
etur
nty
pe.
====================================================================
=

Const
ruct
orExampl
e:
cl
assMai
n{
pr
ivat
eSt
ri
ngname;
/
/const
ruct
or
Mai
n(){
Sy
stem.
out
.pr
int
ln(
"Const
ruct
orCal
l
ed:
")
;
name="
Progr
ami
z";
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){ /
/const
ruct
ori
sinv
okedwhi
l
e
/
/cr
eat
inganobj
ectoft
heMai
ncl
ass
Mai
nobj
=newMai
n()
;
Sy
stem.
out
.pr
int
ln(
"Thenamei
s"+obj
.name)
;
}
}
Out
put
:Const
ruct
orCal
l
ed:
Thenamei
sPr
ogr
ami
z
Intheaboveexampl
e,wehavecreatedaconst
ruct
ornamedMai
n()
.Insi
det
he
constr
uctor
,wearei
nit
ial
i
zingt
hev alueoft
henamevari
abl
e.
Not
icet
hest
atementofcr
eat
inganobj
ectoft
heMai
ncl
ass.
Mai
nobj
=newMai
n()
;
Her
e,whentheobjecti
screated,
theMai
n()const
ruct
ori
scal
l
ed.And,
thev
alueof
t
henamev ar
iabl
eisini
ti
ali
zed.
Hence,
thepr
ogr
am pr
int
sthev
alueoft
henamev
ari
abl
esasPr
ogr
ami
z.
====================================================================
==============
Ty
pesofJav
aconst
ruct
ors
Ther
ear
etwot
ypesofconst
ruct
orsi
nJav
a:
1. Def
aul
tconst
ruct
or
2. No-
argconst
ruct
or
3. Par
amet
eri
zedconst
ruct
or

1)Def
aul
tConst
ruct
or:
A) I fwedonotcr eateanyconstr
uctor
,theJavacompi
lerautomati
cal
l
ycreatea
no-
argconstr
uctorduringtheexecut
ionoftheprogr
am.Thisconstr
uct
oriscal
led
def
aultconst
ruct
or.
B) Youwoul dnotfi
ndthi
sconstr
uctorinyoursour
cecodemeansin.jav
af i
l
e,i
t
wouldbei
nsert
edintocodedur
ingcompilat
ionandexist
sin.
classf
il
e.C)This
Constr
uct
ornotvi
sibl
etoProgr
ammer .

2)No-
argConst
ruct
or:
A) Const r
uctorwit
hnoargumentscal
ledno-
argConst
ruct
or.OrI
faconstr
uct
or
doesnotacceptanyparamet
ers,
iti
sknownasano-argumentconst
ruct
or.
B) Thesi gnatureissameasdefaul
tconst
ructor
,howeverbodycanhav
eany
codeunl
i
kedefaultconst
ruct
orwherebodyoftheconst
ruct
orempty.
C) I fy
ouwrit
epubl
icDemo(){}i
nyourcl
assDemoi
tcannotbecal
l
eddef
aul
t
const
ruct
orsi
nceyouhavewr
it
tenthecodeofi
t.
D) Thi
sConst
ruct
orVi
sibl
etoPr
ogr
ammer
.
-
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
Exampl
e:
Cl
assDemo
{
Publ
i
cDemo(
)
{
Sy
stem.
out
.pr
int
ln(
“Thi
sisanoar
gumentconst
ruct
or”
);
}
Publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)
{
NewDemo(
);
}
}

Out
put
:Thi
sisanoar
gumentconst
ruct
or.

3)Par
amet
eri
zedConst
ruct
or:
A) Const ruct
orwi
thar
gument
s(Par
amet
ers)i
sknownasPar
amet
eri
zed
Const
ruct
or.
B) Wecanpassmul
ti
plear
gument
ssamet
ime.cl
assMai
n{
St
ri
ngl
anguages;
/
/const
ruct
oraccept
ingsi
ngl
eval
ue
Mai
n(St
ri
ngl
ang){
l
anguages=l
ang;
Sy
stem.
out
.pr
int
ln(
languages+"Pr
ogr
ammi
ngLanguage"
);
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
/
/cal
lconst
ruct
orbypassi
ngasi
ngl
eval
ue
Mai
nobj
1=newMai
n("
Jav
a")
;
Mai
nobj
2=newMai
n("
Pyt
hon"
);
Mai
nobj
3=newMai
n("
C")
;
}
}
Out
put
:
Jav
aPr
ogr
ammi
ngLanguage
Py
thonPr
ogr
ammi
ngLanguage
CPr
ogr
ammi
ngLanguage

Di
ff
erencebet
weenMet
hodandConst
ruct
or

Const
ruct
or Met
hod

1)Constr
uct
ori
susedt
oini
ti
ali
zean 1) Met hod is used to exhi
bit
s
object funct
ional
it
yofanobj
ect

2)Noneedtocal
li
fnotcalledthen 2)Needt
ocal
l
(ifnotcal
l
edt
henno
ther
ewil
lbedef
aultconst
ructor. run)
3)Constr
uct
or does not r
etur
n any 3)Met
hodhasr
etur
nty
pe
valuenotev
envoid

4)Name oft
he const
ruct
ormustbe 4)
Inmet
hodsnosuchr
equi
rement
s
samewit
hthenameoftheclass

5)
Wecannotov
err
ideConst
ruct
or 5)Met
hodov
err
idi
ngpossi
ble.
6)Const
ruct
orsar
enoti
nher
it
ed 6)Non-
stat
icmet
hodsar
einher
it
ed.
7)Aconst
ructorcanbecal
l
edusi
ng 7)met hodcanbecal l
edusingobject
newkeyword (Non st at
ic met hods ) or cl ass
ref
erence ( Stati
c met hods) or by
name
8) A constructor can callanot her8) Met hod can callot her method
constr
uct
or usi ng this(
) or super()dir
ectl
y or usi ng class or obj ect
Keyword ref
erence.
9) A constructor cannot be stati
c,9)Met hodcanbest ati
c,abstr
act,f
inal
abstr
act,f
inal,
nativ
eorsy nchr
onized andnat i
veorSynchroni
zed.

Sect
ion-
2:(
OOPsConcept
)
1) I
nher
it
ance
2) Pol
ymor
phi
sm
3) Abst
ract
ion
4) Encapsul
ati
on

1)I
nher
it
ance:
A) I nher
it
ancei
tisoopspr
inci
plewher
eonecl
assacqui
redt
hepr
oper
tyofot
her
cl
ass.
B) Thecl
assf
rom whi
chpr
oper
tyacqui
redori
nher
it
siscal
l
edSuperorPar
ent
Cl
ass.
C) Thecl
assi
nwhi
chpr
oper
tyar
edel
i
ver
edi
scal
l
edSubCl
assorChi
l
dCl
ass.
D) ForI
nher
it
anceext
endskey
wor
dused.

Ty
pesofI
nher
it
ance:
A) Si
ngl
eLev
elI
nher
it
ance
B) Mul
tiLev
elI
nher
it
ance
C) Mul
ti
pleI
nher
it
ance
D) Hi
erar
chi
cal
Inher
it
ance
E) Hy
bri
dInher
it
ance

1)Si
ngl
eLev
elI
nher
it
ance
Singl
eLeveli
nheri
tanceiseasytounderst
and.Whenacl assextendsanotherone
classonl
ythenwecal l
itasingl
eLeveli
nheri
tance.Thebelowfl
owdi agram shows
thatcl
assBextendsonlyoneclasswhichisA.HereAi saparentclassofBandB
wouldbeachildcl
assofA.

Exampl
e:
Cl
assA{
publ
i
cvoi
dmet
hodA(
){
Sy
stem.
out
.pr
int
ln(
"Basecl
assmet
hod"
);
}
}
Cl
assBext
endsA{
publ
i
cvoi
dmet
hodB(
){
Sy
stem.
out
.pr
int
ln(
"Chi
l
dcl
assmet
hod"
);
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Bobj
=newB(
);
obj
.met
hodA(
); /
/cal
l
ingsupercl
assmet
hod
obj
.met
hodB(
); /
/cal
l
ingl
ocal
met
hod
}
}
==============================================================
========
2)Mul
ti
-l
evelI
nher
it
ance
A)I
nmulti
-Lev
eli
nher
it
anceonesubcl
assacqui
redtheproper
tyofsuperor
Par
ent Cl
asswhichal
soacqui
redpr
oper
tyofanot
hersubclass.
B)Inwhi
chmi
nimum t
wosubcl
assesar
erequi
redt
oper
for
mingmul
ti
-l
evel
i
nher
it
ance.

Exampl
e:
Cl
assA{
publ
i
cvoi
dmet
hodA(
){
Sy
stem.
out
.pr
int
ln(
"Cl
assAmet
hod"
);
}
}
Cl
assBext
endsA
{
publ
i
cvoi
dmet
hodB(
)
{
Sy
stem.
out
.pr
int
ln(
"cl
assBmet
hod"
);
}
}
Cl
assCext
endsB
{
publ
i
cvoi
dmet
hodC(
)
{
Sy
stem.
out
.pr
int
ln(
"cl
assCmet
hod"
);
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Cobj
=newC(
);
obj
.met
hodA(
); /
/cal
l
inggr
andpar
entcl
assmet
hod
obj
.met
hodB(
); /
/cal
l
ingpar
entcl
assmet
hod
obj
.met
hodC(
); /
/cal
l
ingl
ocal
met
hod
}
}

3)Mul
ti
pleI
nher
it
ance:
A)Whenonecl
assext
endsmor
ethanonecl
assest
hent
hisi
scal
l
edmul
ti
ple
i
nher
it
ance.
Forexampl
e:
Cl
assCextendscl
assAandBt
hent
hist
ypeofi
nher
it
ancei
sknownas
mul
ti
plei
nher
it
ance.
B)Mul
ti
plei
nher
it
ancenotsuppor
tedi
nJav
abecauseof“
DiamondAmbi
gui
ty”
Pr
obl
em.

C) I nabov
edi
agram Cl
assCextendsBot
hCl
assAandCl
assBandi
n
bot
hcl
asshav
esamemethodnamedispl
ay().
D) NowJav
aCompi
l
ercannotdeci
de,
whi
chdi
spl
ay(
)met
hodi
tshoul
d
i
nher
it
.
E) Sopr
eventsuchsi
tuat
ionmul
ti
plei
nher
it
ancenotsuppor
tedi
njav
a.
==============================================================
=============
4)Hi
erar
chi
calI
nher
it
ance
Whenaclasshasmor ethanonechi
ldcl
asses(subclasses)ori
not
herwor
ds,
morethanonechi
ldcl
asseshav ethesamepar
entcl
ass,thensuchkindof
i
nheri
tancei
sknownashierarchi
cal.

I
fwetal
kaboutthefl
owchar
t,ClassBandCar
ethechi
l
dcl
asseswhi
char
e
i
nher
it
ingf
rom t
heparentcl
assi
.eClassA.
Let
’sseet
hesy
ntaxf
orhi
erar
chi
cal
inher
it
ancei
nJav
a:
Cl
assA{
-
--
}
Cl
assBext
endsA{
-
--
}
Cl
assCext
endsA{
-
--
}
==============================================================
=============
5)Hy
bri
dInher
it
ance:
Hy bri
dinher
it
anceisacombi nat
ionofmul t
ipl
einher
itanceandmul t
il
evel
i
nheri
tance.Sincemult
ipl
einheri
tanceisnotsupport
edinJav aasitleadst
o
ambigui
ty,sothist
ypeofinheri
tancecanonlybeachievedthroughtheuseoft he
i
nter
faces.
Di
agr
am f
orr
efer
ence:

I
fwet
alkaboutt
hef
lowchar
t,cl
assAi
sapar
entcl
assf
orcl
assBandC,wher
eas
Cl
assBandCar
ethepar
entcl
assofDwhi
chi
stheonl
ychi
l
dcl
assofBandC.

2)Pol
ymor
phi
sm
Pol
y=manyandmor
phi
sm =f
orm
>Pol
ymor
phi
sm i
stheconceptwher
eanobj
ectbehav
esdi
ff
erent
lyi
ndi
ff
erent
si
tuat
ions.
>Whenoneobj
ectorel
ementper
for
msdi
ff
erentbehav
iour
satdi
ff
erentst
agesof
l
i
fecy
clei
scal
l
edPol
ymor
phi
sm.
>Pol
ymor
phi
sm meanst
aki
ngmanyf
orms,wher
e‘pol
y’meansmanyand‘
mor
ph’
meansf
orms.
I
tist
heabi
l
ityofav
ari
abl
e,f
unct
ionorobj
ectt
otakeonmul
ti
plef
orms.I
not
her
wor
ds,pol
ymor
phi
sm al
l
owsy
oudef
ineonei
nter
faceormet
hodandhav
emul
ti
ple
i
mpl
ement
ati
ons.

Pol
ymor
phi
sm i
nJav
aisoft
wot
ypes:
1. Compi
l
eti
mepol
ymor
phi
sm
2. Runt
imepol
ymor
phi
sm

1)Compi
leTi
mePol
ymor
phi
sm
>I
ncompi
l
eti
mepol
ymor
phi
sm met
hoddecl
arat
iongetbi
ndedt
oit
sdef
ini
ti
on(
body
)
att
het
imeofcompi
l
ati
onbasedonPar
amet
erorAr
gument
siti
scal
l
ed“
Compi
l
e
Ti
mePol
ymor
phi
sm”
.
>Wecanachi
evebyusi
ngmet
hodov
erl
oadi
ng
>Met
hodOv
erl
oadi
ngwi
l
lbeper
for
mingi
n
SameCl
assonl
y.
>SameMet
hodName
>butdi
ff
erentAr
gument
sorPar
amet
er
Exampl
e:
Ther
ear
e3Way
sofMet
hodOv
erl
oadi
ng:
1.
Changenumberofpar
amet
ers
2.
Dat
aty
peofpar
amet
ers
3.
Orderofpar
amet
ers

1)ChangeNumberofPar
amet
ers
Bychangi
ngt
henumberofpar
amet
ersy
oucanachi
evemet
hodov
erl
oadi
ng.
Forexampl
e:
add(
int,
int
) /
/twopar
amet
ers
add(
int
,int
,int
) /
/thr
eepar
amet
ersPr
act
ical
Exampl
e:

cl
assMet
hodOv
erl
oadi
ngExampl
e{
publ
i
cvoi
dshow(
Str
ings)
{
Sy
stem.
out
.pr
int
ln(
s);
}
publ
i
cvoi
dshow(
inti
,St
ri
ngs)
{
Sy
stem.
out
.pr
int
ln(
i+""+s)
;
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Met
hodOv
erl
oadi
ngExampl
eol
=newMet
hodOv
erl
oadi
ngExampl
e()
;
ol
.show(
"Bei
nPr
esent
");
ol
.show(
10,
"Bei
nPr
esent
");
}
}
Out
put
:
"
Bei
nPr
esent
"
10"
Bei
nPr
esent
"
I
ntheabov
eexampl
e,show (
)met
hodi
sov
erl
oadedbasedont
henumberof
par
amet
ers.
Bot
hshow(
)met
hodshav
edi
ff
erentpar
amet
ers.Onei
saccept
ingSt
ri
ngt
ypewhi
l
e
ot
heri
saccept
ingi
ntandSt
ri
ngpar
amet
ers.

2.Dat
aty
peofpar
amet
ers:
Met
hodov
erl
oadi
ngcanbeachi
evedbychangi
ngt
hedat
aty
peofpar
amet
ers.
Forexampl
e:
add(
int,
int
)
add(
int
,fl
oat
)
Pr
act
ical
Exampl
e:
cl
assMet
hodOv
erl
oadi
ngExampl
e{
publ
i
cvoi
dshow(
Str
ings)
{
Sy
stem.
out
.pr
int
ln(
s);
}
publ
i
cvoi
dshow(
inti
)
{
Sy
stem.
out
.pr
int
ln(
i+""+s)
;
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Met
hodOv
erl
oadi
ngExampl
eol
=newMet
hodOv
erl
oadi
ngExampl
e()
;
ol
.show(
"Bei
nPr
esent
");
ol
.show(
10)
;
}
}
Out
put
:
"
Bei
nPr
esent
"
10
I
ntheabov
eexampl
emet
hodov
erl
oadi
ngi
sdonebychangi
ngt
hedat
aty
peoft
he
par
amet
ers.
Oneshow (
)met
hodi
saccept
ingSt
ri
ngpar
amet
erwhi
l
eot
hershow (
)met
hodi
s
accept
ingi
ntpar
amet
er.

3.Or
derofpar
amet
ers:
Met
hodov
erl
oadi
ngcanbedonebychangi
ngt
heor
derofpar
amet
ers.
Forexampl
e:
add(
fl
oat,
int
)
add(
int
,fl
oat
)
Pr
act
ical
Exampl
e

cl
assMet
hodOv
erl
oadi
ngExampl
e{
publ
i
cvoi
dshow(
Str
ings,
inti
)
{
Sy
stem.
out
.pr
int
ln(
s+""+i
);
}
publ
i
cvoi
dshow(
inti
,St
ri
ngs)
{
Sy
stem.
out
.pr
int
ln(
i+""+s)
;
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Met
hodOv
erl
oadi
ngExampl
eol
=newMet
hodOv
erl
oadi
ngExampl
e()
;
ol
.show(
"Bei
nPr
esent
",10)
;
ol
.show(
15,
"Al
i
vei
sAwesome"
);
}
}
Out
put
:
"
Bei
nPr
esent
"10
10"
Bei
nPr
esent
"
I
ntheabov
eexampl
ebot
hshow(
)met
hodshav
edi
ff
erentsequenceofdat
aty
peof
par
amet
ers.
Si
ncet
hef
ir
stshow (
)met
hodhaspar
amet
ers(
int
,St
ri
ng)andsecondshow (
)
met
hodhaspar
amet
ers(
Str
ing,
int
).
Theabov
ecasei
sav
ali
dmet
hodov
erl
oadi
ng.

2)RunTi
mePol
ymor
phi
sm (
Dynami
cPol
ymor
phi
sm)
>Whenmet
hoddecl
arat
ionbi
ndedwi
thi
tsdef
ini
ti
on(
Body
)att
het
imeofexecut
ion
(
Run)basedonobj
ectandi
nst
ancei
tiscal
l
edas“
RunTi
mePol
ymor
phi
sm”
.
>”
Met
hodOv
err
idi
ng”i
sexampl
eofRunTi
mePol
ymor
phi
sm.
Wecanachi
ever
unt
imepol
ymor
phi
sm byusi
ngmet
hodov
err
idi
ng
Met
hodOv
err
idi
ngMeans
Ther
eissamemet
hodname,
samear
gs,
ISAi
nher
it
anceandcl
assi
sdi
ff
erent
Exampl
e:
publ
i
ccl
assPar
ent
Class{
/
/Ov
err
iddenmet
hod
publ
i
cvoi
dpr
int
Dat
a()
{
Sy
stem.
out
.pr
int
ln(
"I
nthi
smet
hodwear
eshowi
ngt
hedet
ail
sofPar
entcl
ass"
);
}
}
publ
i
ccl
assChi
l
dCl
assext
endsPar
ent
Class
{
/
/Ov
err
idi
ngmet
hod
publ
i
cvoi
dpr
int
Dat
a()
{
Sy
stem.
out
.pr
int
ln(
"I
nthi
smet
hodwear
eshowi
ngt
hedet
ail
sofchi
l
dcl
ass"
);
Sy
stem.
out
.pr
int
ln(
"Wear
eov
err
idi
ngt
hemet
hod"
);
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
]){
Par
ent
Classpar
ent
Obj
ect=newChi
l
dCl
ass(
); /
/Thi
swi
l
lcal
lthechi
l
d
cl
assmet
hod
par
ent
Obj
ect
.pr
int
Dat
a()
;
}
}
Out
put
:
I
nthi
smet
hodwear
eshowi
ngt
hedet
ail
sofchi
l
dcl
assWear
eov
err
idi
ngt
he
met
hod
-
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

I
mpor
tantQuest
ions:
Q1.Whati
sdi
ff
erencebet
weenOv
erl
oadi
ngandOv
err
idi
ng?

Met
hodOv
erl
oadi
ng Met
hodOv
err
idi
ng
1)Met
hodov
erl
oadi
ngi
sacompi
l
e 1. Met
hod over
ri
ding is
ti
mepoly
mor
phi
sm. a r
un timepol
ymorphi
sm.

2.Ithel
pstor
aiset
her
eadabi
l
ityoft
he 2.Whilei
tisusedtograntt
hespecifi
c
program. i
mplementati
onoft hemethodwhi ch
i
salreadyprovi
dedbyitsparentcl
ass
orsupercl
ass.
3.I
tisoccurwi
thi
nthecl
ass. 3.Whil
eitisperf
ormedintwocl
asses
wit
hinheri
tancerel
ati
onshi
p.

4.Methodover
loadi
ngmaynotr
equi
re 4.Whil
emethodover
ri
dingal
way
s
i
nheri
tance. needsi
nher
it
ance.

5.I
nthi
s,methodsmusthav
esame 5.Whi
lei nt hi
s,methods musthav e
nameanddif
ferent same name and same
si
gnat
ure/
Declarat
ion. si
gnature/
Declarat
ion but dif
ferent
Defi
nit
ion(
Body )
6.Inmethodoverl
oading,r
etur
nty
pe 6.Whi
l
eint
his,
ret
urnt
ypemustbe
canorcannotbesame,butwemust sameorco-
vari
ant.
havet
ochangetheparameter
.

Q2)Canweov
erl
oadMai
nMet
hod?
>Socanweov
erl
oadmai
nmet
hodi
nJav
a?
Answeri
sYes,
Wecan.
>Execut
ionofaJav
apr
ogr
am st
art
sfr
om mai
n()met
hod.
I
nfactweshoul
dsayt
hatExecut
ionofaJav
apr
ogr
am st
art
sfr
om amai
n()met
hod
whoseact
ual
synt
axi
s“publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)
”.
>Wecanwr
it
emul
ti
plev
ali
dov
erl
oadedmai
nmet
hodi
nacl
assbutJVM al
way
s
l
ooksf
oramai
nmet
hodwi
thsy
ntaxas“
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)
“.
I
fitf
inds,i
twi
l
lst
artexecut
ionf
rom t
her
eot
her
wisewi
l
lgi
veer
rorst
ati
ng“
Err
or:
Coul
dnotf
indorl
oadmai
n“.

Pr
act
icalExampl
e:
publ
i
ccl
assOv
erl
oadedMai
nMet
hod{
/
/ov
erl
oadedmai
nmet
hod
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngst
r)
{
Sy
stem.
out
.pr
int
ln(
"publ
i
cst
ati
cvoi
dmai
n(St
ri
ngst
r)"
);
}
/
/Ov
erl
oadedmai
nmet
hod
publ
i
cst
ati
cintmai
n(i
ntst
r)
{
Sy
stem.
out
.pr
int
ln(
"publ
i
cst
ati
cvoi
dmai
n(St
ri
ngst
r)"
);
r
etur
n1;
}
/
/ov
erl
oadedmai
nmet
hod
publ
i
cvoi
dmai
n(St
ri
ngst
r,i
ntv
al)
{
Sy
stem.
out
.pr
int
ln(
"publ
i
cvoi
dmai
n(St
ri
ngst
r,i
ntv
al)
");
}
/
/Mai
nmet
hodf
rom wher
eexecut
ionst
art
s
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)
{
Sy
stem.
out
.pr
int
ln(
"publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)
");
/
/Cal
l
ingot
hermai
nmet
hod
mai
n("
Bhar
at"
);
mai
n(10)
;
newOv
erl
oadedMai
nMet
hod(
).
mai
n("
Bhar
at"
,10)
;
}
}

2)Canweov
erl
oadst
ati
cMet
hod?
Yes,wecanov
erl
oadt
hest
ati
cmet
hod.Acl
asscanhav
emor
ethanonest
ati
c
met
hodwi
tht
hesamename,
butdi
ff
erenti
ninputpar
amet
ers.Youcanov
erl
oadt
he
st
ati
cmet
hodbychangi
ngt
henumberofar
gument
sorbychangi
ngt
het
ypeof
ar
gument
s.

Exampl
e:
publ
i
ccl
assMet
hodOv
erl
oadi
ngOf
Stat
icMet
hod
{
publ
i
cst
ati
cvoi
dshow(
Str
ingname)
{
Sy
stem.
out
.pr
int
ln(
"Nameofper
son="
+name)
;
}
publ
i
cst
ati
cvoi
dshow(
intage)
{
Sy
stem.
out
.pr
int
ln(
"Per
sonagei
s="
+age)
;
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
/
/Ifuserpr
ovi
dingpar
amet
erofSt
ri
ngt
ypet
henf
ir
stmet
hodcal
l
ed
Met
hodOv
erl
oadi
ngOf
Stat
icMet
hod.
Show(
"Ram"
);
/
/Ifuserpr
ovi
dingpar
amet
erofi
ntt
ypet
hensecondmet
hodcal
l
ed
Met
hodOv
erl
oadi
ngOf
Stat
icMet
hod.
Show(
18)
;
}
}
Out
put
:Nameofper
son=Ram
Per
sonagei
s=18

3)Canweov
err
ideFi
nalMet
hods?
>Amet
hoddecl
aredwi
tht
hef
inalkey
wor
d,andt
heni
tisknownast
hef
inalmet
hod.
Thef
inal
met
hodcan’
tbeov
err
idden.
>Af
inalmet
hoddecl
aredi
nthePar
entcl
asscannotbeov
err
iddenbyachi
l
dcl
ass.I
f
wet
ryt
oov
err
idet
hef
inalmet
hod,t
hecompi
l
erwi
l
lthr
owanexcept
ionatcompi
l
e
t
ime.Becausei
fwear
edecl
ari
ng anymet
hod wi
tht
hef
inalkey
wor
d,wear
e
i
ndi
cat
ingt
heJVM t
opr
ovi
desomespeci
alat
tent
ionandmakesur
enoonecan
ov
err
idei
t.
>f
inali
sakey
wor
dinj
avaused f
orr
est
ri
cti
ng somef
unct
ional
i
ties.I
fwear
e
decl
ari
ng any met
hod wi
th f
inal key
wor
d i
t means we can’
t change i
ts
i
mpl
ement
ati
oni
nchi
l
dcl
ass.So,
Jav
adoesn’
tper
mitt
oov
err
ideanyf
inal
met
hod.

Exampl
e:
publ
i
ccl
assPar
ent
{
/
/fi
nal
met
hodi
nbasecl
ass
f
inal
voi
dshowDat
a()
{
Sy
stem.
out
.pr
int
ln(
"Thi
sisSt
ati
cmet
hodofPar
entcl
ass"
);
}
}
publ
i
ccl
assChi
l
dext
endsPar
ent
{
/
/fi
nal
met
hodi
ndr
ivedcl
ass
f
inal
voi
dshowDat
a()
{
Sy
stem.
out
.pr
int
ln(
"Thi
sisSt
ati
cmet
hodofchi
l
dcl
ass"
);
}
}
publ
i
ccl
assMai
nCl
ass{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
Par
entpar
ent=newChi
l
d()
;
par
ent
.showDat
a()
;
}
}
Out
put
:Theabov
eexampl
ewi
l
lshowcompi
l
ati
oner
ror

Q.
4Canweov
err
ideSt
ati
cMet
hod?
>Wecannotov
err
ideSt
ati
cMet
hod.
>I
fyouhav
east
ati
cmet
hodi
nPar
entcl
assandy
oudef
ini
ngast
ati
cmet
hodwi
th
samesi
gnat
ureasast
ati
cmet
hodi
nPar
entcl
ass.I
nthi
scase,t
heChi
l
dcl
ass
met
hodwoul
dactdi
ff
erent
ly.I
tisknownasmet
hodhi
ding.
Pr
act
icalExampl
e:
publ
i
ccl
assPar
ent{
/
/St
ati
cmet
hodi
nbasecl
ass
st
ati
cvoi
dshowDat
a()
{
Sy
stem.
out
.pr
int
ln(
"Thi
sisSt
ati
cmet
hodofPar
entcl
ass"
);
}
}
publ
i
ccl
assChi
l
dext
endsPar
ent
{
/
/st
ati
cmet
hodi
nder
ivedcl
ass
st
ati
cvoi
dshowDat
a()
{
Sy
stem.
out
.pr
int
ln(
"Thi
sisSt
ati
cmet
hodofchi
l
dcl
ass"
);
}
}
publ
i
ccl
assMai
nCl
ass{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)
{
Par
entpar
ent=newChi
l
d()
;
par
ent
.showDat
a()
;
}
}
Out
put
:Thi
sisSt
ati
cmet
hodofPar
entcl
ass

Asy
ouknowSt
ati
cmet
hodcandi
rect
lybecal
l
edwi
thcl
assname.I
nthi
sexampl
e
wear
ecal
l
ing showDat
a()met
hod byr
efer
enceofPar
entcl
asst
hencompi
l
er
conv
ert
s.

3)ABSTRACTI
ON
=I
tmeanshi
ding t
hei
mpl
ement
ati
on and showi
ng t
heser
vicet
hathasbeen
pr
ovi
ded.
=Ex.
Car,
ATM
=Ther
ear
e2way
stoachi
eveabst
ract
ion
=ByAbst
ractcl
ass(
0-100%)
=ByI
nter
face(
100%)
=I
tcont
ainsabst
ract&concr
etemet
hod.
=Abst
ractmet
hoddon'
thav
ebodyandconcr
etemet
hodhav
ebody.
=Asbot
hmet
hodsar
eusedi
nit
,iti
spar
ti
all
yabst
ract
ed henceabst
ract
ioncanbe
achi
evedf
rom 0 t
o100%.
=Wedon'
tcr
eat
eobj
ectofabst
ractcl
ass,
wecr
eat
eref
erenceofi
t.
=Weuseext
endskey
wor
dfori
nher
it
ance.
=ov
err
idi
ngcanbedoneher
e.
=whenmet
hodabst
ractt
hencl
asscanal
sobeabst
ract.
=Butt
her
ecanbeabst
ractaswel
lasConcr
etemet
hodi
nabst
ractcl
ass.

ByAbst
ractCl
ass(0-100%)
Exampl
e:
abst
ractcl
assBi
ke{
abst
ractv
oidr
un(
);
}
cl
assHonda4ext
endsBi
ke{
v
oidr
un(
){
Sy
stem.
out
.pr
int
ln(
"runni
ngsaf
ely
");
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)
{
Bi
keobj
=newHonda4(
);
obj
.r
un(
);
}
}
Out
put:ngr
unni
ngsaf
ely
ByI
nter
face(100%)
=I
nter
facecont
ainsonl
yabst
ractmet
hodsoabst
ract
ioncanbeachi
eved100%.
=wedon’
tcr
eat
eobj
ect,
wecr
eat
eref
erence.
=byi
nter
facewecanachi
evemul
ti
plei
nher
it
ance.
=Her
eweusei
mpl
ementkey
wor
d.
=v
ari
abl
eini
nter
facei
spubl
i
cst
ati
cfi
nal
.
Exampl
e:
Publ
i
cInt
erf
aceI
1
{
Voi
dshow(
); /
/abst
ractmet
hod
}
Publ
i
cInt
erf
aceI
2
{
Voi
ddi
spl
ay(
);
}
Publ
i
ccl
assI
mpl
ementI
1,I
2
{
Publ
i
cvoi
dshow(
)
{
Sy
stem.
out
.pr
int
ln(
“1”
);
}
Publ
i
cvoi
ddi
spl
ay(
)
{
Sy
stem.
out
.pr
int
ln(
“2”
);
}
Publ
i
cst
ati
cvoi
dmai
n(st
ri
ng[
]ar
gs)
{
Testa=newt
est(
);
a.
Show(
);
a.
displ
ay(
);
}
}
Di
ff
erencebet
weenabst
ractcl
assandi
nter
face
Srno Abst
ractcl
ass i
nter
face

1 Abst
ractcl
asscanhav
eabst
ract I
nter
face can hav
e onl
y abst
ract
andnon-
abst
ractmet
hods. met
hods.Si
nceJav
a8,i
tcanhav
e
def
aul
tandst
ati
cmet
hodsal
so.
2 Abst
ract cl
ass doesn'
t suppor
t I
nter
face suppor
ts mul
ti
ple
mul
ti
plei
nher
it
ance. i
nher
it
ance.
3 Abst
ractcl
asscanhav
efi
nal
,non- I
nter
face has onl
yst
ati
c and f
inal
f
inal
, st
ati
c and non-
stat
ic v
ari
abl
es.
v
ari
abl
es.
4 Abst
ractcl
ass can pr
ovi
de t
he I
nter
face can'
t pr
ovi
de t
he
i
mpl
ement
ati
onofi
nter
face. i
mpl
ement
ati
onofabst
ractcl
ass.
5 Theabst
ractkey
wor
disusedt
o The i
nter
face key
wor
dis used t
o
decl
areabst
ractcl
ass. decl
arei
nter
face.
6 An abst
ract cl
ass can ext
end An i
nter
face can ext
end anot
her
anot
herJav
acl
assandi
mpl
ement Jav
aint
erf
aceonl
y.
mul
ti
pleJav
aint
erf
aces.
7 Anabst
ractcl
asscanbeext
ended An i
nter
face can be i
mpl
ement
ed
usi
ngkey
wor
d"ext
ends"
. usi
ngkey
wor
d"i
mpl
ement
s".
8 A Jav
a abst
ractcl
ass can hav
e Member
s ofa Jav
aint
erf
ace ar
e
cl
ass member
s l
i
ke pr
ivat
e, publ
i
cbydef
aul
t.
pr
otect
ed,
etc.
9 Exampl
e: Exampl
e:
publ
i
cabst
ractcl
assShape{ publ
i
cint
erf
aceDr
awabl
e{
publ
i
cabst
ractv
oiddr
aw(
); v
oiddr
aw(
);
} }
10 We achi
eve ( 0 – 100 % ) Weachi
eve(100%)abst
ract
ion.
abst
ract
ion
4)Encapsul
ati
on
I
tisamechani
sm ofwr
appi
ngmet
hodsandv
ari
abl
esi
nasi
ngl
euni
t.
Wecanachi
eveanencapsul
ati
onbyt
woway
s:-
1.Bykeepi
ngcl
assaspr
ivat
ei.
e.dat
ahi
ding.
2.Bydecl
ari
ngpubl
i
cget
terandset
termet
hodf
orv
iewi
ngandmodi
fyi
ngt
hedat
a.
I
tisusedf
orbanki
ngt
ransact
ionsasdat
ahi
dingi
sdonef
orsecur
it
ypur
pose.The
di
sadv
ant
ageofEncapsul
ati
oni
sev
eryt
imewehav
etodecl
areget
terandset
ter
met
hod due t
o whi
ch t
he l
engt
h oft
he code i
ncr
eases and i
taf
fect
sthe
per
for
manceofanappl
i
cat
ionl
eadi
ngi
ttowor
ksl
owl
y.

Exampl
e:
publ
i
ccl
assSt
udent
{
/
/Forencapsul
ati
onal
lvar
iabl
esshoul
dbepr
ivat
e
pr
ivat
eintr
oll
No;
pr
ivat
eSt
ri
ngname;
pr
ivat
eSt
ri
ngcl
assName;
/
/Youshoul
dpr
ovi
deset
terandget
ter
sforv
ari
abl
es
publ
i
cintget
Rol
l
No(
){
r
etur
nrol
l
No;
}
publ
i
cSt
ri
ngget
Name(
){
r
etur
nname;
}
publ
i
cSt
ri
ngget
ClassName(
){
r
etur
ncl
assName;
}
publ
i
cvoi
dset
Rol
l
No(
intv
alue)
{
r
oll
No=v
alue;
}
publ
i
cvoi
dset
Name(
Str
ingv
alue)
{
name=v
alue;
}
publ
i
cvoi
dset
ClassName(
Str
ingv
alue)
{
cl
assName=v
alue;
}
}
publ
i
ccl
assEncapsul
ati
onEx
ampl
e{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
St
udentobj
=newSt
udent(
);
obj
.set
Rol
l
No(
1);
obj
.set
Name(
"RAVI
")
;
obj
.set
ClassName(
"MCA"
);
Sy
stem.
out
.pr
int
ln(
"St
udentRol
l
No:
"+obj
.get
Rol
l
No(
));
Sy
stem.
out
.pr
int
ln(
"St
udentName:
"+obj
.get
Name(
));
Sy
stem.
out
.pr
int
ln(
"St
udentCl
ass:
"+obj
.get
ClassName(
));
}
}

Out
put
:
St
udentRol
l
No:
1
St
udentName:
RAVI
St
udentCl
ass:
MCA

Jav
aSt
ri
ng
I
nJava,str
ingisbasi
cal
lyanobj
ectthatrepr
esent
ssequenceofcharv
alues.
Anar
rayofcharacter
sworkssameasJav astr
ing.
Forexampl
e:
1. char
[]ch={
'j
'
,'
a'
,'
v'
,'
a'
,'
t
',
'p'
,
'o'
,
'i
'
,'
n'
,'
t'
};
2. St
ri
ngs=newSt
ri
ng(
ch)
;
i
ssameas:
1. St
ri
ngs="
jav
a";
JavaSt
ringclasspr
ovidesalotofmethodstoperform operat
ionsonstr
ings
suchascompare()
,concat
(),
equals()
,spl
i
t()
,lengt
h()
,replace(
),compareTo(
),
i
nter
n()
,subst
ri
ng()etc.

Char
SequenceI
nter
face
TheCharSequenceint
erf
aceisusedtorepr
esentt
hesequenceofchar
act
ers.
St
ri
ng,Str
ingBuf
ferandStri
ngBui
ldercl
assesimpl
ementit
.Itmeans,
wecancreat
e
st
ri
ngsinJavabyusingthesethr
eeclasses.
TheJav
aSt
ri
ngi
simmut
abl
ewhi
chmeansi
tcannotbechanged.Whenev
er
wechangeanyst
ri
ng, anewinst
anceiscr
eat
ed.Formut
abl
est
ri
ngs,
youcanuse
St
ri
ngBuff
erandStr
ingBuil
dercl
asses.
Wewil
ldi
scussimmutabl
estr
inglat
er.Let
'sf
ir
stunder
standwhatSt
ri
ngi
n
Jav
aisandhowtocreatet
heStr
ingobject
.
Whati
sSt
ri
ngi
nJav
a?
General
ly
,Stri
ngisasequenceofcharacter
s.ButinJava,
str
ingi
sanobject
thatr
epresentsasequenceofcharact
ers.Thejava.
lang.
Str
ingcl
assisusedt
o
creat
east r
ingobject.
Howt
ocr
eat
east
ri
ngobj
ect
?
Ther
ear
etwoway
stocr
eat
eSt
ri
ngobj
ect
:
1. Byst
ri
ngl
i
ter
al
2. Bynewkey
wor
d

1)St
ri
ngLi
ter
al
Jav
aSt
ri
ngl
i
ter
ali
scr
eat
edbyusi
ngdoubl
equot
es.ForExampl
e:
1. St
ri
ngs="
wel
come"
;
Eachti
mey oucreat
east ri
ngli
ter
al,
theJVM checksthe"str
ingconstantpool
"
fi
rst.Ifthestr
ingal
readyexi
stsinthepool,
arefer
encetothepooledinstanceis
returned.Ift
hestri
ngdoesn'texi
stint
hepool,anewstri
nginstanceiscreatedand
placedi nthepool
.Forexampl e:
1. St
ri
ngs1="
Wel
come"
;
2. St
ri
ngs2="
Wel
come"
; /
/Itdoesn'
tcr
eat
eanewi
nst
ance
I
ntheabov eexample,onlyoneobjectwil
lbecreated.Firstl
y,JVM wil
lnotfi
nd
anystri
ngobjectwiththevalue"Welcome"instr
ingconst antpoolthatiswhyitwil
l
creat
eanewobj ect.Aftert
hatitwil
lfi
ndthestri
ngwitht hev al
ue"Wel come"inthe
pool,
itwil
lnotcreat
eanewobj ectbutwil
lret
urnthereferencet othesamei nst
ance.

WhyJav
ausest
heconceptofSt
ri
ngl
it
eral
?
TomakeJavamorememoryeffi
cient(becausenonewobj
ect
sar
ecr
eat
edi
f
i
texi
stsal
readyi
nthest
ri
ngconst
antpool).
2)Bynewkey
wor
d
1. St r
ings=newSt
ri
ng(
"Wel
come"
); /
/cr
eat
est
woobj
ect
sandone
r
efer
encev
ari
abl
e
Insuchcase,JVM wil
l cr
eateanewst ri
ngobjecti
nnormal (
non-pool
)heap
memor y,
andthelit
eral"
Welcome"willbeplacedint
hest r
ingconstantpool
.The
var
iabl
eswi l
lref
ertotheobjectinaheap(non-pool
).
Jav
aSt
ri
ngExampl
e
St
ri
ngExampl
e.j
ava
publ
i
ccl
assSt
ri
ngExampl
e{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
St
ri
ngs1="
jav
a"; /
/cr
eat
ingst
ri
ngbyJav
ast
ri
ngl
i
ter
al
charch[
]={
's'
,
't
',
'
r'
,'
i
',
'
n',
'
g',
'
s'}
;
St
ri
ngs2=newSt
ri
ng(
ch)
; /
/conv
ert
ingcharar
rayt
ost
ri
ng
St
ri
ngs3=newSt
ri
ng(
"exampl
e")
; /
/cr
eat
ingJav
ast
ri
ngbynew
key
wor
d
Sy
stem.
out
.pr
int
ln(
s1)
;
Sy
stem.
out
.pr
int
ln(
s2)
;
Sy
stem.
out
.pr
int
ln(
s3)
;
}

Out
put
:
j
ava
st
ri
ngs
exampl
e
Theabov
ecode,conv
ert
sacharar
rayint
oaSt ri
ngobject
.Anddi
spl
ayst
he
St
ri
ngobj
ect
ss1,s2,
ands3onconsol
eusingpri
ntl
n()method.

Jav
aSt
ri
ngcl
assmet
hods
Thej
ava.
lang.
Str
ingcl
assprovi
desmanyusef
ulmet
hodst
oper
for
m
oper
ati
onsonsequenceofcharv
alues.
No. Met
hod Descr
ipt
ion

1 charchar
At(
inti
ndex) I
tret
urnscharv
aluef
ort
hepar
ti
cul
ari
ndex

2 i
ntl
engt
h() I
tret
urnsst
ri
ngl
engt
h

3 stati
c Str
ing for
mat(St
ri
ng I
tret
urnsaf
ormat
tedst
ri
ng.
format,
Object
..
.args)

4 st
ati
cStr
ingf
ormat(
Localel
,Itr
etur
nsf
ormat
tedst
ri
ngwi
thgi
venl
ocal
e.
St
ri
ngfor
mat,Obj
ect.
..ar
gs)

5 Str
ing subst
ri
ng(
int I
tret
urnssubst
ri
ngf
orgi
venbegi
nindex.
beginI
ndex)

6 Str
ing substr
ing(
int I
tret
urnssubst
ri
ngf
orgi
venbegi
nindexandendi
ndex
.
beginI
ndex,
intendIndex)

7 bool
ean I
tret
urnst
rueorf
alseaf
termat
chi
ngt
hesequenceofcharv
alue.
cont
ains(
Char
Sequences)

8 stat
ic St
ri
ng Itr
etur
nsaj
oinedst
ri
ng.
j
oin(CharSequence
deli
miter, CharSequence.
..
el
ement s)

9 stat
ic Stri
ng I
tret
urnsaj
oinedst
ri
ng.
j
oin(Char
Sequence
deli
miter
,It
erabl
e<?extends
CharSequence>el
ement s)

10 bool
ean equal
s(Obj
ect I
tcheckst
heequal
i
tyofst
ri
ngwi
tht
hegi
venobj
ect
.
anot
her
)

11 bool
eani
sEmpt
y() I
tchecksi
fst
ri
ngi
sempt
y.

12 St
ri
ngconcat
(St
ri
ngst
r) I
tconcat
enat
est
hespeci
fi
edst
ri
ng.

13 Str
ingr
epl
ace(
charol
d,char I
trepl
acesal
loccur
rencesoft
hespeci
fi
edcharv
alue.
new)
14 Stri
ng I
trepl
acesal
loccur
rencesoft
hespeci
fi
edChar
Sequence.
repl
ace(CharSequence ol
d,
CharSequencenew)

15 stat
ic Str
ing I
tcompar
esanot
herst
ri
ng.I
tdoesn'
tcheckcase.
equalsI
gnor
eCase(
Str
ing
another
)

16 St
ri
ng[
]spl
i
t(St
ri
ngr
egex) I
tret
urnsaspl
i
tst
ri
ngmat
chi
ngr
egex.

17 Str
ing[
]spl
i
t(St
ri
ngr
egex,
int I
tret
urnsaspl
i
tst
ri
ngmat
chi
ngr
egexandl
i
mit
.
l
imit)

18 St
ri
ngi
nter
n() I
tret
urnsani
nter
nedst
ri
ng.

19 i
nti
ndexOf
(i
ntch) I
tret
urnst
hespeci
fi
edcharv
aluei
ndex.

20 i
nt indexOf
(i
nt ch, i
nt I
tret
urnst
hespeci
fi
edcharv
aluei
ndexst
art
ingwi
thgi
veni
ndex
.
f
romI
ndex)

21 i
nti
ndexOf
(St
ri
ngsubst
ri
ng) I
tret
urnst
hespeci
fi
edsubst
ri
ngi
ndex.

22 i
nti
ndexOf(St
ri
ngsubst
ri
ng, I
tret
urnst
hespeci
fi
edsubst
ri
ngi
ndexst
art
ingwi
thgi
veni
ndex.
i
ntf
romIndex)

23 St
ri
ngt
oLower
Case(
) I
tret
urnsast
ri
ngi
nlower
case.

24 St
ri
ng t
oLower
Case(
Local
e I
tret
urnsast
ri
ngi
nlower
caseusi
ngspeci
fi
edl
ocal
e.
l
)

25 St
ri
ngt
oUpper
Case(
) I
tret
urnsast
ri
ngi
nupper
case.

26 St
ri
ng t
oUpper
Case(
Local
e I
tret
urnsast
ri
ngi
nupper
caseusi
ngspeci
fi
edl
ocal
e.
l
)

27 St
ri
ngt
ri
m() I
tremov
esbegi
nni
ngandendi
ngspacesoft
hisst
ri
ng.

28 stati
c St
ri
ng v
alueOf
(i
nt I
tconv
ert
sgi
vent
ypei
ntost
ri
ng.I
tisanov
erl
oadedmet
hod.
value)
I
mmut
abl
eSt
ri
ngi
nJav
a
ASt ri
ngisanunav oi
dabletypeofvar
iabl
ewhilewri
ti
nganyapplicat
ion
progr
am.St r
ingref
erencesareusedt ost
orevari
ousatt
ri
butesli
keusername,
passwor
d, etc.I
nJava,Stri
ngobjectsar
eimmut abl
e.I
mmut abl
esimplymeans
unmodif
iableorunchangeable.
OnceStr
ingobj
ecti
scr
eat
edi
tsdat
aorst
atecan'
tbechangedbutanew
St
ri
ngobj
ecti
screat
ed.
Let
'
str
ytounder
standt
heconceptofi
mmut
abi
l
itybyt
heexampl
egi
ven
bel
ow:
cl
assTest
immut
abl
est
ri
ng{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
St
ri
ngs="
Sachi
n";
s.
concat
("Tendul
kar
"); /
/concat
()met
hodappendst
hest
ri
ngatt
heend
Sy
stem.
out
.pr
int
ln(
s); /
/wi
l
lpr
intSachi
nbecausest
ri
ngsar
eimmut
abl
e
obj
ect
s
}
}
Out
put
:
Sachi
n
Nowitcanbeunder
stoodbyt
hediagr
am gi
venbelow.HereSachi
nisnot
changedbutanewobjecti
screat
edwit
hSachinTendul
kar.Thati
swhyStri
ngis
knownasimmut abl
e.

Asy
oucanseeintheabovefi
guret
hattwoobj
ect
sarecreatedbuts
r
efer
encevar
iabl
est
il
lref
erst
o"Sachi
n"nott
o"Sachi
nTendul
kar"
.
Buti
fweexpl
i
cit
lyassi
gni
ttot
her
efer
encev
ari
abl
e,i
twi
l
lref
ert
o"Sachi
n
Tendul
kar
"obj
ect
.
Forexampl
e:
cl
assTest
immut
abl
est
ri
ng1{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
St
ri
ngs="
Sachi
n";
s=s.
concat
("Tendul
kar
");
Sy
stem.
out
.pr
int
ln(
s);
}
}
Out
put
:
Sachi
nTendul
kar
Insuchacase,
spoi
ntstot
he"
Sachi
nTendul
kar
".Pl
easenot
icet
hatst
il
l
Sachi
nobjecti
snotmodi
fi
ed.
WhySt
ri
ngobj
ect
sar
eimmut
abl
einJav
a?
AsJavausestheconceptofStri
ngli
teral
.Supposethereare5ref
erence
var
iabl
es,
all
refertooneobj
ect"Sachi
n".I
fonereferencevari
abl
echangestheval
ue
oft
heobject
,itwil
lbeaff
ect
edbyal lt
herefer
encevar i
abl
es.Thati
swhySt r
ing
obj
ectsar
eimmut abl
einJava.
Fol
l
owi
ngar
esomef
eat
uresofSt
ri
ngwhi
chmakesSt
ri
ngobj
ect
simmut
abl
e.
1.Cl
assLoader
:
ACl assLoaderi
nJavausesaSt r
ingobj
ectasanargument
.Consi
der,i
fthe
Str
ingobjecti
smodi fi
abl
e,theval
uemightbechangedandthecl
asst
hatis
supposedtobel oadedmightbedif
fer
ent.
Toav
oidt
hiski
ndofmi
sint
erpr
etat
ion,
Str
ingi
simmut
abl
e.
2.Thr
eadSaf
e:
AstheStr
ingobjectisimmut
abl
ewedon'thavetotakecar
eofthe
sy
nchr
oni
zat
ionthati
sr equi
redwhi
l
eshar
inganobjectacrossmul
ti
plet
hreads.
3.Secur
it
y:
Aswehav eseeninclassloading,immutableStri
ngobject
sav oi
dfurt
her
err
orsbyloadi
ngt hecorr
ectclass.Thisleadstomaki ngtheappl
icati
onprogr
am
mor esecur
e.Consideranexampl eofbankingsof t
ware.Theusernameand
passwordcannotbemodi fi
edbyanyi nt
ruderbecauseStringobj
ectsarei
mmut abl
e.
Thiscanmaket heappli
cati
onpr ogram mor esecure.
4.HeapSpace:
Theimmut abil
i
tyofStr
inghel
pstomi nimizetheusagei
ntheheapmemor y.
Whenwet r
yt odeclar
eanewSt ri
ngobject,t
heJVM checkswhetherthevalue
al
readyexi
stsintheStri
ngpoolornot
.Ifitexi
sts,t
hesamev al
ueisassignedtot
he
newobj
ect
.Thi
sfeat
ureal
l
owsJav
atouset
heheapspaceef
fi
cient
ly.
WhySt
ri
ngcl
assi
sFi
nali
nJav
a?
ThereasonbehindtheStri
ngcl
assbei
ngfi
nalisbecausenoonecanoverr
ide
themethodsoftheStr
ingclass.Sot
hati
tcanpr
ovidethesamef eat
urest
othenew
Str
ingobj
ectsaswellastotheoldones.

STRI
NGCOMPARE
1)ByUsi
ngequal
s()Met
hod
TheStri
ngclassequal
s()methodcompar
estheor
igi
nalcont
entofthest
ri
ng.I
t
comparesvaluesofst
ri
ngforequal
it
y.St
ri
ngcl
assprov
idesthefol
l
owingtwo
methods:

publ
i
cbool
eanequal
s(Obj
ectanot
her
)compar
est
hisst
ri
ngt
othespeci
fi
edobj
ect
.
publ
icbooleanequal
sIgnor
eCase(
Str
inganot
her
)compar
est
hisst
ri
ngt
o
anot
herstr
ing,
ignori
ngcase.
EX.
cl
assTest
str
ingcompar
ison1{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
St
ri
ngs1="
Sachi
n";
St
ri
ngs2="
Sachi
n";
St
ri
ngs3=newSt
ri
ng(
"Sachi
n")
;
St
ri
ngs4="
Saur
av"
;
Sy
stem.
out
.pr
int
ln(
s1.
equal
s(s2)
); /
/tr
ue
Sy
stem.
out
.pr
int
ln(
s1.
equal
s(s3)
); /
/tr
ue
Sy
stem.
out
.pr
int
ln(
s1.
equal
s(s4)
); /
/fal
se
}
}
Out
put
:
t
rue
t
rue
f
alse

I
ntheabovecode,
twost
ri
ngsarecomparedusi
ngequal
s()met
hodofSt
ri
ngcl
ass.
Andt
heresul
tispr
int
edasbool
eanval
ues,tr
ueorf
alse.

cl
assTest
str
ingcompar
ison2{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
St
ri
ngs1="
Sachi
n";
St
ri
ngs2="
SACHI
N";

Sy
stem.
out
.pr
int
ln(
s1.
equal
s(s2)
);
//f
alse
Sy
stem.
out
.pr
int
ln(
s1.
equal
sIgnor
eCase(
s2)
);
//t
rue
}
}

Out
put
:
f
alse
t
rue
Intheabovepr ogram,themet hodsofSt r
ingcl
assareused.Theequal
s()met
hod
ret
urnstrueifStri
ngobj ect
saremat chingandbothstr
ingsareofsamecase.
equalsI
gnoreCase( )r
eturnstr
uer egar
dlessofcasesofstr
ings.
Cl
i
ckher
eformor
eaboutequal
s()met
hod
_
___
___
___
___
___
___
___
___
___
___
___
___
___
2)ByUsi
ng==oper
ator
The==oper
atorcompar
esr
efer
encesnotv
alues.

cl
assTest
str
ingcompar
ison3{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
St
ri
ngs1="
Sachi
n";
St
ri
ngs2="
Sachi
n";
St
ri
ngs3=newSt
ri
ng(
"Sachi
n")
;
Sy
stem.
out
.pr
int
ln(
s1==s2)
; /
/tr
ue(
becausebot
href
ert
osamei
nst
ance)
System.
out
.pr
int
ln(
s1==s3)
; /
/fal
se(
becauses3r
efer
stoi
nst
ancecr
eat
edi
n
nonpool
)
}
}

Out
put
:
t
rue
f
alse
_
___
___
___
___
___
___
___
___
___
___
___
___
___
3)St
ri
ngcompar
ebycompar
eTo(
)met
hod
Theabovecode,
demonst
rat
est
heuseof==oper
atorusedf
orcompar
ingt
woSt
ri
ng
obj
ects.
_
___
___
___
___
___
___
___
___
___
___
___
___
___
4)ByUsi
ngcompar
eTo(
)met
hod
TheSt r
ingcl
asscompareTo(
)methodcompar esval
ueslexi
cogr
aphical
lyand
retur
nsanintegerv
aluet
hatdescr
ibesi
ffi
rststr
ingi
slessthan,
equaltoorgreat
er
thansecondstri
ng.
Supposes1ands2ar
etwoSt
ri
ngobj
ect
s.I
f:
s1==s2:
Themet
hodr
etur
ns0.
s1>s2:
Themet
hodr
etur
nsaposi
ti
vev
alue.
s1<s2:
Themet
hodr
etur
nsanegat
ivev
alue.
cl
assTest
str
ingcompar
ison4{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
St
ri
ngs1="
Sachi
n";
St
ri
ngs2="
Sachi
n";
St
ri
ngs3="
Rat
an"
;
Sy
stem.
out
.pr
int
ln(
s1.
compar
eTo(
s2)
);
//0
Sy
stem.
out
.pr
int
ln(
s1.
compar
eTo(
s3)
);
//1(
becauses1>s3)
Sy
stem.
out
.pr
int
ln(
s3.
compar
eTo(
s1)
);
//-
1(becauses3<s1)
}
}

Out
put
:
0
1
-
1

ARRAY
=Arr
ayiscoll
ecti
onofsi
mil
ardat
aty
pe
=obj
ecti
sstoreri
nheapmemory.

Adv
ant
agesofar
ray:

=CodeOpt i
mizat
ion:
Itmakest
hecodeopt
imi
zed,
wecanr
etr
iev
eorsor
tthedat
a
ef
fi
cient
ly.
=Random access:
Wecangetanydatal
ocat
edatani
ndexposi
ti
on.
=singl
enamesi mil
ardat
aisst
ores.

Di
sadv
ant
agesofar
ray:

=diff
erentdataty
pecannotbeused.
=sizeofarrayisfi
xed.
=memor ywastage.
=reduceper f
ormance.

ExampleofJavaArray
Let'
sseethesi
mpleexampl
eofjav
aar
ray
,wher
ewear
egoi
ngt
odecl
are,
inst
ant
iat
e,
i
nit
ial
izeandtr
aver
seanarr
ay.

//Jav aPr ogr am toill


ustr
atehowt odecl
are,i
nstanti
ate,
ini
ti
ali
ze
//andt r
aver set heJavaarray.
classTest array {
publ i
cst aticv oidmain(Stri
ngar gs[
]){
i
nta[ ]
=newi nt[5]; //declarati
onandinstanti
ati
on
a[0]=10; //i
nit
iali
zati
on
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
/ /tr
av ersi
ngar ray
for(i
nti =0;i
<a. l
ength;i
++) //l
engthisthepropert
yofar
ray
Sy stem. out.printl
n(a[
i]
);
}}

Output
:
10
20
70
40
50

Decl
arat
ion,
Instant
iat
ionandIni
ti
ali
zati
onofJavaArr
ay
Wecandeclare,
inst
antiat
eandini
ti
ali
zethej
avaarr
aytoget
herby
:

i
nta[
]={
33,
3,
4,
5}; /
/decl
arat
ion,
inst
ant
iat
ionandi
nit
ial
i
zat
ion

Let
'sseet
hesi
mpl
eexampl
etopr
intt
hisar
ray
.

/
/Jav
aPr
ogr
am t
oil
l
ust
rat
etheuseofdecl
arat
ion,
inst
ant
iat
ion
/
/andi
nit
ial
i
zat
ionofJav
aar
rayi
nasi
ngl
eli
ne

classTest array 1{
publicstaticv oidmai n(St
ri
ngargs[]
){
i
nta[ ]
={33,3,4,5} ; //
decl
arati
on,
instant
iat
ionandini
ti
ali
zat
ion
//pri
nti
ngar ray
for(i
nti=0;i
<a. l
engt h;
i
++) //l
engt
hi stheproper
tyofarr
ay
Sy st
em. out.printl
n(a[
i])
;
}
}

Output
:
33
3
4
5

For -
eachLoopf orJav aAr r
ay
Wecanal sopr inttheJav aar rayusingf or-eachloop
.TheJav af or-
eachl ooppr intst hearrayel ement sonebyone.Itholdsanarray
elementi nav ariable,thenexecut est hebodyoft heloop.
Thesy ntaxoft hef or-eachl oopi sgi venbel ow:
for(data_ty pev ar i
able:array){
//bodyoft hel oop
}
Letusseet heexampl eofpr inttheel ement sofJav aarrayusi
ngthefor-
eachloop.
//Jav aPr ogram t opr i
ntt hearrayel
ementsusingfor-
eachloop
classTest ar r
ay 1{
publ i
cst aticv oidmai n(Stri
ngar gs[]
){
i
ntar r
[]
={33, 3,4,5};
//pri
ntingar rayusi ngf or-
eachl oop
for(i
nti :
arr)
Sy stem.out .println(i
);
}
}
Out put:
33
3
4
5
___ _
_ _
___ ______ _______________ _
_ _
_ _
__ _
_ _
Passi ngAr rayt oaMet hodi nJav a
Wecanpasst hej avaar rayt omet hodsot hatwecanr eusethesamel ogiconany
array .
Let '
sseet hesi mpl eexampl et ogett hemi nimum numberofanar r
ayusingamet hod.
//Jav aPr ogram todemonstrat
ethewayofpassi
nganarr
ay
//tomet hod.
classTest arr
ay2{
//creatingamet hodwhichrecei
vesanar
rayasaparamet
er
staticvoi dmi n(
intar
r[]
){
i
ntmi n=ar r
[0];
for(i
nti=1; i
<arr.
lengt
h;i
++)
if(min>ar r[i
])
mi n=ar r
[i]
;

Syst
em.
out
.pr
int
ln(
min)
;
}

publ
i
cst at
icvoi
dmai
n(St
ringargs[]
){
i
nta[]
={33,
3,4,
5}; //declar
ingandini
ti
ali
zi
nganar
ray
min(
a); /
/ passi
ngarraytomethod
}
}

Col
lect
ion:
-

The 
CollectioninJav a i
saf ramewor kthatprovidesanar chitect
uretostor
eand
manipulatethegr oupofobj ects.
JavaCollectionscanachi evealltheoper ati
onst hatyouper form onadatasuchas
sear
ching,sor ti
ng,inserti
on, manipul ati
on,anddel eti
on.
JavaCollectionmeansasi ngleuni tofobjects.Jav aColl
ectionframeworkprovi
des
manyinterfaces( Set,List,Queue, Deque)andcl asses( ArrayList
,
Vector

LinkedLi st

Pr i
orit
y Queue,HashSet ,
LinkedHashSet ,TreeSet).
TheCollecti
oni nterface(java.uti
l.
Col lect
ion)andMapi nterface(jav
a.ut
il
.Map)are
thetwomai n“ root”interf
acesofJav acoll
ectionclasses.

j
av a.uti
l.
Collecti
on:-Thej av a.uti
l.Coll
ecti
onspackagei s thepackaget hatcontai
ns
theCol l
ectionscl ass.Col l
ect i
onsclassisbasicall
yusedwi ththestat
icmet hods
thatoper at
eont hecol l
ectionsorr etur
nthecollecti
on.Thebestgener alpurposeor
'
primar y'i
mpl ement ati
onsar eli
kely 
Array
List,HashMap, andHashSet  
.
HashMap: -Jav a HashMap  classimplement st
heMapi nterfacewhichallowsus to
storekeyandv aluepai r,wher ekeysshouldbeuni que.Ifyout rytoi
nsertthe
duplicatekey ,i
twi l
lreplacet heelementoft hecorrespondingkey .I
tiseasyt o
perform oper at
ionsusi ngthekeyi ndexli
keupdat i
on,deletion,et
c.

Poi
ntst
oremember
:-
o Jav
aHashMapcont
ainsv
aluesbasedont
hekey
.
o Jav
aHashMapcont
ainsonl
yuni
quekey
s.
o Jav
aHashMapmayhav
eonenul
lkeyandmul
ti
plenul
lval
ues.
o Jav
aHashMapi
snonsy
nchr
oni
zed.
o Jav
aHashMapmai
ntai
nsnoor
der
.

1.cl
ear
() Iti
susedt oremov eall
oft hemappingsfrom t
his
map.
2.i
sEmpt
y() Iti
susedt oreturntr
ueifthismapcont ai
nsno
key-
v aluemappi ngs
3.Obj
ectcl
one(
) Iti
susedt oreturnashall
owcopyoft hi
s
HashMapi nstance:t
hekey sandv al
ues
themsel vesarenotcloned.
4.ent
rySet
() Iti
susedt oreturnacoll
ect i
onviewofthe
mappi ngs
containedint hi
smap.
5.key
Set
() Iti
susedt oreturnasetviewoft hekeys
containedint hi
smap.
6.put(
Objectkey,Object Iti
susedt oinsertanentr
yi nthemap.
val
ue)
7.remove(Objectkey) Iti
susedtodeleteanentr
yf ort
hespecifi
edkey .
8.contai
nsKey (
Objectkey) Thismethodretur
nstruei
fsomekeyequal t
ot he
keyexi
stswit
hinthemap, elser
etur
nfalse
9.replace(
Kkey
,Vv
alue) Itr
epl
acesthespecif
iedvalueforaspecif
iedkey.
10.
size() Thismethodretur
nsthenumberofent r
iesinthe
map.

Jav
a.ut
il
.Map:
-JavaHashSetcl
assi
susedt
ocr
eat
eacol
l
ect
iont
hatusesahasht
abl
efor
st
orage.I
tinher
it
stheAbst
ract
Setcl
assandi
mpl
ement
sSeti
nter
face.
Thei
mpor t
antpointsaboutJav aHashSetclassare:
o Ha shSetstorestheelement sbyusi
ngamechani sm cal
l
ed hashing.
o Ha shSetcontainsuni
queel ementsonly.
o Ha shSetall
owsnul lv
alue.
o Ha shSetclassisnonsy nchroni
zed.
o HashSetdoesn'tmaintai
nthei nser
ti
onor der
.Here,
elementsareinsert
edont
he
basi
soft hei
rhashcode.

Met
hodsofHashSet
:-
Met
hod Descr
ipt
ion

add(
Ee) I
tisusedtoaddthespeci
fi
edel
ementt
othi
sseti
fiti
snot
al
readypr
esent
.

cl
ear
() I
tisusedt
oremov
eal
loft
heel
ement
sfr
om t
heset
.

cl
one(
) I
tisusedtoret
urnashal
low copyofthi
sHashSeti
nst
ance:
t
heelement
sthemsel
vesarenotcl
oned.
cont
ains(
Obj
ect Itisusedt
oret
urnt
ruei
fthi
ssetcont
ainst
hespeci
fi
ed
o) element
.

i
sEmpt
y() I
tisusedt
oret
urnt
ruei
fthi
ssetcont
ainsnoel
ement
s.

i
ter
ator
() I
tisusedt
oret
urnani
ter
atorov
ert
heel
ement
sint
hisset
.

remov
e(Obj
ect I
tisusedtor
emov
ethespeci
fi
edel
ementf
rom t
hisseti
fiti
s
o) pr
esent.

si
ze(
) I
tisusedt
oret
urnt
henumberofel
ement
sint
heset
.

spl
i
ter
ator
() I
tisusedtocr
eatealate-
bindi
ngandf
ail
-f
astSpl
i
ter
atorov
er
t
heelementsi
ntheset.

Pat
ter
nPr
ogr
am:
-

1.StarPat
tern:
-Byusingi
ncr
ement
:
Packagedemo;
Publi
cclassStar{

Publicstat
icvoi
dmai n(st
ri
ng[
]ar
gs)
{
for(
inta=1;
a<=5;a++){
for(
intb=1;
b<=a;b++){
system.out.
pri
ntln(
“*)
;
}
system.out.
pri
ntln(
);
}
}
}

2.StarPatter
n:-Byusingdecrement:
Packagedemo;
Publiccl
assSt ar{
Publicstat
icvoidmain(st
ri
ng[]
args)
{
for(
inta=1;
a<=5;a++){
for(
intb=5;
b>=a;b--
){
system.out.
pri
ntln(
“*”
);
}
system.out.
pri
ntln(
);
}
}
}
Logi
calPr
ogr
ams:-
1.Addi
nganInt
eger
s:-

2.ASCI
IPat
ter
n:
3.Fact
ori
alofnumber
:

4.Fi
bonaaciSer
ies:
5.Lar
gestNumber
:

6.LeapYear
:
7.Pal
indr
omenumber
:

8.Pr
imenumber
:
9.Quot
ientandr
emai
nder
:
10.
Rev
erseSt
ri
ng:

11.
Rev
erseNumber
:
12.
Vowel
sandConsonant
:

You might also like