Jaca Docx3
Jaca Docx3
TII Pr
ogr
ammi
ngCons
truct
s
Pr
ogr
ammi
ngCons
truct
s
Var
iabl
es:
Thevar
iabl
eist
hebas
icuni
tofs
tor
age.Avar
iabl
eisdef
inedbyt
he
combi
nat
ionofani
dent
if
ier ype,andan opt
,at ionali
nit
ial
izer
.Inaddi
ti
on,al
l
var
iabl
eshaveas
cope,
whi
chdef
inest
hei
rvi
sibi
li
ty,
andal
if
eti
me.
Decl
ari
ngaVar
iabl
e,i
njavaal
lvar
iabl
esmus
tbedecl
aredbef
oret
heycanbeus
ed.
Synt
ax:
typei
dent
if
ier[
=val
ue][
,ident
if
ier[
=val
ue].
..
];
Thet
ypei
soneofj
ava’
sat
omi
ctypes
,ort
henameofacl
assori
nter
face.The
i
dent
if
ieri
sthenameoft
hevar
iabl
e.Youcani
nit
ial
izet
hevar
iabl
ebys
peci
fyi
ngan
equals
ignandaval
ue.Thatt
hei
nit
ial
izat
ionexpr
ess
ionmus
tres
ulti
naval
ueof
t
hes
ame(
orcompat
ibl
e)t
ypeast
hats
peci
fi
edf
ort
hevar
iabl
e.Todecl
aremor
e
t
hanonevar
iabl
eoft
hes
peci
fi
edt
ype,
usecommas
epar
atedl
ist
.
E.
g.:
inta,
b,c;ori
nta=3,
b=5,
c;byt
ed=22;doubl
epi=3.
14159;chars
='s
';
Dynami
cIni
ti
ali
zat
ion:Al
thought
hepr
ecedi
ngexampl
eshaveus
edonl
ycons
tant
s
as i
nit
ial
izer
s,Java al
lows var
iabl
es t
o be i
nit
ial
ized dynami
cal
ly,us
ing any
expr
ess
ionval
idatt
het
imet
hevar
iabl
eisdecl
ared.
//Dynamiciniti
ali
z at
ion.
importjava.
ut i
l.
Scanner;
classDynIni
t
{
publi
cs t
aticvoidmain(Str
ingargs
[])
{
intnum1, num2,num3;
Scanners =newScanner(Syst
em.i
n);
System. out
.pri
ntl
n("Ent
ernum1&num2values")
;
num1=s .
nextI
nt()
;
num2=s .
nextI
nt()
;
num3=num1+num2;
System. out
.pri
ntl
n("num3valuei
s"+num3);
}
}
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page13
UNI
TII Pr
ogr
ammi
ngCons
truct
s
Dat
aTypes
:Javadef
ines8t
ypesofdat
a:byt
e,s
hor
t,i
nt,l
ong,char
,fl
oat
,
doubl
e,andbool
ean.
Dat
atypescanbedi
videdi
nto2t
ypes
1.
Pri
mit
iveDat
aTypes(
byt
e,s
hor
t,i
nt,
long,
float
,doubl
e,char
,bool
ean)
2.
Non-Pr
imi
ti
veDat
aTypes(
clas
s,St
ring,
arr
ays
,int
erf
aces
)
Pr
imi
ti
veDat
atypes
:Thepr
imi
ti
vet
ypesar
edef
i ohaveanexpl
nedt ici
trange
andmat
hemat
icalbehavi
or.
1.I
nteger
s:Thi
sgr
oupi
ncl
udesbyt
e,s
hor
t,i
nt,andl
ong,whi
char
eforwhol
e-
val
ueds
ignednumber
s,pos
iti
ve&negat
ivenumber
s.
2.Fl
oat
ing-
poi
ntnumber
s:Thi
sgr
oupi
ncl
udesf
loatanddoubl
e,whi
chr
epr
esent
number
swi
thf
ract
ionalpr
eci
sion.
3.Char
act
ers
:Thi
sgr
oupi
ncl
udeschar
,whi
chr
epr
esent
ssymbol
sinachar
act
er
s
et,
likel
ett
ersandnumber
s.
4.Bool
ean:Thi
sgr
oupi
ncl
udesbool
ean,whi
chi
sas
peci
alt
ypef
orr
epr
esent
ing
t
rue/
fal
seval
ues
.
1.I
nteger
s:Javadef
inesf
ouri
ntegert
ypes
:byt
e,s
hor
t,i
nt,andl
ong.Al
loft
hes
e
ar
esi
gned,
pos
iti
veandnegat
iveval
ues
.
a.Javadoesnots
uppor
tuns
igned,
pos
iti
ve-
onl
yint
eger
s.
b.Manyot
hercomput
erl
anguagess
uppor
tbot
hsi
gnedanduns
ignedi
nteger
s.
c.Javamanagest
hemeani
ngoft
hehi
gh-
orderbi
tdi
ff
erent
ly,byaddi
nga
s
peci
al“uns
ignedr
ights
hif
t”oper
ator
.Thus
,theneedf
oranuns
ignedi
nteger
t
ypewasel
imi
nat
ed.
d.TheJavar
un-
ti
meenvi
ronmenti
sfr
eet
ous
ewhat
evers
izei
twant
s,asl
ongas
t
het
ypesbehaveasyoudecl
aredt
hem.
Wi
dthandr
angesofi
ntegert
ypes
Name Wi
dth Range
byt
e 8 –128t
o127
s
hor
t 16 –32,
768t
o32,
767
i
nt 32 –2,
147,
483,
648t
o2,
147,
483,
647
l
ong 64 –9,
223,
372,
036,
854,
775,
808t
o
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page14
UNI
TII Pr
ogr
ammi
ngCons
truct
s
9,
223,
372,
036,
854,
775,
807
. byt
i e:Thes
mal
les
tint
egert
ypei
sbyt
e.Thi
sisas
igned8-
bitt
ypet
hathasa
r
angef
rom –128t
o127.Var
iabl
esoft
ypebyt
ear
ees
peci
all
yus
efulwhen
you’
rewor
kingwi
thas
tream ofdat
afr
om anet
wor
korf
il
e.Theyar
eal
so
us
efulwhenyou’
rewor
kingwi
thr
aw bi
nar
ydat
athatmaynotbedi
rect
ly
compat
ibl
ewi
thJava’
sot
herbui
lt
-i
ntypes
.Byt
evar
iabl
esar
edecl
aredbyus
e
oft
hebyt
ekeywor
d.E.
g.:
byt
eb,
c;
i
i. s
hor
t:s
hor
tisas
igned16-
bitt
ype.I
thasar
angef
rom –32,
768t
o32,
767.I
tis
pr
obabl
ythel
eas
t-us
edi
nJava.
E.g.
:shor
ts;
i
i. i
i nt:i
nti
sa s
igned 32-
bitt
ype t
hathasa r
ange f
rom –2,
147,
483,
648 t
o
2,
147,
483,
647.I
naddi
ti
ont
oot
herus
es,var
iabl
esoft
ypei
ntar
ecommonl
y
empl
oyedt
ocont
roll
oopsandt
oindexar
rays
.Ther
efor
e,i
nti
sof
tent
hebes
t
choi
cewhenani
ntegeri
sneeded.
E.g.
:i
nta,
b,c;
v. l
i ong:
longi
sas
igned64-
bitt
ypeandi
sus
efulf
ort
hos
eoccas
ionswher
eani
nt
t
ypei
snotl
argeenought
ohol
dthedes
iredval
ue.Ther
angeofal
ongi
squi
te
l
arge.
Thi
smakesi
tus
efulwhenbi
g,whol
enumber
sar
eneeded.
2.Fl
oat
ingpoi
ntnumber
s:Fl
oat
ingpoi
ntnumber
sar
eal
soknownasr
ealnumber
s.
Thes
ear
eus
edf
orr
epr
esent
ingt
hef
ract
ionalnumber
s.Ther
ear
etwot
ypes
f
loatanddoubl
e
Wi
dthandr
angesoff
loat
ingt
ypes
Name Wi
dth(
bit
s) Appr
oxi
mat
eRange
f
loat 32 1.
4e-
045t
o3.
4e+038
doubl
e 64 4.
9e-
324t
o1.
8e+308
i
. f
loat
:fl
oats
peci
fi
esas
ingl
epr
eci
sionval
uet
hatus
es32bi
tsofs
tor
age.Fl
oat
i
sus
efulwhenyouneedaf
ract
ionalcomponent
.E.
g.:
floata,
b;
i
i. doubl
e:I
tsr
epr
esent
ati
oni
sfas
tert
hant
hef
loatr
epr
esent
ati
on.I
tcanbeus
ed
f
orhi
ghs
peedcal
cul
ati
ons
.E.
g.:
doubl
ea,
b,c;
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page15
UNI
TII Pr
ogr
ammi
ngCons
truct
s
3.Char
act
ers
:InJava,t
hedat
atypeus
edt
ost
orechar
act
ersi
schar
.chari
nJavai
s
nott
hes
ameaschari
nCorC++.I
nC/
C++,chari
s8bi
tswi
de.Thi
sisnott
hecas
e
i
nJava.I
nst
ead,Javaus
esUni
codet
orepr
esentchar
act
ers
.Iti
sauni
fi
cat
ionof
doz
ensofchar
act
ers
ets
,suchasLat
in,
Greek,
Arabi
c,Cyr
il
li
c,Hebr
ew,
Kat
akana,
Hangul
,andmanymor
e.Fort
hispur
pos
e,i
trequi
res16bi
ts.Thus
,inJavachar
i
sa16-
bitt
ype.Ther
angeofachari
s0t
o65,
536.Ther
ear
enonegat
ivechar
s.
Thes
tandar
dsetofchar
act
ersknownasASCI
Ist
il
lrangesf
rom 0t
o127as
al
ways
,andt
heext
ended8-
bitchar
act
ers
et,I
SO-
Lat
in-
1,r
angesf
rom 0t
o255.
E.
g.:
charch1,
ch2;ch1='
Y';ch2=88;/
/codef
orX;
4.Bool
eans
:Javahasapr
imi
ti
vet
ype,cal
ledbool
ean,f
orl
ogi
calval
ues
.Itcan
haveonl
yoneoft
wopos
sibl
eval
ues
,tr
ueorf
als
e.Thi
sist
het
yper
etur
nedby
al
lrel
ati
onaloper
ator
s,asi
nthecas
eofa<b.bool
eani
sal
sot yper
het equi
red
byt
hecondi
ti
onalexpr
ess
ionst
hatgover
nthecont
rols
tat
ement
ssuchasi
fand
f
or.
E.
g.:
Progr
am
cl
assBool Test
{
publi
cs t
aticvoi dmain(St r
ingar gs[]
)
{
booleanb;
b=f alse;
System. out .
pri
ntln("bis"+b) ;
b=t rue;
System. out .
pri
ntln("bis"+b) ;
//abool eanvaluecancont r
oltheifst
atement
if(
b)
Sys t
em.out .
println("Thisi
sexecuted.
");
b=f alse;
if(
b)
System.out.pri
nt l
n("Thisisnotexecuted.
");
//out comeofar elationaloper at
orisabooleanvalue
System. out .
pri
ntln("10>9i s"+(10>9) )
;
}
}
Output :
bisfalse
bistrue
Thisisexecuted.
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page16
UNI
TII Pr
ogr
ammi
ngCons
truct
s
10>9i
str
ue.
Non-
Pri
mit
ive(
Ref
erence)Dat
atype:Ar
efer
encedat
atypei
sus
edt
oref
ert
oan
obj
ect
.Ar
efer
encevar
iabl
eisdecl
aredt
obeofs
peci
fi
candt
hatt
ypecanneverbe
change.
I
dent
if
ier
s:-I
dent
if
ier
smus
tst
artwi
thal
ett
er,acur
rencychar
act
er(
$),ora
connect
ingchar
act
ers
uchast
heunder
scor
e_.
a.I
dent
if
ier
scannots
tar
twi
thanumber
.
b.Af
tert
hef
irs
tchar
act
er,i
dent
if
ier
scancont
ainanycombi
nat
ionofl
ett
ers
,
cur
rencychar
act
ers
,connect
ingchar
act
ers
,ornumber
s.
c.Ther
eisnol
imi
ttot
henumberofchar
act
ersani
dent
if
iercancont
ain.
d.Youcan'
tus
eaJavakeywor
dasani
dent
if
ier
.
e.I
dent
if
ier
sinJavaar
ecas
e-s
ens
iti
ve;f
ooandFOOar
etwodi
ff
erenti
dent
if
ier
s.
f
. Al
egali
dent
if
ierf
oravar
iabl
eisal
soal
egali
dent
if
ierf
oramet
hodoracl
ass
.
Nami
ngConvent
ions
:Javanami
ngconvent
ioni
sar
ulet
ofol
low asyoudeci
de
whatt
onameyouri
dent
if
ier
ssuchascl
ass
,package,var
iabl
e,cons
tant
,met
hod
et
c.But
,iti
snotf
orcedt
ofol
low.So,i
tisknownasconvent
ionnotr
ule.Al
lthe
cl
ass
es,i
nter
faces
,packages
,met
hodsandf
iel
dsofj
avapr
ogr
ammi
ngl
anguage
ar
egi
venaccor
dingt
ojavanami
ngconvent
ion.Advant
ageofnami
ngconvent
ions
i
njava:
Byus
ings
tandar
dJavanami
ngconvent
ions
,youmakeyourcodeeas
iert
o
r
eadf
oryour
sel
fandf
orot
herpr
ogr
ammer
s.Readabi
li
tyofJavapr
ogr
am i
sver
y
i
mpor
tant
.Iti
ndi
cat
est
hatl
esst
imei
sspentt
ofi
gur
eoutwhatt
hecodedoes
.
Name Convent
ion
s
houl
dst
artwi
thupper
cas
elet
terandbeanoune.
g.St
ring,
Col
or,
cl
assname
But
ton,
Sys
tem,
Thr
eadet
c.
s
houl
dst
artwi
thupper
cas
elet
terandbeanadj
ect
ivee.
g.
i
nter
face
name Runnabl
e,Remot
e,Act
ionLi
steneret
c.
method s
houl
dst
artwi
thl
ower
cas
elet
terandbeaver
be.
g.
name
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page17
UNI
TII Pr
ogr
ammi
ngCons
truct
s
act
ionPer
for
med(
),mai
n()
,pr
int
(),
pri
ntl
n()et
c.
vari
able s
houl
dst
artwi
thl
ower
cas
elet
tere.
g.f
irs
tName,
order
Numberet
c.
name
package s
houl
dbei
nlower
cas
elet
tere.
g.j
ava,
lang,
sql
,ut
ilet
c.
name
constant
s s
houl
dbei
nupper
cas
elet
ter
.e.
g.RED,
YELLOW,
MAX_
PRI
ORI
TYet
c.
name
Keywor
ds:
TheJavapr
ogr
ammi
ngl
anguagehast
otalof50r
eser
vedkeywor
ds
whi
chhaves
peci
almeani
ngf
ort
hecompi
lerandcannotbeus
edasvar
iabl
enames
.
Fol
lowi
ngi
sal
istofJavakeywor
dsi
nal
phabet
icalor
der
,cl
ickonani
ndi
vidual
keywor
dtos
eei
tsdes
cri
pti
onandus
ageexampl
e.
abs
tract as
ser
t bool
ean br
eak byt
e cas
e
cat
ch char cl
ass cons
t cont
inue def
aul
t
do doubl
e el
se enum ext
ends f
inal
f
inal
ly f
loat f
or got
o i
f i
mpl
ement
s
i
mpor
t i
nst
anceof i
nt i
nter
face l
ong nat
ive
new package pr
ivat
e pr
otect
ed publ
ic r
etur
n
s
hor
t s
tat
ic s
tri
ctf
p s
uper s
wit
ch
s
ynchr
oni
zed
t
his t
hrow t
hrows t
rans
ient t
ry voi
d
vol
ati
le whi
le
Poi
ntsr
egar
dingJavakeywor
ds:
o cons t
and
goto ar
er eseveredwordsbutnotus
ed.
o tr
ue,
fal
se
and null
arelit
erals,
notkeywor
ds.
o allkeywordsareinl ower-case.
Cat
egor
y Keywor
ds
Acces
s pr
i e,
vat
prot
ect
ed,
publ
ic
modi
fi
ers
Cl
ass
, abs
tr ,
act
clas
s,
ext ,
ends
fi ,
nal
impl
ement
s,
met
hod, i
nter
face,
nat
ive,
new,
stat
ic,
str
ict
fp,
synchr
oni
zed,
trans
i ,
ent
vol
ati
l
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page18
UNI
TII Pr
ogr
ammi
ngCons
truct
s
var
iabl
e e
modi
fi
ers
Fl
owcont
rol br
eak,
cas
e,
cont
inue,
def
aul
t,
do,
els
e,
for
,
if
,
ins
tanceof
,r
etur
n,
swi
tch,
whi
le
Package i
mpor
t,
package
cont
rol
Pr
imi
ti
ve bool
ean,
byt
e,
char
,
doubl
e,
fl
oat
,
int
,
long,
shor
t
t
ypes
Er
ror as
ser
t,
cat
ch,
final
ly,
thr
ow,
thr
ows
,
tr
y
handl
ing
Enumer
ati
on enum
Ot
her
s s
uper
,
thi
s,
voi
d
Unus
ed cons
t,got
o
Li
ter
als
:Li
ter
alsi
nJavaar
eas
equenceofchar
act
ers(
digi
ts,l
ett
ers
,andot
her
char
act
ers
)thatr
epr
esentcons
tantval
uest
obes
tor
edi
nvar
iabl
es.Li
ter
alscanbe
anynumber
,text
,orot
heri
nfor
mat
iont
hatr
epr
esent
saval
ue.Javal
anguage
s
peci
fi
esf
ivemaj
ort
ypesofl
it
eral
s.Theyar
e:I
ntegerl
it
eral
s,Fl
oat
ingl
it
eral
s,
Char
act
erl
it
eral
s,St
ringl
it
eral
s,andBool
eanl
it
eral
s.Eachoft
hem hasat
ype
as
soci
atedwi
thi
t.Thet
ypedes
cri
beshow t
heval
uesbehaveandhow t
heyar
e
s
tor
ed.
1.I
ntegerl
it
eral
s:I
ntegerdat
atypescons
istoft
hef
oll
owi
ngpr
imi
ti
vedat
atypes
:
i
nt,l
ong,byt
e,and s
hor
t.byt
e,i
nt,l
ong,and s
hor
tcan be expr
ess
ed i
n
deci
mal
(bas
e10)
,hexadeci
mal
(bas
e16)oroct
al(
bas
e8)numbers
yst
emsaswel
l.
Pr
efi
x0i
sus
edt
oindi
cat
eoct
alandpr
efi
x0xi
ndi
cat
eshexadeci
malwhenus
ing
t
hes
enumbers
yst
emsf
orl
it
eral
s.
Exampl
es:
intdeci
mal=100;i
ntoct
al=0144;i
nthexa=0x64;
2.Fl
oat
ing-
poi
nt l
it
eral
s:Fl
oat
ing-
poi
nt number
s ar
eli
ke r
eal number
sin
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page19
UNI
TII Pr
ogr
ammi
ngCons
truct
s
mat
hemat
ics
,forexampl
e,4.
13179,-
0.000001.Javahast
woki
ndsoff
loat
ing-
poi
ntnumber
s:f
loatanddoubl
e.Thedef
aul
ttypewhenyouwr
iteaf
loat
ing-
poi
ntl
it
erali
sdoubl
e,butyoucandes
ignat
eitexpl
ici
tl
ybyappendi
ngt
heD(
or
d)s
uff
ix.However
,thes
uff
ixF(
orf
)isappendedt
odes
ignat
ethedat
atypeofa
f
loat
ing-
poi
ntl
it
eralasf
loat
.Wecan al
sos
peci
fyaf
loat
ing-
poi
ntl
it
erali
n
s
cient
if
icnot
ati
onus
ingExponent(
shor
tEor
e),f
ori
nst
ance:t
hedoubl
eli
ter
al
0.
0314E2i
sint
erpr
etedas
:0.
0314*10²(
i.
e.3.
14)
.
fl
oatff=89.0f
;doubledou=89.
0D;doubledoub=89. 0d;
fl
oatf=89.0;//Typemismat
ch:cannotconvertf
rom doubl
etofl
oat
doubledoubl=89.0;//
OK,bydefaul
tfl
oatingpointl
it
erali
sdoubl
e
3.Bool
ean Li
ter
als
:The val
uest
rue and f
als
e ar
etr
eat
ed asl
it
eral
sin Java
pr
ogr
ammi
ng.Whenweas
signaval
uet
oabool
eanvar
iabl
e,wecanonl
yus
e
t
hes
etwoval
ues
.Unl
ikeC,wecan'
tpr
esumet
hatt
heval
ueof1i
sequi
val
entt
o
t
rueand0i
sequi
val
entt
ofal
sei
nJava.Wehavet
ous
etheval
uest
rueandf
als
e
t
orepr
esentaBool
eanval
ue.Exampl
ebool
eanchos
en=t
rue;
4.Nul
lLi
ter
als
:Thef
inall
it
eralt
hatwecanus
einJavapr
ogr
ammi
ngi
sanul
lli
ter
al.
Wes
peci
fyt
heNul
lli
ter
ali
nthes
our
cecodeas'
nul
l'
.Tor
educet
henumberof
r
efer
ences
toanobj
ect
,us
enul
lli
ter
al.Thet
ypeoft
henul
lli
ter
ali
sal
waysnul
l.
Wet
ypi
cal
lyas
signnul
lli
ter
alst
oobj
ectr
efer
encevar
iabl
es.
Fori
nst
ances=nul
l;
5.Char
act
erl
it
eral
s:chardat
atypei
sas
ingl
e16-
bitUni
codechar
act
er.Wecan
s
peci
fyachar
act
erl
it
eralasas
ingl
epr
int
abl
echar
act
eri
napai
rofs
ingl
equot
e
char
act
erss
uchas'
a','
#',and'
3'.Youmus
tknowaboutt
heASCI
Ichar
act
ers
et.
TheASCI
Ichar
act
ers
eti
ncl
udes128char
act
ersi
ncl
udi
ngl
ett
ers
,numer
als
,
punct
uat
ionet
c.Bel
owt
abl
eshowsas
etoft
hes
especi
alchar
act
ers
.
Escape
Meaning
\n
Newl i
ne
\t
Tab
\b
Backspace
\r
Carri
ageretur
n
\f
Formfeed
\\
Backslas
h
\'
Singl
e
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page20
UNI
TII Pr
ogr
ammi
ngCons
truct
s
quotat
ionmark
Double
\"
quotat
ionmark
\d
Octal
\xd
Hexadecimal
Unicode
\ud
char
acter
I
fwewantt
ospeci
fyas
ingl
equot
e,abacks
las
h,ora
non-
pri
ntabl
e char
act
eras
achar
act
erl
it
eralus
eanes
capes
equence.
Anes
capes
equenceus
esas
peci
al
s
ynt
ax
tor
epr
esent
sachar
act
er.Thes
ynt
axbegi
nswi
th as
ingl
ebacks
las
h
char
act
er.
6.St
ringLi
ter
als
:Thes
etofchar
act
ersi
nrepr
esent
edasSt
ringl
it
eral
sinJava.
Al
waysus
e"doubl
equot
es"f
orSt
ringl
it
eral
s.Ther
ear
efewmet
hodspr
ovi
ded
i
nJavat
ocombi
ne
str
ings
,modi
fys
tri
ngsandt
oknowwhet
hert
ost
ringshave
t
hes
ameval
ues
.
""
Theempt ystring
"\""
As t
ringcont aini
ng
"Thisi
sastr
ing"
As t
ringcont aini
ng16char acter
s
"Thisi
sa"+"two-li
ne
actuall
yas tring-
valuedcons t
antexpressi
on,
s t
ring" for
medf rom t wos t
ringl
it
er al
s
St
andar dDef
aultValues:I
njava,everyvar i
abl ehasadef aultvalue.Ifwedon’
t
i
nit
ial
izeavar
iabl
ewheni
tisf
irs
tcr
eat
ed,j
avapr
ovi
desdef
aul
tval
uet
othat
var
iabl
etypeaut
omat
ical
lyass
howni
nfol
lowi
ngt
abl
e:
TypeofVar i
abl
e Def aultValue
Byte 0( byte)
Short 0( short)
int 0
Long 0L
Float 0.0f
Doubl e 0.0d
Char nul lcharacter
Boolean false
Reference nul l
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page21
UNI
TII Pr
ogr
ammi
ngCons
truct
s
Oper
ator
s:Javapr
ovi
desar
ichs
etofoper
ator
s.Anoper
atori
sas
ymbolt
hat
t
ell
sthe comput
ert
o per
for
m cer
tai
n mat
hemat
icalorl
ogi
calmani
pul
ati
ons
.
Oper
ator
sar
eus
edi
npr
ogr
amst
omani
pul
atedat
aandvar
iabl
es.
Thef
oll
owi
ngt
abl
eshowst
her
elat
edcat
egor
ies
:
Categor y Oper
ator
s
Simpl e =
assignment
Ari
thmet ic +
-
* /
%
Unar y +
-
++ --!
Relational ==
!=
> >= <
<=
Condi ti
onal && || ?:(ternary)
Typecompar is
on inst
anceof
Bit
wi seandBit ~ << >> >>> & ^
|
shif
t
1.Si
mpl
eas
signment
:Thi
sist
hemos
tcommonl
yus
edoper
ator
.Itas
signst
he
val
ueoni
tsr
ightt
otheoper
andoni
tsl
eft
.Her
ear
esomeexampl
es:
As
signi
ngnumber
s:i
ntx=10;f
loaty=3.
5F;
As
signi
ng obj
ectr
efer
ences
:St
ring mes
sage = “Hel
lo wor
ld”;Fi
le cs
v = new
Fi
le(
“tes
t.cs
v”)
;
2.Ar
ithmet
icoper
ator
s:Thear
ithmet
icoper
ator
sar
eus
edt
oper
for
m mat
hemat
ic
cal
cul
ati
onsj
ustl
ikebas
icmat
hemat
icsi
nschool
.Thef
oll
owi
ngt
abl
eli
stsal
l
ar
ithmet
icoper
ator
sinJava:
Oper
ator Meaning
+ Additi
on( andstri
ngsconcat
enat
ion)
operator
- Subtractionoperator
* Multi
pl i
cati
onoper at
or
/ Divi
sionoper at
or
% Remai nderoperator
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page22
UNI
TII Pr
ogr
ammi
ngCons
truct
s
publi
cclas
sStringConcat Demo
{
publi
cstaticvoi dmai n(
Stri
ng[]args)
{
Stringf irs
tName="James ";
Stringl astName="Gos li
ng";
Stringgr eeting="Hell
o"+f i
rst
Name+""+l
ast
Name;
Syst em. out.
print
ln(
greeti
ng);
}
}
Output:
Hell
oJamesGos ling!
3.Unar
yoper
ator
s: Theunar
yoper
ator
sinvol
vei
nonl
yas
ingl
eoper
and.The
f
oll
owi
ngt
abl
eli
stsal
lunar
yoper
ator
sinJava:
Operator Meani ng
+ Unar yplusoperator;i
ndicatesposit
ive
value(number sarepos it
ivebydefault,
withoutt hi
soperator).
- Unar yminusoper at
or ;negatean
expressi
on.
++ Incrementoper at
or;increment savalue
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page23
UNI
TII Pr
ogr
ammi
ngCons
truct
s
by1.
-
- Decrementoperator
;decr
ement sa
val
ueby1;
! Logi
calcomplementoperator
;inver
ts
val
ueofabool ean.
Not
ethatt
hei
ncr
ementanddecr
ementoper
ator
scanbepl
acedbef
ore(
pref
ix)or
af
ter(
pos
tfi
x)t
heoper
and,e.
g.++xorx++,-
-yory-
-.Whenus
ingt
hes
etwof
ormsi
n
anexpr
ess
ion,
thedi
ff
erencei
s:
Pr
efi
xfor
m:t
heoper
andi
sincr
ement
edordecr
ement
edbef
oreus
edi
nthe
expr
ess
ion.
Pos
tfi
xfor
m:t
heoper
andi
sincr
ement
edordecr
ement
edaf
terus
edi
nthe
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page12
UNI
TII Pr
ogr
ammi
ngCons
truct
s
expr
ess
ion.
Thef
oll
owi
ngexampl
eil
lus
trat
est
hepr
efi
x/pos
tfi
x:
publiccl
assPref
ixPos
tfi
xDemo
{
publ i
cstati
cvoidmain(Str
ing[
]ar
gs)
{
intx=10;
inty=20;
System.out.
pri
ntl
n(++x);
System.out.
pri
ntl
n(x++);
System.out.
pri
ntl
n(x);
System.out.
pri
ntl
n(--
y);
System.out.
pri
ntl
n(y--
);
System.out.
pri
ntl
n(y);
}
}
Output:
11
11
12
19
19
18
4.Rel
ati
onaloper
ator
s:Ther
elat
ionaloper
ator
sar
eus
edt
ocompar
etwooper
ands
ort
woexpr
ess
ionsandr
esul
tisabool
ean.Thef
oll
owi
ngt
abl
eli
stsal
lrel
ati
onal
oper
ator
sinJava.
Operat
or Meaning
== equalto
!= notequalto
> great
erthan
>= great
erthanorequalt
o
< lesst
han
<= lesst
hanorequalto
publ
iccl
assRelat
ional
Demo
{
publi
cstat
icvoidmain(
Str
ing[
]ar
gs)
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page13
UNI
TII Pr
ogr
ammi
ngCons
truct
s
{
intx=10;
inty=20;
bool eanresult=x==y;
System. out.
print
ln(
"x==y?"+result
);
result=x! =y;
System. out.
print
ln(
"x!
=y?"+result);
result=x>y;
System. out.
print
ln(
"x>y?"+result
);
result=x>=y;
System. out.
print
ln(
"x>=y?"+result
);
result=x<y;
System. out.
print
ln(
"x<y?"+result
);
result=x<=y;
System. out.
print
ln(
"x<=y?"+result
);
}
}
Output:
x==y?f alse
x!
=y?t r
ue
x>y?f alse
x>=y?f alse
x<y?t rue
x<=y?t rue
5.Condi
ti
onaloper
ator
s:The condi
ti
onaloper
ator
s(&& and ||)ar
e us
ed t
o
per
for
m condi
ti
onal
-AND and condi
ti
onal
-OR oper
ati
ons on t
wo bool
ean
expr
ess
ionsandr
esul
tinabool
eanval
ue.
Theyhave“s
hor
t-ci
rcui
ti
ng”behavi
or:
Fort
he&& oper
ator
:ift
hel
eftexpr
ess
ioni
seval
uat
edt
ofal
se,t
hent
her
ight
expr
ess
ioni
snoteval
uat
ed.
Finalr
esul
tisf
als
e.
Fort
he||oper
ator
:ift
hel
eftexpr
ess
ion i
seval
uat
ed t
otr
ue,t
hen t
her
ight
expr
ess
ioni
snoteval
uat
ed.
Finalr
esul
tist
rue.
Oper
ator Meaning
&& condi
tional-ANDoper
ator
|| condi
tional-
ORoperat
or
?: ter
naryoperatori
nfor
m of:
A?B:
C
Exampl
ePr
ogr
am:
publ
iccl
assCondi
ti
onal
Demo
{
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page14
UNI
TII Pr
ogr
ammi
ngCons
truct
s
publicst
ati
cvoidmai n(Str
ing[
]ar
gs)
{
intx=10;
inty=20;
if((
x>8)&&(y>8) )
{
Syst
em.out.
printl
n("Bothxandyaregreaterthan8")
;
}
if((
x>10)||(y>10) )
{
Syst
em.out.
printl
n("Eit
herxoryi
sgreaterthan10");
}
}
}
Output:
Bothxandyar egreaterthan8
Ei
therxoryisgreaterthan10
Ot
hercondi
ti
onaloper
ator e?and:
sar whi
chf
orm at
ernar
y(t
hreeoper
ands
)int
he
f
oll
owi
ngf
orm:r
esul
t=A?B:C.Thi
sisi
nter
pret
edl
iket
his
:ifAeval
uat
est
otr
ue,
t
heneval
uat
esBandas
signi
tsval
uet
other
esul
t.Ot
her
wis
e,i
fAeval
uat
est
ofal
se,
t
heneval
uat
esCandas
signi
tsval
uet
other
esul
t.Fors
hor
t,wecans
ay:
IfAt
henB
el
seC.
Sot
hisi
sal
sor
efer
redass
hor
thandf
orani
f-
then-
els
est
atement
.
Exampl
e:
publicclassTernaryDemo
{
publi
cs t
at i
cvoidmain(Stri
ng[]args)
{
intx=10;
inty=20;
intresult=(x>10)?x: y;
System. out.
print
ln(
"result1is
: "+res
ult);
result=( y>10)?x:y;
System. out.
print
ln(
"result2is
: "+res
ult);
}
}
Output:result1is:20
r
esult2is:10
6.Typecompar i
sonoper at
or( i
nstanceof
):Theins
tanceofoper
atort
est
sifanobj
ect
i
sani
nst
anceofacl
ass
,as
ubcl
assoracl
asst
hati
mpl
ement
sani
nter
face;and
resultinabooleanval
ue.
Her
e’sanexamplepr
ogram:
JavaProgr
amming DeptofCSE,VVI
T Page15
UNI
TII Pr
ogr
ammi
ngCons
truct
s
publicclassI
nstanceofDemo
{
publ i
cs t
ati
cvoi dmain(Stri
ng[]args)
{
Str
ingname="Java";
i
f(namei nstanceofStr
ing)
{
System.out.pri
ntl
n("aninstanceofSt
ringcl
ass
");
}
}
}
Output:
aninstanceofSt ri
ngclass
7.Bi
twi
seandBi
tshi
ftoper
ator
s:Thes
eoper
ator
sper
for
m bi
twi
seandbi
tshi
ft
oper
ati
onsononl
yint
egr
alt
ypes
,notf
loatt
ypes
.Theyar
erar
elyus
eds
othel
ist
ing
her
eisj
ustf
orr
efer
ence:
Oper
ator Meani ng
~ unarybit wi
secompl ement
;inver
tsabi
t
pattern
<< si
gnedl eftshi
ft
>> si
gnedr ightshif
t
>>> unsignedr i
ghtshif
t
& bit
wi s
eAND
^ bit
wi s
eexcl usi
veOR
| bit
wi s
ei ncl
usiveOR
publicclas sBitDemo
{
publ i
cs tat i
cvoidmai n(St
ring[]args)
{
intx=10;
intres ult=x<<2;
System. out.print
ln(
"Beforeleftshift
:"+x);
System. out.pri
ntl
n("Aft
erleftshift
:"+resul
t);
}
}
Output:
Beforelefts hif
t:10
Aft
erlefts hift:
40
Expr es si
ons :
Anar i
thmet i
cexpr essi
onisacombi
nat
ionofvar
iabl
es,cons
tant
s,
andoper
ator
sar
rangedaspert
hes
ynt
axoft
hel
anguage.Javacanhandl
eany
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page16
UNI
TII Pr
ogr
ammi
ngCons
truct
s
compl
exmat
hemat
icalexpr
ess
ions
.
Al
gebr
aicexpr
ess
ion Javaexpr
ess
ion
ab-
c a*b-
c
(
m+n)
(x+y) (
m+n)
*(x+y)
3x2+2x+1 3*x*x+2*x+1
Eval
uat
ionofExpr
ess
ion:Express
ionsi
njavaareevaluatedus
inganas
signmentof
t
hef
orm var
iabl
e=expr
ess
ion;var
iabl
eisanyval
idj
avavar
iabl
ename.Whent
he
s
tat
ementi
sencount
ered,t
heexpr
ess
ioni
seval
uat
edf
ir
standt
her
esul
tthen
r
epl
acest
hepr
evi
ousval
ueoft
hevar
iabl
eont
hel
eft
-hands
ide.Al
lvar
iabl
esus
ed
i
ntheexpr
ess
ionmus
tbeas
signedval
uesbef
oreeval
uat
ioni
sat
tempt
ed.
Pr
ecedencer
ulesandAs
soci
ati
vit
y:Javaoper
ator
shavet
wopr
oper
tiest
hos
e
ar
epr
ecedence,andas
soci
ati
vit
y.Pr
ecedencei
sthepr
ior
ityor
derofanoper
ator
,if
t
her
ear
etwoormor
eoper
ator
sinanexpr
ess
iont
hent
heoper
atorofhi
ghes
t
pr
ior
itywi
llbeexecut
edf
irs
tthenhi
gher
,andt
henhi
gh.Forexampl
e,i
nexpr
ess
ion
1+2*5,mul
ti
pli
cat
ion(
*)oper
atorwi
llbepr
oces
sedf
ir
standt
henaddi
ti
on.I
t's
becaus
emul
ti
pli
cat
ionhashi
gherpr
ior
ityorpr
ecedencet
hanaddi
ti
on.
I
fal
loper
ator
sinanexpr
ess
ionhaves
amepr
ior
ityi
nsuchcas
ethes
econdpr
oper
ty
as
soci
atedwi
thanoper
atorcomesi
ntopl
ay,whi
chi
sas
soci
ati
vit
y.As
soci
ati
vit
y
t
ell
sthedi
rect
ionofexecut
ionofoper
ator
sthatcanbeei
therl
eftt
ori
ghtorr
ightt
o
l
eft
.
Forexampl
e,i
nexpr
ess
iona=b=c=8t
heas
signmentoper
atori
sexecut
edf
rom
r
ightt
olef
tthatmeanscwi
llbeas
signedby8,t
henbwi
llbeas
signedbyc,and
f
inal
lyawi
llbeas
signedbyb.Youcanpar
ent
hes
izet
hisexpr
ess
ionas(
a=(
b=(
c=
8)
)).
Thef
oll
owi
ngi
stheTabl
ewhi
chl
ist
sJavaoper
ator
s-pr
ecedencechar
thi
ghes
tto
l
owes
t.
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page17
UNI
TII Pr
ogr
ammi
ngCons
truct
s
Pr
ecedenceOper
ator Des
cri
pti
on As
soci
ati
vit
y
1 [
] ar
rayindex Lef
t->Ri
ght
(
) methodcall
. memberaccess
2 ++ preorpostf
ixi
ncrement Ri
ght-
>Lef
t
--
preorpostf
ixdecrement
+- unaryplus
,minus
~ bi
twiseNOT
! l
ogicalNOT
3 (t
ype typecast Ri
ght-
>Lef
t
cast
) objectcr
eati
on
new
4 * multi
pli
cat
ion Lef
t->Ri
ght
/ di
vis
ion
% modulus(r
emainder
)
5 +- addit
ion,subtr
acti
on Lef
t->Ri
ght
+ st
ringconcatenat
ion
6 << l
eftshi
ft
Lef
t->Ri
ght
>> si
gnedrights
hif
t
>>> unsi
gnedorzero-
fi
llr
ights
hif
t
7 < lessthan Lef
t->Ri
ght
<= lessthanorequalto
> greaterthan
>= greaterthanorequalt
o
ins
tanceofrefer
encet es
t
8 == equalt
o Lef
t->Ri
ght
!
= notequalt
o
9 & bi
twi
seAND Lef
t->Ri
ght
10 ^ bi
twi
seXOR Lef
t->Ri
ght
11 | bi
twi
seOR Lef
t->Ri
ght
12 && l
ogi
calAND Lef
t->Ri
ght
13 || l
ogi
calOR Lef
t->Ri
ght
14 ?: condi
ti
onal(
ter
nar
y) Ri
ght-
>Lef
t
15 = +=-= ass
ignmentands
hor
thandas
signment Ri
ght-
>Lef
t
*= /
= %= operat
ors
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page18
UNI
TII Pr
ogr
ammi
ngCons
truct
s
&= ^= |=
<<= >>=
>>>=
Pr
imi
ti
veTypeConvers
ionandCas
ting:Javas
uppor
tst
wot
ypesofcas
tings–
pr
imi
ti
vedat
atypecas
tingandr
efer
encet
ypecas
ting.Ref
erencet
ypecas
tingi
s
not
hingbutas
signi
ngoneJavaobj
ectt
oanot
herobj
ect
.Typecas
tingcomeswi
th3
cat
egor
ies
.
1.I
mpl
ici
tcas
ting(
wideni
ngconver
sion)
:Adat
atypeofl
owers
ize(
occupyi
ngl
ess
memor
y)i
sas
signedt
oadat
atypeofhi
ghers
ize.Thi
sisdonei
mpl
ici
tl
ybyt
heJVM.
Thel
owers
izei
swi
denedt
ohi
ghers
ize.Thi
sisal
sonamedasaut
omat
ict
ype
conver
sion.
Examples:
intx=10; //occupies4bytes
doubley=x; //occupies8bytes
System.
out.
pri
ntl
n(y); / /pr i
nts10.
0
I
nt heabovecode4bytesint
egervalueisass
ignedt
o8byt
esdoubl
eval
ue.
2.Expl
ici
tcas
ting(
nar
rowi
ngconver
sion)
:Adat
atypeofhi
ghers
ize(
occupyi
ng
mor
ememor
y)cannotbeas
signedt
oadat
atypeofl
owers
ize.Thi
sisnotdone
i
mpl
ici
tl
ybyt
heJVM and r
equi
resexpl
ici
tcas
ting;a cas
ting oper
ati
on t
o be
per
for
medbyt
hepr
ogr
ammer
.Thehi
ghers
izei
snar
rowedt
olowers
ize.
doublex=10.5; //8byt
es
i
nty=x; //4bytes;rais
escompilat
ioner
ror
Intheabovecode,8byt esdoubleval
ueisnar r
owedto4bytesintval
ue.Itr
aises
err
or.Letusexpli
cit
lytypecasti
t.
doublex=10.5;
i
nty=( i
nt)x;
Thedoubl exisexplici
tl
yconvertedtointy.Thethumbrul
eis,onbothsides,t
he
s
amedat
atypes
houl
dexi
st.
3.Bool
eancas
ting:Abool
eanval
uecannotbeas
signedt
oanyot
herdat
atype.
Exceptbool
ean,al
lther
emai
ning7dat
atypescanbeas
signedt
ooneanot
her
ei
theri
mpl
ici
tl
yorexpl
ici
tl
y;butbool
eancannot
.Wes
ay,bool
eani
sincompat
ibl
e
f
orconver
sion.
Maxi
mum wecanas
signabool
eanval
uet
oanot
herbool
ean.
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page19
UNI
TII Pr
ogr
ammi
ngCons
truct
s
Fol
lowingrai
seserr
or.
booleanx=t r
ue;
inty=x; /
/er
ror
booleanx=t r
ue;
inty=(i
nt)x; / /er
ror
byt
e–>s
hor
t–>i
nt–>l
ong–>f
loat–>doubl
e
I
ntheaboves
tat
ement
,lef
ttor
ightcanbeas
signedi
mpl
ici
tl
yandr
ightt
olef
t
r
equi
resexpl
ici
tcas
ting.Thati
s,byt
ecanbeas
signedt
oshor
timpl
ici
tl
ybuts
hor
t
t
obyt
erequi
resexpl
ici
tcas
ting.
Exampl
e:
publiccl
assDemo
{
publicst
ati
cvoidmai
n(St
ringar
gs[
])
{
charch1='A'
;
doubled1=ch1;
Sys
tem.
out
.pr
int
ln(
d1); //pr
int
s65.0
Sys
tem.
out
.pr
int
ln(
ch1*ch1)
; //print
s4225,
65*65
doubled2=66.0;
charch2=(char)d2;
Syst
em.out.pr
intl
n(ch2)
; /
/pr
int
sB
}
}
Fl
ow ofCont
rol
:AJavapr
ogr
am i
sas
etofs
tat
ement
s,whi
char
enor
mal
ly
execut
ed s
equent
ial
lyi
nthe or
deri
n whi
ch t
heyappear
.Thi
shappenswhen
opt
ionsorr
epet
iti
onsofcer
tai
ncal
cul
ati
onsar
enotneces
sar
y.
Whenapr
ogr
am br
eakst
hes
equent
ialf
lowandj
umpst
oanot
herpar
toft
hecode,
i
tiscal
ledbr
anchi
ng.Whent
hebr
anchi
ngi
sbas
edonapar
ticul
arcondi
ti
on,i
tis
knownascondi
ti
onalbr
anchi
ng.I
tthebr
anchi
ngt
akespl
acewi
thoutanydeci
sion,
i
tisknownasuncondi
ti
onalbr
anchi
ng.
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page20
UNI
TII Pr
ogr
ammi
ngCons
truct
s
1.
Condi
ti
onalSt
atement
s:t
hes
econdi
ti
onals
tat
ement
sincl
udet
hef
oll
owi
ng
a)i
fel
ses
tat
ement
b)nes
tedi
fst
atement
c)i
fel
sei
fladder
d)s
wit
chcas
est
atement
2.
Iter
ati
onSt
atement
s:t
hes
eit
erat
ions
tat
ement
sincl
udet
hef
oll
owi
ng
a)whi
lel
oop
b)dowhi
lel
oop
c)f
orl
oop
3.
JumpSt
atement
s:t
hes
ejumps
tat
ement
sincl
udet
hef
oll
owi
ng
a)br
eak
b)cont
inue
c)r
etur
n
1.
Condi
ti
onalSt
atement
s:
a)i
fel
ses
tat
ement
:Thi
sst
atementi
sus
edt
oper
for
m at
askdependi
ngupon
whet
hert
hegi
vencondi
ti
oni
str
ueorf
als
e.Her
eat
askr
epr
esent
ssi
ngl
est
atement
orgr
oupofs
tat
ement
s.
Synt ax:i
f(condit
ion)
{
//statement s;
}
el
s e
{
//Statement s;
}
Her eifconditioni
str
uet
hens
tat
ement
1wi
llbeexecut
ed.i
fcondi
ti
oni
sfal
se
t
hens
tat
ement
2wi
llbeexecut
ed.s
tat
ement
1ands
tat
ement
2repr
esentei
thera
s
ingl
est
atement
sormor
ethanones
tat
ement
.Ifmor
ethanones
tat
ementi
sus
ed
t
hent
heys
houl
dbeencl
osedi
nangul
arbr
acket{
}.
E.
g.:
if(
a>b)
Syst
em.
out
.pr
int
ln(
“theval
ueofa=”+a)
;
else
Syst
em.
out
.pr
int
ln(
“theval
ueofb=”+b)
;
b)Nestedifs
tat
ement
:Anes
tedi
fisani
fstat
ementthati
sthet
argetofanot
herifor
JavaPr
ogr
amming DeptofCSE,VVI
T Page21
UNI
TII Pr
ogr
ammi
ngCons
truct
s
el
se.
Nes
tedi
fsar
ever
ycommoni
npr
ogr
ammi
ng.
Whenyounes
tif
s,t
hemai
nthi
ng
t
orememberi
sthatanel
ses
tat
emental
waysr
efer
stot
henear
esti
fst
atementt
hat
i
swi
thi
nthes
amebl
ockast
heel
seandt
hati
snotal
readyas
soci
atedwi
thanel
se.
Syntax:i
f(condi ti
on1)
{
if
(condi t
ion2)
//St atement s1;
else
//St atement s2;
}
else
//Stat ements3;
E.g.
:if(
i==10)
{
if
(j<20)
a=b;
else
a=c;/ /as sociat
edwi ththi
sels
e
}
else
a=d;/ /thiselsereferst
oif(
i==10)
c) i
f-
els
e-i
fLadder
:A common pr
ogr
ammi
ng cons
tructt
hati
sbas
ed upon a
s
equenceofnes
tedi
fsi
sthei
f-
els
e-i
fladder
.
Syntax: i
fcondi
( t
ion)
//statement ;
el
s eifcondi
( t
ion)
//s tat
ement ;
el
s eifcondi
( t
ion)
//s t
atement ;
el
s e
//st
atement ;
Thei fstatementsareexecut
edf
rom t
het
opdown.Ass
oonasoneoft
hecondi
ti
ons
cont
rol
li
ngt
hei
fist
rue,t
hes
tat
ementas
soci
atedwi
tht
hati
fisexecut
ed,andt
he
r
estoft
hel
adderi
sbypas
sed.I
fnoneoft
hecondi
ti
onsi
str
ue,t
hent
hef
inalel
se
s
tat
ementwi
llbeexecut
ed.Thef
inalel
seact
sasadef
aul
tcondi
ti
on;t
hati
s,i
fal
l
ot
hercondi
ti
onalt
est
sfai
l,t
hent
hel
astel
ses
tat
ementi
sper
for
med.I
fther
eisno
f
inalel
seandal
lot
hercondi
ti
onsar
efal
se,
thennoact
ionwi
llt
akepl
ace.
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page22
UNI
TII Pr
ogr
ammi
ngCons
truct
s
E.
g.:i
ntfib(i
ntm)
{
if
(m==1)
r
eturn1;
else
i
f(m==2)
return1;
else
ret
urn(f
ib(
m-1)
+fi
b(m-
2))
;
}
d)s
wit
ch:
Thes
wit
chs
tat
ementi
sJava’
smul
ti
waybr
anchs
tat
ement
.Itpr
ovi
desan
eas
ywayt
odi
spat
chexecut
iont
odi
ff
erentpar
tsofyourcodebas
edont
heval
ueof
anexpr
ess
ion.Ass
uch,i
tof
tenpr
ovi
desabet
teral
ter
nat
ivet
hanal
arges
eri
esofi
f-
el
se-
ifs
tat
ement
s.
Synt
ax:switch( expressi
on)
{
caseval ue1:
//stat ements equence
break;
caseval ue2:
//stat ements equence
break;
..
.
caseval ueN:
//stat ements equence
break;
defaul t:
//def aultst
atements equence
}
The expr es s
ion mus tbeoft ypebyt
e,s
hor
t,i
nt,orchar he val
;each oft ues
s
peci
fi
edi
nthecas
est
atement
smus
tbeofat
ypecompat
ibl
ewi
tht
heexpr
ess
ion.
Eachcas
eval
uemus
tbeauni
quel
it
eral(
thati
s,i
tmus
tbeacons
tant
,nota
var
iabl
e).
Dupl
icat
ecas
eval
uesar
enotal
lowed.
E.g.
:swi t
ch(i)
{
cas e0:Sys tem.
out.
print
ln(
"ii
sz er
o. ")
;
break;
cas e1:Sys tem.
out.
print
ln(
"ii
sone. ");
break;
case2: Sys t
em.out
.pri
ntl
n("ii
stwo.") ;
JavaProgrammi ng DeptofCSE,
VVI
T Page23
UNI
TII Pr
ogr
ammi
ngCons
truct
s
break;
cas
e3:System.out.
pri
ntl
n("iisthr
ee.
");
br
eak;
def
ault
:System.out
.pr
int
ln("iisgr
eat
erthan3.
");
}
2.I
ter
ati
onSt
atement
s:Java’
sit
erat
ions
tat
ement
sar
efor
,whi
le,anddo-
whi
le.
Thes
est
atement
scr
eat
ewhatwecommonl ll
ycal oops
.Asyoupr
obabl
yknow,a
l
oopr
epeat
edl
yexecut
est
hes
ames
etofi
nst
ruct
ionsunt
ilat
ermi
nat
ioncondi
ti
on
i
smet
.
a)whi
lel
oop:
Thewhi
lel
oopi
sJava’
smos
tfundament
all
oops
tat
ement
.Itr
epeat
s
as
tat
ementorbl
ockwhi
lei
tscont
rol
li
ngexpr
ess
ioni
str
ue.
Syntax:
whil condi
e( ti
on)
{
//bodyofloop
}
Thecondit
ioncanbeanyBool
eanexpr
ess
ion.
Thebodyoft
hel
oopwi
llbeexecut
ed
asl
ongast
hecondi
ti
onalexpr
ess
ioni
str Whencondi
ue. ti
onbecomesf
als
e,cont
rol
pas
sest
othenextl
ineofcodei
mmedi
atel
yfol
lowi
ngt
hel
oop.Thecur
lybr
acesar
e
unneces
sar
yifonl
yas
ingl
est
atementi
sbei
ngr
epeat
ed.
E.
g.:
whi l
e(c<n)
{
a=b;
b=c;
c=a+b;
}
b)do-
whi
lel
oop:I
fthecondi
ti
onalexpr
ess
ioncont
rol
li
ngawhi
lel
oopi
sini
ti
all
y
f
als
e,t
hent
hebodyoft
hel
oopwi
llnotbeexecut
edatal
l.However
,somet
imesi
tis
des
irabl
eto execut
ethebodyofal
oop atl
eas
tonce,even i
fthecondi
ti
onal
expr
ess
ioni
sfal
set
obegi
nwi
th.I
not
herwor
ds,t
her
ear
eti
meswhenyouwoul
d
l
iket
otes
tthet
ermi
nat
ionexpr
ess
ionatt
heendoft
hel
oopr
athert
hanatt
he
begi
nni
ng.For
tunat
ely,Javas
uppl
iesal
oopt
hatdoesj
ustt
hat
:thedo-
whi
le.The
do-
whi
lel
oop al
waysexecut
esi
tsbodyatl
eas
tonce,becaus
eit
scondi
ti
onal
expr
ess
ioni
satt
hebot
tom oft
hel
oop.
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page24
UNI
TII Pr
ogr
ammi
ngCons
truct
s
Synt
ax:do
{
//bodyofloop
}whil
e(condit
ion);
Eachi
ter
ationofthedo- whi
lel
oopf
irs
texecut
est
hebodyoft
hel
oopandt
hen
eval
uat
est
hecondi
ti
onalexpr
ess
ion.I
fthi
sexpr
ess
ioni
str
ue,t
hel
oopwi
llr
epeat
.
Ot
her
wis
e,t
hel
oopt
ermi
nat
es.Aswi
thal
lofJava’
sl ,condi
oops ti
onmus
tbea
Bool
eanexpr
ess
ion.
The do-
whi
lel
oop i
ses
peci
all
yus
efulwhen you pr
oces
sa menu s
elect
ion,
becaus
eyouwi
llus
ual
lywantt
hebodyofamenul
oopt
oexecut
eatl
eas
tonce.
Cons
idert
hef
oll
owi
ngpr
ogr
am,whi
chi
mpl
ement
saver
ysi
mpl
ehel
psys
tem f
or
Java’
ssel
ect
ionandi
ter
ati
ons
tat
ement
s:
E.
g.:i
ntn=10;
do
{
Sys
tem.out.
pri
ntl
n(n)
;
n--
;
}whil
e(n>0)
;
c)f
orl
oop:Thet
radi
ti
onalf
ormt
hathasbeeni
nus
esi
ncet
heor
igi
nalver
sionof
Java.When t
hel
oop s
tar
ts,t
hei
nit
ial
izat
ion por
tion oft
hel
oop i
sexecut
ed.
I
nit
ial
izat
ionexpr
ess
ionexecut
edonl
yonceandt
hencondi
ti
oni
seval
uat
ed.Thi
s
mus
tbeaBool
eanexpr
ess
ion.
Checkt
hecondi
ti
on;i
fthecondi
ti
oni
str
ue,
thent
he
bodyoft
hel
oopi
sex
ecut
ed.I
fiti
sfai
l,t
hel
oopt
ermi
nat
es.Next
,thei
ter
ati
on
por
tionoft
hel
oop i
sexecut
ed and goest
oincr
ementordecr
ementt
hel
oop
cont
rolvar
iabl
eandagai
ncheckst
hecondi
ti
oni
fiti
str
ue,t
hent
hebodyoft
he
l
oopi
sexecut
ed.
Thi
spr
oces
sisr
epeat
edupt
othecondi
ti
oni
sfai
l.
Syntax:tradi
tionalf
orst
atement:
fori
(ni
tiali
zati
on;condit
ion;i
ter
ati
on)
{
//body
}
E.g.
:for (
i=1;
i<=n;i
++)
{
a=b;
b=c;
c=a+b;
JavaPr
ogrammi ng DeptofCSE,
VVI
T Page25
UNI
TII Pr
ogr
ammi
ngCons
truct
s
}
Declari
ngLoopCont rolVar
iabl
esInsi
detheforLoop
f
or(datatypei
nit
ial
izati
on;condit
ion;i
ter
ati
on)
{
//body
}
E.
g.:for(
inti=1;
i<=n;
i++)
{
a=b;
b=c;
c=a+b;
3.JumpSt at
ement s:
Javasuppor
tst
hreej
umps
tat
ement
s:br
eak,
cont
inue,
and
r
etur
n.Thes
est
atement
str
ans
fercont
rolt
oanot
herpar
tofyourpr
ogr
am.
a)br
eak:
InJava,
thebr
eaks
tat
ementhast
hreeus
es.
i
tter
minat
esas
tat
ements
equencei
nas
wit
chs
tat
ement
.
i
tcanbeus
edt
oexi
tal
oop.
i
tcanbeus
edasa“ci
vil
ized”f
orm ofgot
o.
Thel
astt
wous
esar
eexpl
ainedher
e.
Us
ingbr
eakt
oExi
taLoop:
Byus
ingbr
eak,youcanf
orcei
mmedi
atet
ermi
nat
ionof
al
oop,bypas
singt
hecondi
ti
onalexpr
ess
ionandanyr
emai
ningcodei
nthebodyof
t
he l
oop.When a br
eak s
tat
ementi
sencount
ered i
nsi
de a l
oop,t
he l
oop i
s
t
ermi
nat
edandpr
ogr
am cont
rolr
esumesatt
henexts
tat
ementf
oll
owi
ngt
hel
oop.
E.g.
:for (
inti=0;i
<100;i++)
{
if(i==10)
break;/ /ter
minatel oopifiis10
Sys tem.out.
pri
ntln("i:"+i)
;
}
Labelledbr eak:j
avasuppor t
slabell
edbr
eak
Syntax:
breaklabel
;
booleant=true;
fi
rst:
{
second:
{
thi
rd:
{
System.out
.pri
ntl
n("Bef
oret
hebr
eak.
");
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page26
UNI
TII Pr
ogr
ammi
ngCons
truct
s
i
f(t
)
breaks econd;/ /breakoutofsecondblock
System.out .
printl
n("Thiswon'
texecute")
;
}
}
System.out .
printl
n("Thisi
saft
ersecondblock.
");
}
Output:
Beforethebr eak.
Thisisaftersecondbl ock.
b)cont
inue:
Thecont
inues
tat
ementper
for
mss
uchanact
ion.
Inwhi
leanddo-
whi
le
l
oops
,a cont
inue s
tat
ementcaus
escont
rolt
o be t
rans
fer
red di
rect
lyt
othe
condi
ti
onalexpr
ess
iont
hatcont
rol
sthel
oop.I
naf
orl
oop,cont
rolgoesf
ir
stt
othe
i
ter
ati
onpor
tionoft
hef
ors
tat
ementandt
hent
othecondi
ti
onalexpr
ess
ion.Foral
l
t
hreel
oops
,anyi
nter
medi
atecodei
sbypas
sed.
E.
g.:for(
inti=0;i<10;i
++)
{
System. out.pr
int
(i+"");
if(i
%2==0)cont i
nue;
System.out .
pri
ntl
n("")
;
}
c)r
etur
n:Thel
astcont
rols
tat
ementi
sret
urn.Ther
etur
nst
atementi
sus
edt
o
expl
ici
tl
yret
urnf
rom amet
hod.Thati
s,i
tcaus
espr
ogr
am cont
rolt
otr
ans
ferback
t
othecal
leroft
hemet
hod.Ass
uch,i
tiscat
egor
izedasaj
umps
tat
ement
.Atany
t
imei
namet
hodt
her
etur
nst
atementcanbeus
edt
ocaus
eexecut
iont
obr
anch
back t
othe cal
leroft
he met
hod.Thus
,the r
etur
nst
atementi
mmedi
atel
y
t
ermi
nat
est
hemet
hodi
nwhi
chi
tisexecut
ed.Her
e,r
etur
ncaus
esexecut
iont
o
r
etur
ntot
heJavar
un-
ti
mes
yst
em,
sincei
tist
her
un-
ti
mes
yst
em t
hatcal
lsmai
n()
.
E.
g.:
intfi
b(intm)
{
if
(m==1)
return1;
elseif
(m==2)
return1;
else
return(f
ib(
m-1)
+fi
b(m-
2))
;
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page27
UNI
TII Pr
ogr
ammi
ngCons
truct
s
Cl
ass
esandObj
ect
s:Javai
sat
rueobj
ect
-or
ient
edl
anguageandt
her
efor
ea
j
avapr
ogr
am mus
tbeencaps
ulat
edi
nacl
asst
hatdef
inest
hes
tat
eandbehavi
orof
t
hebas
icpr
ogr
am component
sknownasObj
ect
s.
Cl
ass
:A cl
ass can be def
ined as a t
empl
ate/
blue pr
intt
hatdes
cri
bes t
he
behavi
ors
/st
atest
hatobj
ectofi
tst
ypes
uppor
t.I
tisacombi
nat
ionofdat
ait
ems
andf
unct
ionswhi
char
ecal
ledasmember
sofcl
ass
.
TheGeneralForm ofaClass
cl
assCl
assName[ ext
endsSuperCl
assName]
{
[
typeinstanceVar
iabl
e1;]
[
typeinstanceVar
iabl
e2;]
[
typemet hodName1( par
ameter-
li
st)
{
//bodyofmet hod
}
]
[
typemet hodName2( par
ameter-
li
st)
{
//bodyofmet hod
}
]
}
Ever
ythi
ngi
nsi
det
hes
quar
ebr
acket
sisopt
ional
.Ther
efor
e,t
hef
oll
owi
ngi
saval
id
cl
assdef
ini
ti
on:
cl
assEmpt
y
{
}
Thedat
a,orvar
iabl
es,def
inedwi
thi
nacl
assar
ecal
ledi
nst
ancevar
iabl
es.Thecode
i
scont
ained wi
thi
n met
hods
.Col
lect
ivel
y,t
he met
hodsand var
iabl
esdef
ined
wi
thi
nacl
assar
ecal
ledmember
soft
hecl
ass
.Var
iabl
esdef
inedwi
thi
nacl
assar
e
cal
ledi
nst
ancevar
iabl
esbecaus
eeachi
nst
anceoft
hecl
ass(
thati
s,eachobj
ectof
t
hecl
ass
)cont
ainsi
tsowncopyoft
hes
evar
iabl
es.
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page28
UNI
TII Pr
ogr
ammi
ngCons
truct
s
Obj
ect
:Anobj
ecti
njavai
ses
sent
ial
lyabl
ockofmemor
ythatcont
ainss
pacet
o
s
tor
ethei
nst
ancevar
iabl
es.Cr
eat
inganobj
ecti
sal
sor
efer
stoasi
nst
ant
iat
ingan
obj
ect
.Obj
ect
sar
ecr
eat
edus
ing“new”oper
ator
.Thenew oper
atordynami
cal
ly
al
locat
esmemor
yforanobj
ectandr
etur
nsr
efer
encet
othatobj
ect
.
Cl
ass
Namecn; /
/decl
aret
her
efer
encevar
iabl
e
cn=newCl
ass
Name(
);/
/ins
tant
iat
etheobj
ect
Thef
irs
tst
atementdecl
aresavar
iabl
etohol
dtheobj
ectr
efer
enceandt
hes
econd
oneact
ual
lyas
signst
heobj
ectr
efer
encet
othevar
iabl
e.Thevar
iabl
ecni
snowan
obj
ectoft
heCl
ass
Name.
Bot
hSt
atement
scanbecombi
nedi
ntoones
tat
ement
:Cl
ass
Namecn=new
Cl
ass
Name(
);
I
tisi
mpor
tantt
ounder
standt
hatanychangest
othevar
iabl
esofoneobj
ecthave
noef
fectont
hevar
iabl
esofanot
her
.
Acces
singCl
assMember
s:Eachobj
ectofacl
assi
shavi
ngi
tsowns
etofvar
iabl
es,
wes
houl
das
signval
uest
othes
evar
iabl
esi
nor
dert
ous
ethem i
nourpr
ogr
am.
The
f
oll
owi
ngi
sthepr
ocedur
eforacces
singavar
iabl
eandamet
hodr
espect
ivel
y.
obj
ect
name.
var
iabl
ename=val
ue;
obj
ect
name.
met
hodname(
);
Example:Program toil
lustr
atecl
assmembers:
importjava.
util
.*;
clas
sExampl e
{
intnum1, num2;
voidmet hod()
{
System.out.
print
ln(
“Num1valuei
s“+num1+”Num2val
uei
s“+num2)
;
}
publ i
cstati
cvoidmai n(
Stri
ngar
gs[]
)
{
Examplee=newExampl e(
);
e.
num1=12;
e.
num2=22;
e.
met hod();
}
}
Output:
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page29
UNI
TII Pr
ogr
ammi
ngCons
truct
s
Num1val
uei
s12Num2val
uei
s22
Met
hods
:Cl
ass
esus
ual
lycons
istoft
wot
hings
:ins
tancevar
iabl
esandmet
hods
.
Met
hodi
sal
argeonebecaus
eJavagi
vest
hem s
omuchpowerandf
lexi
bil
it
y.Thi
s
i
sthegener
alf
orm ofamet
hod:
ret
urntypemethodName(par
amet er
-l
ist
)
{
//bodyofmethod
}
Here,r
et nt
ur ypespeci
fi
esthetypeofdatar
etur
nedbyt
hemet
hod.Thi
scanbeany
val
idt
ype,i
ncl
udi
ngcl
asst
ypest
hatyoucr
eat
e.I
fthemet
hoddoesnotr
etur
na
val
ue,
itsr
etur
ntypemus
tbevoi
d.
Met
hodnamecanbeanyl
egali
dent
if
ierot
hert
hant
hos
eal
readyus
edbyot
her
i
temswi
thi
nthecur
rents
cope.
The par
amet
er-
li
sti
sa s
equence oft
ype and i
dent
if
ierpai
rss
epar
ated by
commas
.Par
amet
ers ar
e es
sent
ial
ly var
iabl
es t
hatr
ecei
ve t
he val
ue oft
he
ar
gument
spas
sedt
othemet
hodwheni
tiscal
led.
I
fthemet
hodhasnopar
amet
ers
,thent
hepar
amet
erl
istwi
llbeempt
y.
Met
hodst
hathavear
etur
ntypeot
hert
hanvoi
dret
urnaval
uet
othecal
li
ng
r
out
ineus
ingt
hef
oll
owi
ngf
orm oft
her
etur
nst
atement
:ret
urnval
ue;her
e,val
uei
s
t
heval
uer
etur
ned.
Example:
cl
assMet hodDemo
{
inta,b,
c;
intshow( )
{
returna*b*c;
}
voidvar (
intx,
inty,i
ntz
)
{
a=x;
b=y;
c=z;
}
}
cl
assParaMai n
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page30
UNI
TII Pr
ogr
ammi
ngCons
truct
s
{
publ
icstat
icvoidmain(Str
ingar
gs[]
)
{
i
ntd;
MethodDemomdr =newMethodDemo(
);
md.var(
10,2,
3);
d=md.show();
Syst
em.out.pr
intl
n("Dval
ue:"+d)
;
}
}
Output:
Dvalue:60
Cons
truct
ors
:Cons
truct
ori
njavai
sas
peci
alt
ypeofmet
hodt
hati
sus
edt
o
i
nit
ial
izet
heobj
ect
.Javacons
truct
ori
sinvokedatt
het
imeofobj
ectcr
eat
ion.I
t
cons
truct
stheval
uesi
.e.pr
ovi
desdat
afort
heobj
ectt
hati
swhyi
tisknownas
cons
truct
or.
Ther
ear
ebas
ical
lyt
wor
ulesdef
inedf
ort
hecons
truct
or.
Cons
truct
ornamemus
tbes
ameasi
tscl
assname
Cons
truct
ormus
thavenoexpl
ici
tret
urnt
ype
Ther
ear
etwot
ypesofcons
truct
ors
:
Def
aul
t cons
truct
or (
no-
arg cons
truct
or)
:A cons
truct
or t
hat has no
par
amet
eri
sknownasdef
aul
tcons
truct
or.
Par
amet
eri
zedcons
truct
or:Acons
truct
ort
hathaspar
amet
ersi
sknownas
par
amet
eri
zedcons
truct
or.
Def
aul
tcons
truct
or:Def
aul
tcons
truct
orpr
ovi
dest
hedef
aul
tval
uest
otheobj
ect
l
ike0,
nul
let
c.dependi
ngont
het
ype.
Exampl
e:
cl
assConst
ructorDemo
{
Cons
tructorDemo()
{
System.out
.pr
int
ln(
“Def
aul
tCons
truct
or”)
;
}
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page31
UNI
TII Pr
ogr
ammi
ngCons
truct
s
publ
icstat
icvoi
dmain(
Str
ingar
gs[
])
{
Constr
uctor
Democd=newConst
ruct
orDemo(
);
}
}
Out
put
:Def
aul
tCons
truct
or
Not
e:I
fther
eisnocons
truct
ori
nacl
ass
,compi
leraut
omat
ical
lycr
eat
esadef
aul
t
cons
truct
or.
Par
amet
eri
zedcons
truct
or:Par
amet
eri
zedcons
truct
ori
sus
edt
opr
ovi
dedi
ff
erent
val
uest
othedi
sti
nctobj
ect
s.
Exampl
e:
cl
assCons t
ructorDemoOne
{
intnum1, num2;
ConstructorDemoOne( i
ntn1,i
ntn2)
{
num1=n1;
num2=n2;
}
voiddisplay()
{
System.out.
pri
ntln(
“Num1valuei
s“+num1+”Num2valueis”+num2)
;
}
publicstati
cvoidmain(Stri
ngargs
[])
{
Cons t
ructor
DemoOnecd=newCons t
ruct
orDemoOne(
2,5)
;
cd.dis
play()
;
}
}
Output:
Num1val ueis2Num2val ueis5.
Cons
truct
orOver
loadi
ng:A cons
truct
orcan al
so beover
loaded.Over
loaded
cons
truct
orsar
edi
ff
erent
iat
edont
hebas
isoft
hei
rtypeofpar
amet
ersornumber
ofpar
amet
ers
.Cons
truct
orover
loadi
ng i
s notmuch di
ff
erentt
han met
hod
over
loadi
ng.I
ncas
eofmet
hodover
loadi
ngyouhavemul
ti
plemet
hodswi
ths
ame
name butdi
ff
erents
ignat
ure,wher
eas i
n Cons
truct
orover
loadi
ng you have
mul
ti
plecons
truct
orwi
thdi
ff
erents
ignat
urebutonl
ydi
ff
erencei
sthatCons
truct
or
does
n'thaver
etur
ntypei
nJava.Cons
truct
orover
loadi
ngi
sdonet
ocons
truct
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page32
UNI
TII Pr
ogr
ammi
ngCons
truct
s
obj
ecti
ndi
ff
erentways
.
Example:
cl
assCons t
ructorOLDemo }
{ publ
ics tati
c voi d mai
n(Str
ing
intnum1, num2; args[
])
ConstructorOLDemo(
) {
{ Cons t
r uctor
OLDemo
num1=num2=0; cd=newCons tructor OLDemo()
;
} cd.display()
;
ConstructorOLDemo(
int n1,
int Cons t
r uctor
OLDemo
n2) cd1=newCons tructor OLDemo(2,
5);
{ cd1.display()
;
num1=n1; }
num2=n2; }
}
voiddisplay(
) Out
put:
{ Num1valuei
s0Num2val
uei
s0.
Num1valuei
s2Num2val
uei
s5.
System.
out
.pr
int
ln(
“Num1 value i
s
“+num1+”Num2valuei
s”+num2)
;
Ther
eisnocopycons
truct
ori
njava.But
,wecancopyt
heval
uesofoneobj
ectt
o
anot
herl
ikecopycons
truct
ori
nC++.
cl
assCopyDemo
{
intnum1,
num2;
CopyDemo()
{
num1=num2=0;
}
CopyDemo(intn1,intn2)
{
num1=n1;
num2=n2;
}
CopyDemo(CopyDemocd)
{
num1=cd.num1;
num2=cd.num2;
}
voiddi
spl
ay()
{
Sys
tem.out.print
ln(
“Num1val
uei
s“+num1+”Num2val
uei
s”+num2)
;
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page33
UNI
TII Pr
ogr
ammi
ngCons
truct
s
}
publ
icstati
cvoi dmai n(
Str
ingar
gs[
])
{
CopyDemocd=newCopyDemo( )
;
cd.dis
pl ay()
;
CopyDemocd1=newCopyDemo( 2,5)
;
cd1.display()
;
CopyDemocd2=newCopyDemo( cd1);
cd2.display()
;
}
}
Out
put:
Num1valuei
s0Num2val
uei
s0.
Num1valuei
s2Num2val
uei
s5.
Num1valuei
s2Num2val
uei
s5.
Gar
bage Col
lect
or:I
njava,gar
bage means unr
efer
enced obj
ect
s.Gar
bage
Col
lect
ioni
spr
oces
sofr
ecl
aimi
ngt
her
unt
imeunus
edmemor
yaut
omat
ical
ly.I
n
ot
herwor
ds,
iti
sawayt
odes
troyt
heunus
edobj
ect
s.
Todos
o,wewer
eus
ingf
ree(
)funct
ioni anguageanddel
nCl ete(
)inC++.But
,in
j
avai
tisper
for
medaut
omat
ical
ly.
So,
javapr
ovi
desbet
termemor
ymanagement
.
Advant
ageofGar
bageCol
lect
ion:I
tmakesj
avamemor
yef
fi
cientbecaus
egar
bage
col
lect
orr
emovest
heunr
efer
encedobj
ect
sfr
om heapmemor
y.I
tisaut
omat
ical
ly
donebyt
hegar
bagecol
lect
or(
apar
tofJVM)s
owedon'
tneedt
omakeext
raef
for
ts.
Anobj
ectcanbeunr
efer
enced.
Ther
ear
emanyways
:
Bynul
li
ngt
her
efer
ence
Byas
signi
ngar
efer
encet
oanot
her
1)Bynul
li
ngar
efer
ence:
Employeee=newEmpl
oyee(
);
e=nul
l;
2)Byas
signi
ngar
efer
encet
oanot
her
:
Empl
oyeee1=newEmpl
oyee(
);
Empl
oyeee2=newEmpl
oyee(
);
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page34
UNI
TII Pr
ogr
ammi
ngCons
truct
s
e1=e2;
//nowt
hef
irs
tobj
ectr
efer
redbye1i
savai
labl
eforgar
bagecol
lect
ion
f
inal
ize(
)met
hod:
Thef
inal
ize(
)met
hodi
sinvokedeacht
imebef
oret
heobj
ecti
s
gar
bagecol
lect
ed.Thi
smet
hodcanbeus
edt
oper
for
m cl
eanuppr
oces
sing.Thi
s
met
hodi
sdef
inedi
nObj
ectcl
assas
:pr
otect
edvoi
dfi
nal
ize(
){}
Not
e:TheGar
bagecol
lect
orofJVM col
lect
sonl
ythos
eobj
ect
sthatar
ecr
eat
edby
new keywor
d.Soi
fyouhavecr
eat
edanyobj
ectwi
thoutnew,youcanus
efi
nal
ize
met
hodt
oper
for
m cl
eanuppr
oces
sing(
des
troyi
ngr
emai
ningobj
ect
s).
gc(
)met
hod:
Thegc(
)met
hodi
sus
edt
oinvoket
hegar
bagecol
lect
ort
oper
for
m
cl
eanuppr
oces
sing.Thegc(
)isf
oundi
nSys
tem andRunt
imecl
ass
es.publ
ics
tat
ic
voi
dgc(
){}
.
Not
e:Nei
therf
inal
izat
ionnorgar
bagecol
lect
ioni
sguar
ant
eed.
Example: Tes
tGar
bage1(
);
publi
cclassTestGarbage1
{
TestGarbage1 s
2=new
publicvoidfinal
ize()
Tes
tGarbage1();
{
s1=null
;
Syst
em. out.pri
ntl
n("obje
s2=null
;
ctisgarbagecollected")
;
System.gc()
;
}
}
publics t
at i
c void main(Stri
ng
}
args
[])
Output:
{
objecti
sgarbagecol
lected
TestGarbage1 s1=new
objecti
sgarbagecol
lected
t
hiskeywor
d:t
hisi
sar
efer
encevar
iabl
et hatref
erstothecurrentobj
ect
.The
f
oll
owi
ngar
etheus
agesoft
hiskeywor
d.
t
hiskeywor
dcanbeus
edt
oref
ercur
rentcl
assi
nst
ancevar
iabl
e.
t
his
()canbeus
edt
oinvokecur
rentcl
asscons
truct
or.
t
hiskeywor
dcanbeus
edt
oinvokecur
rentcl
assmet
hod(
impl
ici
tl
y)
t
hiscanbepas
sedasanar
gumenti
nthemet
hodcal
l.
t
hiscanbepas
sedasar
gumenti
nthecons
truct
orcal
l.
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page35
UNI
TII Pr
ogr
ammi
ngCons
truct
s
t
hiskeywor
dcanal
sobeus
edt
oret
urnt
hecur
rentcl
assi
nst
ance.
Exampl eforthiskeywor dcanbeus edtor
efercur rentclassins t
ancevariable.
cl
as sBox w i
dth *l
e ngth*he i
gh t
;
{ }
doublewi dt h,height,l
engt h; publ i
cs tatic voi
d mai n(
Stri
ng
Box() args[])
{ {
widt h=l ength=hei ght=-1; Boxb=newBox( );
} doubl evol=b.volume();
Box(doubl e wi dth, doubl e
height,doublel engt h) System. out.
println(“Vol
umeofBoxi s
{ “+vol);
thi
s .wi dth=wi dth; Box b1=new
this.hei ght=height; Bo x(
1 2,
1 2,
12);
this.lengt h=lengt h; b1.volume( )
;
}
doublevol ume( ) System. out.
println(“Vol
umeofBoxi s
{ “+vol);
retur n }
} VolumeofBoxi s-1
Out put: VolumeofBoxi s1728
Exampl eforthis( )canbeus edt oinvokecurrentclas scons t
ructor .
cl
as sThisDemo
{
i
ntnum1, num2;
ThisDemo( intnum1, intnum2)
{
thi
s .num1=num1;
this.num2=num2;
}
ThisDemo( intnum1)
{
thi
s (num1, num1) ;
}
ThisDemo( )
{
thi
s (0) ;
}
publicstat icvoidmai n(Stringargs[
])
{
This Demot d=newThi sDemo();
}
}
Explanation:this ()isus edf orcal l
ingthecurrentcl asscons tructor.t
his(0)call
sthe
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page36
UNI
TII Pr
ogr
ammi
ngCons
truct
s
cons
truct
orwhi
ch i
s havi
ng a s
ingl
e par
amet
ercons
truct
oroft
ype i
nteger
.
t
his
(num1,
num1)cal
lst
hecons
truct
orwhi
chi
shavi
ngt
wopar
amet
ersoft
ype
i
nteger
.
St
ati
cKeywor
d:I
fwewantt
odef
ineacl
assmemberwher
ethatwi
llbeus
ed
i
ndependent
lyofanyobj
ectoft
hatcl
ass
.Nor
mal
ly,acl
assmembermus
tbe
acces
sedonl
yinconj
unct
ionwi
thanobj
ectofi
tscl
ass
.But
,iti
spos
sibl
etocr
eat
ea
membert
hatcanbeus
edbyi
tsel
f,wi
thoutr
efer
encet
oas
peci
fi
cins
tance.To
cr
eat
esuchamember
,pr
ecedei
tsdecl
arat
ionwi
tht
hekeywor
dst
ati
c.
Whenamemberi
sdecl
areds
tat
ic,i
tcanbeacces
sedbef
oreanyobj
ect
sofi
tscl
ass
ar
ecr
eat
ed,andwi
thoutr
efer
encet
oanyobj
ect
.Youcandecl
arebot
hmet
hods
andvar
iabl
est
obes
tat
ic.Themos
tcommonexampl
eofas
tat
icmemberi
smai
n()
.
mai
n()i
sdecl
aredass
tat
icbecaus
eitmus
tbecal
ledbef
oreanyobj
ect
sexi
st.
Themember
sthatar
edecl
aredass
tat
icar
ecal
leds
tat
icmember
s.Si
ncet
hes
e
member
sar
eas
soci
atedwi
tht
hecl
assi
tsel
frat
hert
hani
ndi
vidualobj
ect
s,t
he
s
tat
ic var
iabl
esand s
tat
ic met
hodsar
eref
err
ed ascl
assvar
iabl
esand cl
ass
met
hods i
n or
dert
o di
sti
ngui
sht
hem f
rom i
nst
ance var
iabl
es and i
nst
ance
met
hods
.
St
ati
cvar
iabl
esar
eus
edwhenwewantt
ohaveavar
iabl
ecommont
oal
lins
tances
ofacl
ass
.Javacr
eat
esonl
yonecopyf
oras
tat
icvar
iabl
ewhi
chcanbeus
edeveni
f
t
hecl
assi
nnoti
nst
ant
iat
ed.
Met
hodsdecl
aredass
tat
ichaves
ever
alr
est
rict
ions
:
Theycanonl
ydi
rect
lycal
lot
hers
tat
icmet
hods
.
Theycanonl
ydi
rect
lyacces
sst
ati
cdat
a.
Theycannotr
efert
othi
sors
uperi
nanyway.
Wecandecl
ares
tat
icbl
ockt
hatget
sexecut
edexact
lyonce,whent
hecl
assi
sfi
rst
l
oaded.s
tat
icvar
iabl
esand s
tat
icmet
hodscan beus
ed i
ndependent
lyofany
obj
ect
.Fort
his
,weneedt
ospeci
fyt
henameoft
hei
rcl
assf
oll
owedbyt
hedot
oper
ator
.
Synt
ax:Clas
s Name.
stat
icVar
iabl
e;
ClassName.s
tati
cMethod()
;
Ex
Jaa
vmp
aPr
ole
g:
r //
ng De
ammi mons
trat
e s
ta
Dt
ei
c
p v
tofCSEa
,r
Vi
a
Vb
Tl
I es
,met
hods
,andbl
ocks
.Page37
UNI
TII Pr
ogr
ammi
ngCons
truct
s
cl
as sUseStati
c b=a*4;
{ }
s
taticinta=3; }
s
taticintb; cl
assStaticDemo
s
taticvoidmeth(i
ntx) {
{ publ i
cs t
atic void main(
Str
ing
System.out.pr
int
ln(
"x="+x); ar
gs[])
System.out.pr
int
ln(
"a="+a); {
System.out.pr
int
ln(
"b="+b); UseStati
c.meth(
42);
} }
stati
c }
{ Output:
System.out.pr
int
ln(
"Stat
ic bl
ock St
aticblockini
tial
ized.
x=42
i
nit
ial
ized.
");
a=3
b=12
Ar
rays
:Anar
rayi
sagr
oupofvar
iabl
est
hatar
eref
err
edt
obyacommonname.
Ar
raysofanyt
ypecanbecr
eat
edandmayhaveoneormor
edi
mens
ions
.As
peci
fi
c
el
ementi
nanar
rayi
sacces
sedbyi
tsi
ndex.
One-
Dimens
ionalAr
rays
:Aone-
dimens
ionalar
rayi
sal
istofvar
iabl
es.
Tocr
eat
eanar
ray,
fir
styoumus
tcr
eat
eanar
rayvar
iabl
eoft
hedes
iredt
ype.
Synt
ax:
type[
]var
-name;
o t
ypedecl
arest
hebas
etypeoft
hear
ray.
o Thebas
etypedet
ermi
nest
hedat
atypeofeachel
ementt
hatcompr
isest
he
`ar
ray.Thus
,thebas
etypef
ort
hear
raydet
ermi
neswhatt
ypeofdat
athe
ar
raywi
llhol
d.
newi
sas
peci
aloper
atorf
oral
locat
ingmemor
y.
Synt
axvar
-name=newt
ype[
siz
e];
o t
ypes
peci
fi
est
het
ypeofdat
abei
ngal
locat
ed.
o s
izes
peci
fi
est
henumberofel
ement
sint
hear
raywhi
chmus
tbeanumer
ic
cons
tant
.
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page38
UNI
TII Pr
ogr
ammi
ngCons
truct
s
o var
-namei
sthear
rayvar
iabl
ethati
sli
nkedt
othear
ray.
Theel
ement
sint
hear
rayal
locat
edbynewwi
llaut
omat
ical
lybei
nit
ial
izedt
ozer
o.
g.
E. :
int
[]number
s=newi
nt[
3];
Anar
rayi
sat
wo-
steppr
oces
s:
o Youmus
tdecl
areavar
iabl
eoft
hedes
iredar
rayt
ype.
o Youmus
tal
locat
ethememor
ythatwi
llhol
dthear
ray,us
ingnew,andas
sign
i
ttot
hear
rayvar
iabl
e.
Thus
,inJavaal
lar
raysar
edynami
cal
lyal
locat
ed.
Onceyouhaveal
locat
edanar
ray,
youcanacces
sas
peci
fi
cel
ementi
nthear
raybys
peci
fyi
ngi
tsi
ndexwi
thi
nsquar
e
br
acket
s.Al
lar
rayi
ndexess
tar
tatz
ero.
//Demons trateaone-dimensionalar r
ay.
classArray
{
publi
cs tat
icvoi
dmai n(
Str i
ngar gs
[])
{
i
ntnumber s[
];
numbers=newi nt[3];
numbers[0]=4;
numbers[1]=3;
numbers[2]=6;
Syst
em.out.
print
ln("ILikeNumber"+number
s[0]
);
}
}
Out put:
ILikeNumber4
Anar
rayi
nit
ial
izeri
sal
istofcomma-
separ
atedexpr
ess
ionss
urr
oundedbycur
ly
br
aces
.Thecommass
epar
atet
heval
uesoft
hear
rayel
ement
s.Thear
raywi
ll
aut
omat
ical
lybecr
eat
edl
argeenought
ohol
dthenumberofel
ement
syou
s
peci
fyi
nthear
rayi
nit
ial
izer
.Ther
eisnoneedt
ous
enew.
//Ani mprovedversionofthepr
evi
ouspr
ogram.
classAutoArray
{
publicst
aticvoidmai n(
Str
ingar
gs[
])
{
int[
]number s={4,
3,6};
System.out.pri
ntl
n("ILi
keNumber"+numbers[
0])
;
}
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page39
UNI
TII Pr
ogr
ammi
ngCons
truct
s
}
Output
:
ILi
keNumber4
Al
ter
nat
iveAr
rayDecl
arat
ionSynt
ax:Ther
eisas
econdf
ormt
hatmaybeus
edt
o
decl
areanar
ray:Synt
ax:
typevar
-name[
];
Her
e,t
hes
quar
ebr
acket
sfol
lowt
hear
rayvar
iabl
ename,
andnott
het
ypes
peci
fi
er.
E.
g.:t
hef
oll
owi
ngt
wodecl
arat
ionsar
eequi
val
ent
:
i
nt[
]a2=newi
nt[
3];
i
ntal
[]=newi
nt[
3];
Thef
oll
owi
ngdecl
arat
ionsar
eal
soequi
val
ent
:
char
[][
]twod2=newchar
[3]
[4]
;
chart
wod1[
][]=newchar
[3]
[4]
;
Thi
sfi
rstdecl
arat
ionf
orm of
fer
sconveni
encewhendecl
ari
ngs
ever
alar
raysatt
he
s
amet
ime.
E.
g.i
nt[
]nums
,nums
2,nums
3;/
/cr
eat
ethr
eear
rays
Theaboves
tat
ementcr
eat
est
hreear
rayvar
iabl
esoft
ypei
nt.I
tist
hewr
iti
ngs
ame
ast
hef
oll
owi i
ng:ntnums
[],nums
2[]
,nums
3[]
;//cr
eat
ethr
eear
rays
Thef
irs
tdecl
arat
ionf
ormi
sal
sous
efulwhens
peci
fyi
nganar
rayasar
etur
ntypef
or
amet
hod.
Mul
ti
dimens
ionalAr
rays
:InJava,mul
ti
dimens
ionalar
raysar
eact
ual
lyar
raysof
ar
rays
.Todecl
areamul
ti
dimens
ionalar
rayvar
iabl
e,s
peci
fyeachaddi
ti
onali
ndex
us
inganot
hers
etofs
quar
ebr
acket
s.
g.
E. :
int
[][
]TD=newi
nt[
3][
3];
Thi
sal
locat
esa 3 by 3 ar
ray and as
signsi
tto TD.I
nter
nal
lyt
hismat
rixi
s
i
mpl
ement
edasanar
rayofar
raysofi
nt.
Thef
oll
owi
ngpr
ogr
am number
seachel
ementi
nthear
ray,r
ow byr
ow,andt
hen
di
spl
ayst
hes
eval
ues
:
// Demons tr
atea t wo-di
mensional {
array. i
nti,j,
k=0;
cl
as sTwoDArray i
ntTD[][]=newint
[3][
3];
{ f
or(
i=0;i<3;i
++)
publ
ics t
ati
c voi
d main(
Stri
ng {
args[]
) for(j
=0;j
<3;j
++)
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page40
UNI
TII Pr
ogr
ammi
ngCons
truct
s
{ }
k=TD[i
][j
]; Sys
tem.out
.pr
int
ln(
);
k++; }
} }
} }
for
(i=0;i
<3;i
++) Output
:
{ 012
for
(j=0;j
<3;j
++) 345
{ 678
System.out.
pri
nt(TD[
i][
j]+"");
f oreachloop:JDK1. 5int
roducedanew f
orl
oopknownasf
oreachl
oopor
enhancedf
orl
oop,whi
chenabl
esyout
otr
aver
set
hecompl
etear
rays
equent
ial
ly
wi
thoutus
ingani
ndexvar
iabl
e.
publi
cclassTes tArray
{
publ i
cs t
aticvoidmai n(Str
ingar gs[]
)
{
doubl e[]myLi s
t={1,2,3,
4} ;
for(doubleel e:
myList)
{
Sys t
em. out.
print(
ele);
}
} }
Output:E:\
>javacTes t
Ar r
ay.j
ava
E:
\>javaTes tArr
ay
1.
02.03. 04.0
CommandLi neAr guments:St r
ing[]argswi
thi
nthedecl
arat
ionoft
hemai
n
met
hodr
epr
esent
saSt
ringar
raynamedar
gswher
ear
gsi
snot
hingmor
ethanan
i
dent
if
ier
,wecanr
epl
acei
twi
thanyot
heri
dent
if
ierandt
hepr
ogr
am wi
lls
til
lwor
k.
ASt
ringar
raycanbepas
sedasanar
gumentwhenweexecut
ethepr
ogr
am.We
pas
sitt
hrought
hecommandl
inei
tsel
f.Cons
idert
hatwehaveacl
assnamedAdd.
Thef
oll
owi
ngs
tat
ementnor
mal
lyus
edt
oexecut
ethepr
ogr
am.
E:
\>j
avacAdd.
java
E:
\>j
avaAdd
Whenwewi
sht
opas
stheSt
ringar
ray,wes
impl
yincl
udet
heel
ement
soft
hear
ray
ass
impl
eSt
ringsbes
idet
hecl
assname.Encl
osi
ngt
heSt
ringsi
nquot
esi
sopt
ional
.
Cons
ecut
iveSt
ringsar
esepar
atedwi
thas
pace.Forexampl
e,i
fwewi
sht
opas
sa
t
hreeel
ementSt
ringar
raycont
aini
ngt
heval
ues"1","2",and "3"anyoft
he
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page41
UNI
TII Pr
ogr
ammi
ngCons
truct
s
f
oll
owi
ngl
inesi
sent
eredont
hecommandpr
ompt
.
E:
\>j
avaAdd123
E:
\>j
avaAdd"1""2""3"
Si
ncet
hes
ear
gument
sar
epas
sedt
hrought
hecommandl
ine,t
heyar
eknownas
commandl
inear
gument
s.TheSt
ringar
gument
spas
sedar
est
oredi
nthear
ray
s
peci
fi
edi
nthemai
n()decl
arat
ion.ar
gs[
]isnowat
hreeel
ementSt
ringar
ray.
Thes
e
el
ement
sar
eacces
sedi
nthes
amewayast
heel
ement
sofanor
malar
ray.The
f
oll
owi
ngi
sthecompl
eteAddpr
ogr
am whi
chi
scapabl
eofaddi
nganynumberof
i
nteger
spas
sedascommandl
inear
gument
s.
publi
cclas
sAdd
{
publi
cs t
ati
cvoidmain(
St r
ing[]args)
{
intsum =0;
for(i
nti=0;i<ar
gs .
length;i++)
{
s
um =sum +Integer.pars
eInt(
args[
i])
;
}
System.out
.pr
int
ln("Thes um oftheargumentspas
sedi
s"+s
um)
;
}
}
Output:
E:
\>javaAdd123
Thesum oftheargumentspassedis6
JavaPr
ogr
ammi
ng DeptofCSE,
VVI
T Page42