Orp Intjava

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

I

OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

Chapt
erOne:I
ntr
oduct
iont
oObj
ectOr
ient
edPr
ogr
ammi
ng

1. Pr
ogr
ammi
ngPar
adi
gms
Pr
ogr
ammi
ngi
sacr
eat
ivepr
ocesscar
ri
edoutbypr
ogr
ammer
stoi
nst
ructacomput
eronhowt
o
doat
ask.Apr
ogr
am i
sasetofi
nst
ruct
ionst
hatt
ell
sacomput
erwhatt
odoi
nor
dert
ocomeup
wi
thasol
uti
ont
oapar
ti
cul
arpr
obl
em.Ther
ear
eanumberofal
ter
nat
iveappr
oachest
othe
pr
ogr
ammi
ngpr
ocess,
ref
err
edt
oaspr
ogr
ammi
ngpar
adi
gms.

Pr
ogr
ammi
ng par
adi
gms ar
e model
s empl
oyed f
ordev
elopi
ng comput
ati
onalsol
uti
ons t
o
pr
obl
ems.Thesepar
adi
gmsest
abl
i
sht
her
ulesandl
ogi
ctodev
eloppr
ogr
ams.I
nthi
sway
,
pr
ogr
ammi
ngl
anguagesi
mpl
ementt
heser
ulesandl
ogi
c,pr
ovi
dingt
hem f
orpr
ogr
ammer
s.
Di
ff
erentpar
adi
gms r
epr
esentf
undament
all
ydi
ff
erentappr
oaches t
o bui
l
ding sol
uti
ons t
o
speci
fi
cty
pesofpr
obl
emsusi
ngpr
ogr
ammi
ng.Cur
rent
ly,t
her
eexi
stt
womaj
orpr
ogr
ammi
ng
par
adi
gms:i
mper
ati
veanddecl
arat
ive.Thesepar
adi
gms,
int
urn,
subdi
vi
dei
ntoot
herpar
adi
gms
wi
thev
enmor
epar
ti
cul
archar
act
eri
sti
cs.

1.
1.I
mper
ati
vePr
ogr
ammi
ngpar
adi
gms
Thei
mper
ati
vepar
adi
gm i
stheol
destcomput
erpr
ogr
ammi
ngpar
adi
gm.Thi
spar
adi
gm pr
esent
s
asacent
ralchar
act
eri
sti
cthedef
ini
ti
onofsequencesofi
nst
ruct
ionsr
epr
esent
ingmodi
fi
cat
ions
i
nthest
atesofacomput
ersy
stem.

Theyar
esai
dto becommanddr
iven.Thi
spar
adi
gm di
rect
sthewr
it
tencodeexecut
ionas
sequenceofst
atement
sexecut
edonebyone.Thei
mper
ati
vest
ylepr
ogr
am consi
stsofsetof
pr
ogr
am st
atement
s.Eachst
atementdi
rect
sthecomput
ert
oper
for
m speci
fi
ctask.I
nthi
sst
yle
t
hepr
ogr
ammerhast
oel
abor
ateeachst
atement
sindet
ail
s.Eachst
atementdi
rect
swhati
stobe
doneandhowi
tist
obedone.

1
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

Fi
gur
e1I
mper
ati
vepr
ogr
ammi
ngl
anguage

1.
1.1.
Str
uct
uredPr
ogr
ammi
ng
Thest
ruct
uredpr
ogr
ammi
ngi
ntendst
oopt
imi
zet
hecodebyusi
ngt
hepr
ogr
am cont
rol
flow
const
ruct
s,deci
si
onmaki
ng(
IF,
IFTHEN,
ELSE)const
ruct
sandt
hei
ter
ati
onconst
ruct
s(f
or,
whi
l
e
l
oops)
,bl
ocksandf
unct
ions.Themai
nint
entoft
hest
ruct
uredpr
ogr
ammi
ngi
stoi
mpr
ovet
he
r
eadabi
l
ityoft
hecode.Thi
sfaci
l
itat
est
her
e-usabi
l
ityoft
hecodebydi
vi
dingt
hecodei
ntosemi
-
i
ndependentmodul
es.I
tisal
socal
l
edModul
arPr
ogr
ammi
ng.

Fi
gur
e2st
ruct
uredpr
ogr
ammi
ngl
anguage

Thest
ruct
uredpr
ogr
ammi
ngdoesnotadv
ocat
etheuseofuncondi
ti
onal
cont
rol
stat
ement
ssuch
asgot
oconst
ruct
s.Theuseofgot
oconst
ruct
scanr
esul
tint
ospaghet
ticodet
hati
sdi
ff
icul
tto

2
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

debug.

 Exampl
esofLanguagest
hatsuppor
tthest
ruct
ural
progr
ammi
ngpar
adi
gm:
-C++.

St
ruct
uredpr
ogr
ammi
ngi
saki
ndofi
mper
ati
vepr
ogr
ammi
ngwher
econt
rol
flowi
sdef
inedby
nest
edl
oops,
condi
ti
onal
s,andsubr
out
ines,
rat
hert
hanv
iagot
o.Var
iabl
esar
egener
all
ylocal
to
bl
ocks(
hav
elexi
cal
scope)
.

1.
1.2.
Procedur
alPr
ogr
ammi
ng
The pr
ocedur
alpr
ogr
ammi
ng par
adi
gm f
ocuses on subdi
vi
ding a pr
ogr
am f
rom a si
mpl
e
sequenceofi
nst
ruct
ionst
oacol
lect
ionofsubr
out
ineswi
thpar
ti
cul
ari
nst
ruct
ions,st
ruct
ures,
andv
ari
abl
es.Apr
ocedur
e/subr
out
inecont
ainsaser
iesofcomput
ati
onal
stepst
obecar
ri
edout
.
Pr
ocedur
alpr
ogr
ammi
ngi
sal
sor
efer
redt
oasi
mper
ati
vepr
ogr
ammi
ng.Pr
ocedur
alpr
ogr
ammi
ng
l
anguagesar
eal
soknownast
op-
downl
anguages.Pr
iort
opr
ocedur
alpr
ogr
ammi
ng,
ther
epet
it
ion
ofaspeci
fi
cpor
ti
onofcoder
eli nggot
edonusi ost
atement
s.Howev
er,i
tmadepr
ogr
am codes
v
erycompl
ext
ofol
l
owandhar
dtomai
ntai
nandupdat
e.

A pr
ocedur
e/subr
out
ine ofa pr
ogr
am i
stai
l
ored t
o accompl
i
sh a si
ngl
e wel
l
-def
ined t
ask.
Howev
er,
impl
ement
ingsubr
out
inesdemandednewi
nst
ruct
ionsf
ordev
elopi
ngpr
ogr
ams:

 Decl
arat
ion:t
hedecl
arat
ionofasubr
out
inet
ypi
cal
l
ydef
inesi
tsnameandt
her
equi
red
par
amet
ers.I
nmostl
anguages,t
hesubr
out
inedef
ini
ti
on(
thecode)i
spr
esent
edj
ustaf
ter
t
hedecl
arat
ion

 Cal
l:i
nst
ruct
iont
hatt
ri
gger
stheexecut
ionofanal
readydecl
aredsubr
out
ine.Thus,t
he
dat
a cor
respondi
ng t
o each par
amet
erofa subr
out
ine i
s def
ined wi
thi
nthe cal
l
ing
i
nst
ruct
ion

 Ret
urn:t
he r
etur
ninst
ruct
ion i
ndi
cat
es t
he r
esul
tofa subr
out
ine.Howev
er,some
subr
out
inesdonotpr
esentr
etur
nabl
eresul
tsand,consequent
ly,donotexecut
ether
etur
n
i
nst
ruct
ion

Exampl
esofpr
ocedur
all
anguagesi
ncl
udeFORTRAN,COBOLandC,whi
chhav
ebeenar
ound
si
ncet
he1960sand70s.

3
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

Fi
gur
e3Gener
aldepi
cti
onofpr
ocedur
alpr
ogr
ammi
ngl
anguage

Fi
gur
e4Exampl
eofpr
ocedur
alpr
ogr
ammi
ngl
anguage

1.
1.3.
Obj
ectOr
ient
edPr
ogr
ammi
ng(
OOP)
OOPi
sanappr
oacht
opr
obl
em-
sol
vi
ngwher
eal
lcomput
ati
onsar
ecar
ri
edoutusi
ngobj
ect
s.
Anobj
ecti
sacomponentofapr
ogr
am t
hatknowshowt
oper
for
m cer
tai
nact
ionsandhowt
o
i
nter
actwi
thot
herel
ement
soft
hepr
ogr
am.Amet
hodi
nobj
ect
-or
ient
edpr
ogr
ammi
ngi
sli
kea
pr
ocedur
einpr
ocedur
alpr
ogr
ammi
ng.Thekeydi
ff
erenceher
eist
hatt
hemet
hodi
spar
tofan
obj
ect
.Inobj
ect
-or
ient
edpr
ogr
ammi
ng,
youor
gani
zey
ourcodebycr
eat
ingobj
ect
s,andt
heny
ou
cangi
vet
hoseobj
ect
spr
oper
ti
esandy
oucanmaket
hem docer
tai
nthi
ngs.Akeyaspectof
obj
ect
-or
ient
edpr
ogr
ammi
ngi
stheuseofcl
asses.Acl
assi
sabl
uepr
intofanobj
ect
.Youcan
t
hinkofacl
assasaconcept
,andt
heobj
ectast
heembodi
mentoft
hatconcept
.Exampl
eof
4
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

OOPl
anguageJav
a,C#,
C++,
Visual
Basi
cet
c…

Fi
gur
e5Gener
aldepi
cti
onofOOP

Fi
gur
e6Exampl
eofOOP

1.
2.Decl
arat
ivePr
ogr
ammi
ngpar
adi
gms
Thedecl
arat
ivepar
adi
gm hasast
hemai
nfeat
uret
hedef
ini
ti
onoft
askst
hatcomput
ersy
stems
mustaccompl
i
sh.Di
ff
erentf
rom t
hei
mper
ati
vepar
adi
gm,
thedecl
arat
ivepar
adi
gm doesn’
tmake
cl
earhowt
opr
ocessat
ask.Ont
hecont
rar
y,pr
ogr
amsf
oll
owi
ngt
hedecl
arat
ivepar
adi
gm wor
k

5
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

as“
gui
des”wi
thi
nst
ruct
ionsdef
ini
ngwhatt
asksacomput
ersy
stem shoul
daccompl
i
sh,
r
egar
dlessofhowt
heset
asksar
eaccompl
i
shed.

Duet
othi
schar
act
eri
sti
cofdescr
ibi
ngwhatt
odoi
nst
eadofhowt
odosomet
hing,
progr
am
codesi
nthedecl
arat
ivepar
adi
gm nat
ural
l
yposeahi
gherabst
ract
ionl
evel
.Iti
saconsequenceof
usi
ngpr
edet
ermi
nedcommandst
ruct
urest
odef
inet
asks.Thi
shi
gherabst
ract
ionl
evel
also
i
mpr
ovest
hemai
ntai
nabi
l
ityofapr
ogr
am duet
othest
andar
dizedoper
ati
onoft
hesecommand
st
ruct
ures.Thus,
iti
seasi
erf
ordi
ff
erentt
eamst
owor
kondi
sti
nctst
agesofasof
twar
eli
fecy
cle,
suchasdev
elopmentandmai
ntenance.

1.
2.1. Funct
ional
Progr
ammi
ng
Thef
unct
ional
par
adi
gm consi
der
sthatpr
ogr
amsar
ecomposi
ti
onsofmul
ti
plef
unct
ions.I
nsuch
ascenar
io,
wecanempl
oyf
unct
ionsasanydat
aty
pe.Thus,
funct
ionscanhav
eident
if
ier
sand
wor
kasar
gument
sorr
esul
tsofot
herf
unct
ions.Fur
ther
mor
e,t
her
ear
edi
ff
erentcat
egor
iesof
f
unct
ions,
eachoneconsi
der
ingpar
ti
cul
archar
act
eri
sti
cs:

 Fi
rst
-cl
assf
unct
ions:
element
aryf
unct
ionsf
ort
hef
unct
ional
par
adi
gm.Theycanbe
assi
gnedt
ovar
iabl
es,
passedasar
gument
stoot
herf
unct
ions,
andr
etur
nedasot
her
f
unct
ionsr
esul
t

 Pur
efunct
ions:
thesef
unct
ionsf
oll
owt
hepr
oper
ti
esoft
ranspar
encyandl
ackofsi
de
ef
fect
s.Tr
anspar
encysi
gni
fi
est
hataf
unct
ional
way
sret
urnst
hesamer
esul
tgi
vent
he
samei
nput
.Lackofsi
deef
fect
smeanst
hataf
unct
iondoesn’
tcauseanyst
atemut
ati
oni
n
t
hepr
ogr
am,
forexampl
e,pr
int
ingsomei
nfor
mat
ionorsendi
ngdat
athr
ought
henet
wor
k

 Hi
gh-
orderf
unct
ions:
thesef
unct
ionsr
ecei
veot
herf
unct
ionsasar
gument
sorr
etur
na
f
unct
ionasar
esul
t(orev
enbot
h).Anexampl
ei hemapf
st unct
ion,
whi
chexecut
esa
pr
ovi
dedf
unct
iont
oeachel
ementofagi
veni
ter
abl
e,t
husr
etur
ninganewi
ter
abl
e

6
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

1.
2.2. Logi
cPr
ogr
ammi
ng
Thel
ogi
cpr
ogr
ammi
ngpar
adi
gm usesf
ormal
logi
ctosol
veamy
riadofpr
obl
ems.Thi
spar
adi
gm
r
eli
esonaknowl
edgebasewi
thsev
eral
fact
sandr
ulest
oanswerquer
ies:

 Fact
s:f
act
srepr
esentspeci
fi
crel
ati
onsamongobj
ect
s.Concr
etel
y,f
act
sar
easser
ti
ons
aboutobj
ect
s

 Rul
es:
theyar
epr
edi
cat
est
hatdescr
ibeal
ogi
cal
rel
ati
onamongf
act
s.I
npr
act
ice,
rul
es
hav
eheadandbody
,wher
egener
all
yheadi
sanasser
ti
on,
andt
hebodyi
sacondi
ti
on

 Quer
ies:
aquer
yconsi
stsofoneormor
elogi
cexpr
essi
onsi
nter
leav
edwi
thl
ogi
coper
ator
s.
Fur
ther
mor
e,t
ohav
eapr
operanswer
,weshoul
dcr
eat
equer
iesconsi
der
ingt
hef
act
sand
r
ulesi
ntot
hepr
ogr
ams’
knowl
edgebase

Wi
tht
hedescr
ibedr
esour
ces,
progr
amsuseani
nfer
encesy
stem t
oanswerquer
ies.So,
the
i
nfer
encesy
stem sear
chesf
orpr
oof
sforeachquer
y.Fi
nal
l
y,t
hepr
ogr
am r
etur
nst
hededuct
ibl
e
sol
uti
onst
oaquer
y.Ot
her
wise,
ift
her
ear
enosol
uti
ons,
thepr
ogr
am r
etur
nsaf
alsev
alue.

2. Obj
ectOr
ient
edPr
ogr
ammi
ngv
s.Pr
ocedur
alPr
ogr
ammi
ng

2.
1. Pr
ocedur
alPr
ogr
ammi
ngPar
adi
gm
 Emphasi
sondoi
ngt
hings(
algor
it
hm)
.
 Modul
esorf
unct
ionsar
ethephy
sical
bui
l
dingbl
ocks.
 Dat
amov
esopenl
yar
oundt
hesy
stem f
rom f
unct
iont
ofunct
ion.
 Mostoft
hef
unct
ionshar
egl
obal
dat
a.

2.
2.Obj
ectOr
ient
edPr
ogr
ammi
ngpar
adi
gm
 Emphasi
sisondat
arat
hert
hanpr
ocedur
e.
7
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

 Dat
aishi
ddenandcannotbeaccessedbyext
ernal
funct
ion.
 Thepr
obl
em i
sdi
vi
dedi
ntoobj
ect
s.

3. Adv
ant
ageofOOPsov
erPr
ocedur
e-or
ient
edpr
ogr
ammi
ngl
anguage
1)OOPs make dev
elopmentand mai
ntenance easi
erwher
e as i
n Pr
ocedur
e-or
ient
ed
pr
ogr
ammi
ngl
anguagei
tisnoteasyt
omanagei
fcodegr
owsaspr
ojectsi
zegr
ows.
2)OOPspr
ovi
dedat
ahi
dingwher
easi
nPr
ocedur
e-or
ient
edpr
ogr
ammi
ngl
anguageagl
obal
dat
acanbeaccessedf
rom any
wher
e.
3)OOPspr
ovi
desabi
l
ityt
osi
mul
ater
eal
-wor
ldev
entmuchmor
eef
fect
ivel
y
4)OOPmakesi
teasyt
oaddnewf
eat
ures

4. Concept
sofOOP
Obj
ect
s:Obj
ect
sar
ethebasi
crun-
ti
meent
it
iesi
n an obj
ect
-or
ient
ed sy
stem.Pr
ogr
ammi
ng
pr
obl
em i
sanal
yzedi
nter
msofobj
ect
sandnat
ureofcommuni
cat
ionbet
weent
hem.Whena
pr
ogr
am i
sexecut
ed,
obj
ect
sint
eractwi
theachot
herbysendi
ngmessages.Di
ff
erentobj
ect
scan
al
soi
nter
actwi
theachot
herwi
thoutknowi
ngt
hedet
ail
soft
hei
rdat
aorcode.
asses:Acl
Cl assi
sacol
l
ect
ionofobj
ect
sofsi
mil
art
ype.Onceacl
assi
sdef
ined,anynumberof
obj
ect
scanbecr
eat
edwhi
chbel
ongt
othatcl
ass.
Dat
a Abst
ract
ion:Abst
ract
ion r
efer
stot
he actofr
epr
esent
ing essent
ialf
eat
ures wi
thout
i
ncl
udi
ngt
hebackgr
ounddet
ail
sorexpl
anat
ions.Cl
assesuset
heconceptofabst
ract
ionandar
e
def
inedasal
i
stofabst
ractat
tri
but
es.
Encapsul
ati
on:St
ori
ngdat
aandf
unct
ionsi
nasi
ngl
euni
t(cl
ass)i
sencapsul
ati
on.Dat
acannot
beaccessi
blet
otheout
sidewor
ldandonl
ythosef
unct
ionswhi
char
est
oredi
nthecl
asscan
accessi
t.
I
nher
it
ance:I
nher
it
ancei
sthepr
ocessbywhi
chobj
ect
scanacqui
ret
hepr
oper
ti
esofobj
ect
sof
ot
hercl
ass.I
nOOP,
inher
it
ancepr
ovi
desr
eusabi
l
ity
,li
ke,
addi
ngaddi
ti
onalf
eat
urest
oanexi
sti
ng
cl
asswi
thoutmodi
fyi
ngi
t.Thi
sisachi
evedbyder
ivi
nganewcl
assf
rom t
heexi
sti
ngone.Thenew
cl
asswi
l
lhav
ecombi
nedf
eat
uresofbot
hthecl
asses.
Pol
ymor
phi
sm:Pol
ymor
phi
sm meanst
heabi
l
ityt
otakemor
ethanonef
orm.Anoper
ati
onmay
exhi
bitdi
ff
erentbehav
ior
sindi
ff
erenti
nst
ances.Thebehav
iordependsont
hedat
aty
pesusedi
n
t
heoper
ati
on.Pol
ymor
phi
sm i
sext
ensi
vel
yusedi
nimpl
ement
ingI
nher
it
ance.

8
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

Exampl
e

Benef
it
sofobj
ect
-or
ient
edpr
ogr
ammi
ngappr
oach:

 Bet
terabst
ract
ion

 Bet
termai
ntai
nabi
l
ity

 Bet
terr
eusabi
l
ity

Jav
aLanguageSpeci
fi
cat
ionandBasi
cTer
msofOOPi
nJav
a

Comput
erl
anguageshav
est
ri
ctr
ulesofusage.I
fyoudonotf
oll
owt
her
uleswhenwr
it
inga
pr
ogr
am,
thecomput
erwi
l
lbeunabl
etounder
standi
t.TheJav
alanguagespeci
fi
cat
ionandJav
a
APIdef
inet
heJav
ast
andar
d.TheJav
alanguagespeci
fi
cat
ioni
sat
echni
cal
def
ini
ti
onoft
he
l
anguaget
hati
ncl
udest
hesy
ntaxandsemant
icsoft
heJav
apr
ogr
ammi
ngl
anguage.TheJav
a
l
anguagespeci
fi
cat
ioni
sst
abl
e,butt
heAPIi
sst
il
lexpandi
ng.

 Cl
ass–i
tisuni
tofpr
ogr
am t
hathousesasetofmet
hodsandat
tr
ibut
es.Exampl
e:acl
ass
t
hatr
epr
esent
sabankaccountmi
ghtcont
ainonemet
hodt
odeposi
tmoneyt
oanaccount
,
anot
hert
owi
thdr
awmoneyf
rom anaccountandat
hir
dtoi
nqui
rewhatt
heaccount
’s
cur
rentbal
ancei
s.

9
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

Her
eyouhav
eaCl
assnamedas:
Account

At
tri
but
esar
e:account
_number
,account
_bal
ance

Met
hod/
Act
ioni
s:showdat
a()

 Obj
ect–i
tisani
nst
anceofi
tscl
ass.Real
-wor
ldobj
ect
sshar
etwochar
act
eri
sti
cs−t
hey
al
lhav
est
ateandbehav
ior
.Letusseet
hef
oll
owi
ngpi
ctor
ial
exampl
etounder
stand
Obj
ect
s.

I
ntheabov
edi
agr
am,
theobj
ect‘
Dog’
hasbot
hst
ateandbehav
ior
.Anobj
ectst
oresi
ts
i
nfor
mat
ioni
nat
tri
but
esanddi
scl
osesi
tsbehav
iort
hroughmet
hods.

 Met
hod–i
tisawayt
oper
for
m at
aski
napr
ogr
am.I
thousest
hepr
ogr
am st
atement
sthat
act
ual
l
yper
for
mit
stasks.
10
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

 Message–i
tissomet
hingwhi
chi
ssendwi
thi
nanobj
ectorcl
ass.Exampl
e:Wheny
ou
dr
iveacar
,pr
essi
ngi
tsgaspedal
sendsamessaget
othecart
oper
for
m at
ask,
thati
s,t
o
gof
ast
er.

 Met
hodCal
l–Eachmessagei
simpl
ement
edasamet
hodcal
lthatt
ell
samet
hodoft
he
obj
ectt
oper
for
mit
stask.

 I
nst
ant
iat
ion–i
tist
hepr
ocessofbui
l
danobj
ectofacl
assbef
oreapr
ogr
am canper
for
m
t
het
askst
hatt
hecl
ass’
smet
hodsdef
ine.

 Reuse–Reuseofexi
sti
ngcl
asseswhenbui
l
dingnewcl
assesandpr
ogr
amssav
est
ime
andef
for
t.Reuseal
sohel
psy
oubui
l
dmor
erel
i
abl
eandef
fect
ivesy
stems,
because
exi
sti
ngcl
assesandcomponent
sof
tenhav
egonet
hroughext
ensi
vet
est
ing,
debuggi
ng
andper
for
mancet
uni
ng.

 At
tri
but
e–i
sav
isi
bleoranext
ernal
speci
fi
cat
ionofanobj
ect
.Exampl
e:I
fyouconsi
der
car
,it
sat
tri
but
esar
eli
kecol
or,
numberofdoor
s,speed,
etc.

 I
nst
anceVar
iabl
e–i
tisanamet
hatspeci
fi
est
hecl
assesat
tr
ibut
es.Exampl
e:abank
accountobj
ecthasabal
anceat
tri
but
ethatr
epr
esent
stheamountofmoneyi
ntheaccount
.
Eachbankaccountobj
ectknowst
hebal
ancei
ntheaccounti
trepr
esent
s,butnott
he
bal
ancesoft
heot
heraccount
sint
hebank.

5. Feat
uresofJav
a
Jav
aisapower
fulobj
ect
-or
ient
edpr
ogr
ammi
ngl
anguagei
ntr
oducedbySunMi
crosy
stemsi
n
1995.
Ther
eismanyf
eat
uresofj
ava.Thesear
e:
 Si
mpl
e:Accor
dingt
oSun,Jav
alanguagei
ssi
mpl
ebecause: sy
ntaxi
sbasedonC++(
so
easi
erf
orpr
ogr
ammer
stol
ear
nitaf
terC++)
.Noneedt
oremov
eunr
efer
encedobj
ect
s
becauset
her
eisAut
omat
icGar
bageCol
l
ect
ioni
njav
a.
Jav
ahasr
emov
edmanycompl
i
cat
edandr
arel
y-
usedf
eat
ures,
forexampl
e,expl
i
cit
poi
nter
s,oper
atorov
erl
oadi
ng,
etc.

Ther
eisnoneedt
oremov
eunr
efer
encedobj
ect
sbecauset
her
eisanAut
omat
icGar
bage
Col
l
ect
ioni
nJav
a.

11
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

 Obj
ect
-or
ient
ed:Obj
ect
-or
ient
edmeansweor
gani
zeoursof
twar
easacombi
nat
ionof
di
ff
erentt
ypes ofobj
ect
sthati
ncor
por
ates bot
h dat
a and behav
ior
.Obj
ect
-or
ient
ed
pr
ogr
ammi
ng (
OOPs)i
s a met
hodol
ogy t
hatsi
mpl
i
fies sof
twar
e dev
elopmentand
mai
ntenancebypr
ovi
dingsomer
ules.
 Pl
atf
ormI
ndependent
:A pl
atf
ormi
sthehar
dwar
eorsof
twar
eenv
ironmenti
nwhi
cha
pr
ogr
am r
uns.Ther
ear
etwot
ypesofpl
atf
ormssof
twar
e-basedandhar
dwar
e-based.Jav
a
pr
ovi
dessof
twar
e-basedpl
atf
orm.TheJav
apl
atf
orm di
ff
ersf
rom mostot
herpl
atf
ormsi
n
t
hesenset
hati
t'
sasof
twar
e-basedpl
atf
ormt
hatr
unsont
opofot
herhar
dwar
e-based
pl
atf
orms.Jav
acodecanber
unonmul
ti
plepl
atf
ormse.
g.Wi
ndows,Li
nux
,SunSol
ari
s,
andMac/
OSet
c.Jav
acodei
scompi
l
edbyt
hecompi
l
erandconv
ert
edi
ntoby
tecode.Thi
s
by
tecodei
sapl
atf
ormi
ndependentcodebecausei
tcanber
unonmul
ti
plepl
atf
ormsi
.
e.
Wr
it
eOnceandRunAny
wher
e(WORA)
.
 Secur
ed:Javai
ssecur
edbecause:
 Noexpl
i
citpoi
nter
 Pr
ogr
amsr
uni
nsi
dev
irt
ual
machi
nesandbox
.

 Cl
assl
oader
-addssecur
it
ybysepar
ati
ngt
hepackagef
ort
hecl
assesoft
hel
ocalf
il
e
sy
stem f
rom t
hoset
hatar
eimpor
tedf
rom net
wor
ksour
ces.

 By
tecodeVer
if
ier
-checkst
hecodef
ragment
sfori
l
legalcodet
hatcanv
iol
ateaccess
r
ightt
oobj
ect
s.

 Secur
it
yManager
-det
ermi
neswhatr
esour
cesacl
asscanaccesssuchasr
eadi
ngand
wr
it
ingt
othel
ocal
disk

12
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

 Robust
:Jav
amakesanef
for
ttoel
i
minat
eer
ror
-pr
onesi
tuat
ionsbyemphasi
zi
ngmai
nlyon
compi
l
eti
meer
rorchecki
ngandr
unt
imechecki
ng.Robustsi
mpl
ymeansst
rong.
Jav
aisr
obustbecause:
o I
tusesst
rongmemor
ymanagement
.
o Ther
eisal
ackofpoi
nter
sthatav
oidssecur
it
ypr
obl
ems.
o Ther
eisaut
omat
icgar
bagecol
l
ect
ioni
njav
awhi
chr
unsont
heJav
aVi
rt
ual
Machi
ne
t
ogetr
idofobj
ect
swhi
char
enotbei
ngusedbyaJav
aappl
i
cat
ionany
mor
e.
o Ther
ear
eexcept
ionhandl
i
ngandt
het
ypechecki
ngmechani
sm i
nJav
a.Al
lthese
poi
ntsmakeJav
arobust
.
 Por
tabl
e:Wemaycar
ryt
hej
avaby
tecodet
oanypl
atf
orm
 Mul
ti
-t
hreaded:At
hreadi
sli
keasepar
atepr
ogr
am,execut
ingconcur
rent
ly.Wecanwr
it
e
Jav
apr
ogr
amst
hatdealwi
thmanyt
asksatoncebydef
ini
ngmul
ti
plet
hreads.Themai
n
adv
ant
ageofmul
ti
-t
hreadi
ngi
sthati
tshar
est
hesamememor
y.Thr
eadsar
eimpor
tantf
or
mul
ti
-medi
a,Webappl
i
cat
ionset
c.
 I
nter
pret
ed–Jav
aby
tecodei
str
ansl
atedont
hef
lyt
onat
ivemachi
nei
nst
ruct
ionsandi
s
notst
oredany
wher
e.Thedev
elopmentpr
ocessi
smor
erapi
dandanal
yti
calsi
ncet
he
l
i
nki
ngi
sani
ncr
ement
alandl
i
ght
-wei
ghtpr
ocess.

Jav
aEdi
ti
ons

Ther
ear
ebasi
cal
l
yfouredi
ti
onsofj
ava.

13
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

 Jav
aSt
andar
dEdi
ti
on(
SE)–i
tisusedt
odev
elopcl
i
ent
-si
dest
andal
oneappl
i
cat
ionsorappl
ets.I
t
def
inesev
ery
thi
ngf
rom t
hebasi
cty
pesandobj
ect
soft
heJav
apr
ogr
ammi
ngl
anguaget
ohi
gh-
l
evel
classest
hatar
eusedf
ornet
wor
king,
secur
it
y,dat
abaseaccess,
graphi
cal
useri
nter
face(
GUI
)
dev
elopment
,andXMLpar
sing.Consi
stsofav
irt
ual
machi
ne,
dev
elopmentt
ool
s,depl
oyment
t
echnol
ogi
es,
andot
hercl
assl
i
brar
iesandt
ool
ki
tscommonl
yusedi
nJav
atechnol
ogy
appl
i
cat
ions.
 Jav
aEnt
erpr
iseEdi
ti
on(
EE)–i
sgear
edt
owar
ddev
elopi
ngl
arge-
scal
e,di
str
ibut
ednet
wor
king
appl
i
cat
ionsandweb-
basedappl
i
cat
ions.I
nthepast
,mostcomput
erappl
i
cat
ionsr
anon

standal
one”comput
ers(
comput
erst
hatwer
enotnet
wor
kedt
oget
her
).Today
’sappl
i
cat
ionscan
bewr
it
tenwi
tht
heai
m ofcommuni
cat
ingamongt
hewor
ld’
scomput
ersv
iat
heI
nter
netandt
he
web.
 Jav
aMobi
leEdi
ti
on(
ME)–i
sgear
edt
owar
ddev
elopi
ngappl
i
cat
ionsf
orsmal
l
,memor
y-
const
rai
neddev
ices,
suchasBl
ackBer
rysmar
tphones.TheJav
aMEpl
atf
orm pr
ovi
desanAPIand
asmal
l
-foot
pri
ntv
irt
ual
machi
nef
orr
unni
ngJav
apr
ogr
ammi
ngl
anguageappl
i
cat
ionsonsmal
l
dev
ices,
li
kemobi
l
ephones.TheAPIi
sasubsetoft
heJav
aSEAPI
,al
ongwi
thspeci
alcl
ass
l
i
brar
iesusef
ulf
orsmal
ldev
iceappl
i
cat
iondev
elopment
.Jav
aMEappl
i
cat
ionsar
eof
tencl
i
ent
s
ofJav
aEEpl
atf
orm ser
vices.
 Jav
aFX–i
tisapl
atf
ormf
orcr
eat
ingr
ichi
nter
netappl
i
cat
ionsusi
ngal
i
ght
wei
ghtuser
-i
nter
face
API
.Jav
aFXappl
i
cat
ionsusehar
dwar
e-accel
erat
edgr
aphi
csandmedi
aengi
nest
otake
adv
ant
ageofhi
gher
-per
for
mancecl
i
ent
sandamoder
nlook-
and-
feel
aswel
lashi
gh-
lev
elAPI
sfor
connect
ingt
onet
wor
keddat
asour
ces.Jav
aFXappl
i
cat
ionsmaybecl
i
ent
sofJav
aEEpl
atf
orm
ser
vices.

Dev
elopmentEnv
ironment
:
Thepl
acewher
esof
twar
eisbei
ngdev
eloped.Exampl
e:Sof
twar
eCompany
.Ther
equi
redt
ool
sto
dev
elopasof
twar
ear
e
 Compi
l
er(
jav
ac)
,debugger(
jdb)
,Jav
aVi
rt
ualMachi
neorI
nter
pret
er(
jav
a),packagi
ngt
ool
(
.j
ar)
,runni
ngAppl
et(
appl
etv
iewer
),et
c.
JDK
 I
tcont
ainst
hesof
twar
edev
elopmentt
ool
sli
stedabov
e.
 JDK=JRE+Dev
elopmentt
ool
s

14
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

I
DE
 I
tisal
ltheJDKt
ooli
ntegr
atedandaccessi
blef
rom asi
ngl
ewi
ndow.Exampl
e:Net
Beans,
Ecl
i
pse,
etc.
Pr
oduct
ionEnv
ironment
:
 I
tisapl
acewher
easof
twar
eisbei
ngusedatr
eal
-env
ironment(
cli
entenv
ironment
).
JRE
 JRE=JVM +Jav
ali
brar
ies
Jav
apr
ogr
amsnor
mal
l
ygot
hroughf
ivephases.Theyar
eedi
t,compi
l
e,l
oad,
ver
if
yandexecut
e.

Phase1:Cr
eat
ingaPr
ogr
am

I
tconsi
stsofedi
ti
ngaf
il
ewi
thanedi
torpr
ogr
am,
nor
mal
l
yknownsi
mpl
yasanedi
tor(
Not
epad,
Edi
tPl
us(
www.
edi
tpl
us.
com)
,Text
Pad(
www.
text
pad.
com)andj
Edi
t(www.
jedi
t.
org)
.Yout
ypea
Jav
apr
ogr
am (
sour
cecode)usi
ngt
heedi
tor
,makeanynecessar
ycor
rect
ionsandsav
ethe
pr
ogr
am onasecondar
yst
oragedev
ice,
suchasy
ourhar
ddr
ive.Af
il
enameendi
ngwi
tht
he.
jav
a
ext
ensi
oni
ndi
cat
est
hatt
hef
il
econt
ainsJav
asour
cecode.

Phase2:Compi
li
ngaJav
aPr
ogr
am i
ntoBy
tecodes

I
nthi
s,y
ouuset
hecommandj
avac(
theJav
acompi
l
er)t
ocompi
l
eapr
ogr
am.Forexampl
e,t
o
compi
l
eapr
ogr
am cal
l
edWel
come.
jav
a,y
ou’
dty
pe

i
nthecommandwi
ndowofy
oursy
stem (
i.
e.,
theCommandPr
ompti
nWi
ndows)
.Ift
hepr
ogr
am
compi
l
es,
thecompi
l
erpr
oducesa.
classf
il
ecal
l
edWel
come.
classt
hatcont
ainst
hecompi
l
ed
v
ersi
onoft
hepr
ogr
am.

15
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

TheJav
acompi
l
ert
ransl
atesJav
asour
cecodei
ntoby
tecodes.By
tecodesar
eexecut
edbyt
he
Jav
aVi
rt
ual
Machi
ne(
JVM)–apar
toft
heJDKandt
hef
oundat
ionoft
heJav
apl
atf
orm.AVM i
s
asof
twar
eappl
i
cat
iont
hatsi
mul
atesacomput
erbuthi
dest
heunder
lyi
ngoper
ati
ngsy
stem and
har
dwar
efr
om t
hepr
ogr
amst
hati
nter
actwi
thi
t.I
fthesameVM i
simpl
ement
edonmany
comput
erpl
atf
orms,
appl
i
cat
ionst
hati
texecut
escanbeusedonal
lthosepl
atf
orms.TheJVM i
s
oneoft
hemostwi
del
yusedv
irt
ual
machi
nes.

Unl
i
kemachi
nel
anguage,
whi
chi
sdependentonspeci
fi
ccomput
er
har
dwar
e,byt
ecodesar
epl
atf
ormi
ndependent
.So,
Jav
a’sby
tecodesar
epor
tabl
e–wi
thout
r
ecompi
l
ingt
hesour
cecode,
thesameby
tecodescanexecut
eonanypl
atf
orm.TheJVM i
s
i
nvokedbyt
hej
avacommand.Forexampl
e,t
oex
ecut
eaJav
aappl
i
cat
ioncal
l
edWel
come,
you’
d
t
ypet
hecommand

Phase3:Loadi
ngaPr
ogr
am i
ntoMemor
y

I
nthi
s,t
heJVM pl
acest
hepr
ogr
am i
nmemor
ytoexecut
eit–t
hisi
sknownasl
oadi
ng.The
JVM’
scl
assl
oadert
akest
he.
classf
il
escont
aini
ngt
hepr
ogr
am’
sby
tecodesandt
ransf
erst
hem
t
opr
imar
ymemor
y.Thecl
assl
oaderal
sol
oadsanyoft
he.
classf
il
espr
ovi
dedbyJav
athaty
our
pr
ogr
am uses.The.
classf
il
escanbel
oadedf
rom adi
skony
oursy
stem orov
eranet
wor
k(e.
g.,
y
ourl
ocal
col
l
egeorcompanynet
wor
k,ort
heI
nter
net
).

16
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

Phase4:By
tecodeVer
if
icat
ion

I
nthi
s,ast
hecl
assesar
eloaded,
theby
tecodev
eri
fi
erexami
nest
hei
rby
tecodest
oensur
ethat
t
hey
’rev
ali
danddonotv
iol
ateJav
a’ssecur
it
yrest
ri
cti
ons.Jav
aenf
orcesst
rongsecur
it
ytomake
sur
ethatJav
apr
ogr
amsar
ri
vi
ngov
ert
henet
wor
kdonotdamagey
ourf
il
esory
oursy
stem (
as
comput
erv
irusesandwor
msmi
ght
).

Phase5:Execut
ion

I
nthi
s,t
heJVM execut
est
hepr
ogr
am’
sby
tecodes,
thusper
for
mingt
heact
ionsspeci
fi
edbyt
he
pr
ogr
am.TheJVM anal
yzest
heby
tecodesast
hey
’rei
nter
pret
ed,
sear
chi
ngf
orhotspot
s–par
ts
oft
heby
tecodest
hatexecut
efr
equent
ly.Fort
hesepar
ts,
ajust
-i
n-t
ime(
JIT)compi
l
er–knownas
t
heJav
aHot
Spotcompi
l
er–t
ransl
atest
heby
tecodesi
ntot
heunder
lyi
ngcomput
er’
smachi
ne
l
anguage.Whent
heJVM encount
erst
hesecompi
l
edpar
tsagai
n,

17
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

t
hef
ast
ermachi
ne-
languagecodeexecut
es.Thus,
Jav
apr
ogr
amsact
ual
l
ygot
hrought
wo
compi
l
ati
onphases–onei
nwhi
chsour
cecodei
str
ansl
atedi
ntoby
tecodes(
forpor
tabi
l
ityacr
oss
JVMsondi
ff
erentcomput
erpl
atf
orms)andasecondi
nwhi
ch,
dur
ingexecut
ion,
theby
tecodes
ar
etr
ansl
atedi
ntomachi
nel
anguagef
ort
heact
ual
comput
eronwhi
cht
hepr
ogr
am execut
es.

Pr
obl
emsThatMayOccuratExecut
ionTi
me

Jav
avi
rt
ualmachi
ne(
JVM)

Compi
l
ingJav
asour
cecodedoesnotr
esul
tinamachi
nel
anguagepr
ogr
am.I
nst
ead,
whenJav
a
sour
cecodei
scompi
l
ed,
wegetwhati
scal
l
edJav
aby
tecode.Jav
aby
tecodei
saf
orm of
machi
nel
anguagei
nst
ruct
ions.Howev
er,
iti
snotpr
imi
ti
vet
otheCPU.Jav
aby
tecoder
unsona
pr
ogr
am t
hatmi
micsi
tsel
fasar
eal
machi
ne.Thi
spr
ogr
am i
scal
l
edt
heJav
aVi
rt
ual
Machi
ne
(
JVM)orJav
aRun-
ti
meEnv
ironment(
JRE)
.Thi
sar
chi
tect
uremakesJav
aby
tecoder
unsonany
machi
nest
hathav
eJVM,
independentoft
heOSsandCPUs.Thi
smeanst
heef
for
tinwr
it
ingj
ava
sour
cecodef
oracer
tai
npr
ogr
am i
sspentonceandt
het
argetpr
ogr
am canr
unonanypl
atf
orms.
(
E.g.Wi
ndows,
MacOS,
UNI
X,et
c.)

Jav
avi
rt
ualmachi
ne(
JVM)
Compi
l
ingJav
asour
cecodedoesnotr
esul
tinamachi
nel
anguagepr
ogr
am.I
nst
ead,whenJav
a
sour
cecodei
scompi
l
ed,wegetwhati
scal
l
edJav
aby
tecode.Jav
aby
tecodei
saf
orm of
machi
nel
anguagei
nst
ruct
ions.Howev
er,i
tisnotpr
imi
ti
vet
otheCPU.Jav
aby
tecoder
unsona

18
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

pr
ogr
am t
hatmi
micsi
tsel
fasar
ealmachi
ne.Thi
spr
ogr
am i
scal
l
edt
heJav
aVi
rt
ualMachi
ne
(
JVM)orJav
aRun-
ti
meEnv
ironment(
JRE)
.Thi
sar
chi
tect
uremakesJav
aby
tecoder
unsonany
machi
nest
hathav
eJVM,
independentoft
heOSsandCPUs.Thi
smeanst
heef
for
tinwr
it
ingj
ava
sour
cecodef
oracer
tai
npr
ogr
am i
sspentonceandt
het
argetpr
ogr
am canr
unonanypl
atf
orms.
(
E.g.Wi
ndows,
MacOS,
UNI
X,et
c.)
By
tecodesar
easetofi
nst
ruct
ionst
hatl
ooksal
otl
i
kesomemachi
necodes,
butt
hati
snot
speci
fi
ctoanyonepr
ocessor
.

6. Jav
aNami
ngconv
ent
ions
Jav
anami
ngconv
ent
ioni
sar
ulet
ofol
l
owasy
oudeci
dewhatt
onamey
ouri
dent
if
ier
ssuchas
cl
ass,package,v
ari
abl
e,const
ant
,met
hodet
c.But
,iti
snotf
orcedt
ofol
l
ow.So,i
tisknownas
conv
ent
ion notr
ule.Al
lthe cl
asses,i
nter
faces,packages,met
hods and f
iel
ds ofj
ava
pr
ogr
ammi
ngl
anguagear
egi
venaccor
dingt
ojav
anami
ngconv
ent
ion.

6.
1.Adv
ant
ageofnami
ngconv
ent
ionsi
njav
a
Byusi
ngst
andar
dJav
anami
ngconv
ent
ions,
youmakey
ourcodeeasi
ert
oreadf
ory
our
sel
fand
f
orot
herpr
ogr
ammer
s.Readabi
l
ityofJav
apr
ogr
am i
sver
yimpor
tant
.Iti
ndi
cat
est
hatl
ess
t
imei
sspentt
ofi
gur
eoutwhatt
hecodedoes.

Name Conv
ent
ion

cl
assname shoul
dst
artwi
thupper
casel
ett
erandbeanoune.
g.St
ri
ng,
Col
or,
But
ton,
Syst
em,
Thr
eadet
c.

i
nter
facename shoul
dst
artwi
thupper
casel
ett
erandbeanadj
ect
ivee.
g.
Runnabl
e,Remot
e,Act
ionLi
steneret
c.

met
hodname shoul
dst
artwi
thl
ower
casel
ett
erandbeav
erbe.
g.
act
ionPer
for
med(
),mai
n()
,pr
int
(),
pri
ntl
n()et
c.

v
ari
abl
ename shoul
dst
artwi
thl
ower
casel
ett
ere.
g.f
ir
stName,
order
Numberet
c.

packagename shoul
dbei
nlower
casel
ett
ere.
g.j
ava,
lang,
sql
,ut
ilet
c.

const
ant
sname Shoul
dbei
nupper
casel
ett
er.e.
g.RED,
YELLOW,
MAX_
PRI
ORI
TY
et
c.

19
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

6.
2.Under
standi
ngCamelCasei
njav
anami
ngconv
ent
ions
Jav
afol
l
owscamel
casesy
ntaxf
ornami
ngt
hecl
ass,
int
erf
ace,
met
hodandv
ari
abl
e.
I
fnamei
scombi
nedwi
tht
wowor
ds,secondwor
dwi
l
lst
artwi
thupper
casel
ett
eral
way
se.
g.
act
ionPer
for
med(
),f
ir
stName,
Act
ionEv
ent
,Act
ionLi
steneret
c.
Si
mpl
eJav
aPr
ogr
am

Thev
ari
oust
ermsusedi
ntheabov
epr
ogr
am hav
esomespeci
fi
cpur
pose.Theset
ermsar
e:

Publ
ic– publ
i
cisanaccessmodi
fi
erusedt
odef
ineaccessr
est
ri
cti
ons.I
nthi
scase,publ
i
c
i
mpl
i
est
hatt
hecl
ass“
Mai
n”i
spubl
i
clyav
ail
abl
eandi
tsf
unct
ionmai
n()canbeaccessedby
Cl
ass–t
hekey
wor
dcl
assbegi
nst
hecl
assdef
ini
ti
onf
oranewl
ycr
eat
edcl
ass,
sayMai
n.
St
ati
c– t
hiskey
wor
dst
atest
hatt
hef
unct
ionmai
n()i
sacl
assf
unct
ionwhi
chcanbecal
l
ed
wi
thouti
nst
ant
iat
ingt
hecl
ass.
Voi
d–t
het
ermv
oidr
efer
stot
her
etur
nty
peandshowst
hatt
hef
unct
ionmai
n()doesn’
tret
urn
anyv
alue.
mai
n()–i
sthemai
nst
art
ingpoi
ntofexecut
ioni
nev
eryJav
apr
ogr
am.
St
ri
ngar
gs[
]–t
hisi
sthepar
amet
erl
i
stoff
unct
ionmai
n()
.Itsay
sthatt
hemai
n()f
unct
ioncan
acceptanar
rayofSt
ri
ngobj
ectt
hatr
epr
esentt
hecommand–l
i
near
gument
spassedbyt
heuser
att
het
imeofexecut
ion.St
ri
ngi
sthenameofpr
edef
inedcl
ass.
Sy
stem – i
sapr
edef
inedcl
assusedt
oaccesst
hekey
boar
dandmoni
tor
.Iti
suseddi
rect
ly
becausei
tisf
oundi
nthepackagej
ava.
langi
nwhi
chi
tisaut
omat
ical
l
yincl
udedi
nanyJav
a
pr
ogr
am.
Out–r
efer
stot
heconsol
e/moni
tor
.Itdef
inesanout
putst
ream usedt
oout
putsomet
hingont
he
moni
tor
.
Pr
int
ln/
pri
nt–i
susedt
opr
intdi
ff
erentt
ypesofv
ari
abl
esandt
ext
.
{
}-t
hesebr
acesar
eusedt
odef
inecl
assbodyandmet
hodbody
.

20
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

Thecl
assnamesshoul
dbet
hesameaswi
tht
hef
il
enamewher
ethecl
assl
i
ves.
egcl
assnamed
Mai
nhast
obesav
edi
nthef
il
ecal
l
edMai
n.j
ava.
Not
e:Jav
aiscase–sensi
ti
ve.
7. Jav
aDev
elopmentEnv
ironment
Jav
adev
elopmentki
tist
het
ool
sthatar
eusedt
odev
elopandexecut
eJav
apr
ogr
ams.
Basi
ctool
s:t
heset
ool
sar
ethef
oundat
ionoft
heJav
a2SDK(
Sof
twar
eDev
elopmentSy
stem)
.
Theyar
ethet
ool
susedt
ocr
eat
eandbui
l
dappl
i
cat
ions.
1.Jav
ac–i
stheJav
alanguagecompi
l
er,whi
chconv
ertJav
asour
cecodei
ntoby
tef
il
e(by
te
code)
.(Jav
accl
assName.
jav
a)
2.Jav
a–t
heJav
alanguagei
nter
pret
er,whi
chi
susedt
orunJav
aappl
i
cat
ionpr
ogr
am.(
jav
a
cl
assname)
3.Jav
adoc – cr
eat
esdocument
ati
on i
n HTML f
ormatf
rom t
he j
ava sour
ce code.
(j
avadoc
cl
assName.
j
ava)
4.Appl
etv
iewer–r
unanddebugappl
etswi
thoutawebbr
owser
.

7.
1.St
epsf
orCr
eat
ing,
Compi
li
ngandRunni
ngJav
apr
ogr
ams
1.Cr
eat
ingasour
cef
il
e–asour
cef
il
econt
ainst
extwr
it
teni
nJav
apr
ogr
ammi
ngl
anguage.
2.Compi
li
ng–t
hecompi
l
er,Jav
ac,t
akest
hesour
cef
il
eandt
ransl
atesi
tst
exti
ntoi
nst
ruct
ion
t
hatt
heJav
aVi
rt
ualMachi
ne(
JVM)canunder
stand(
byt
ecodef
il
e).By
tecodei
sknownas
compi
l
edcodeorby
tecodei
shi
ghl
yopt
imi
zedsetofi
nst
ruct
iondesi
gnedt
obeexecut
edby
JVM.
3.Run–t
hei
nter
pret
ert
akest
heby
tecodef
il
eandcar
ri
est
hem i
ntoi
nst
ruct
iont
hatacomput
er
canunder
stand.

21
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

Basi
csi
nJav
aPr
ogr
ammi
ng

1.I
ntr
oduct
ion
Javapr ogrammi nglanguagewasor i
ginal
l
ydevelopedbySunMicrosystemswhi chwasi ni
ti
ated
byJamesGosl ingandr el
easedin1995ascorecomponentofSunMi crosyst
ems’Jav aplat
form.
Sun Mi crosyst
emshasr enamed t
he new J2 v er
sionsasJav
a SE,Jav a EE and Java ME,
respect
ively.Javai sguarant
eedtobeWr i
teOnce,RunAnywher
e.Jav afoll
owsobj ectori
ented
programmi ngpar adi
gm.

 Object-Obj ect
shav estatesandbehav iors.Exampl e:Adoghasst at
es-
color,name,and
breedaswel lasbehav iors- wagging,barking,andeat i
ng.Anobj ectisani nstanceofa
class.
 Class-Acl asscanbedef inedasat emplate/bluepr intthatdescr
ibethebehav i
or s/
states
thatobjectofit
st ypesuppor t.
 Met hods-Amet hodisbasi call
yabehav i
or.Acl asscancont ai
nmanymet hods.
 InstantVariables-Eachobj ecthasitsuniquesetofi nstantvari
ables.Anobject'sstateis
createdbythev aluesassignedt otheseinstantv ar
iables.
Fi
rstJav
aPr
ogr
am
Letuslookatasi mplecodet hatwouldpri
ntthewordsHelloWorl
d.
publi
cclassMy First
JavaProgram{
/*Thisismyf i
rstj
avaprogram.
*Thiswill
pr i
nt'Hel
loWor l
d'astheoutput
*/
publi
cstati
cv oidmain(St
ring[]
args){
System.out.pri
ntl
n("
Hell
oWor ld")
;//pr
int
sHell
oWor ld
}
}
AboutJavapr ograms,iti
sv eryi
mpor t
anttokeepi
nmi ndthefol
l
owingpoi
nts.

 CaseSensi
ti
vit
y-Javai
scasesensi
ti
vewhi
chmeansi
dent
if
ierHel
loandhel
lowoul
dhav
e
di
ffer
entmeani
nginJav
a.

 ClassNames-Forallclassnamest
hefi
rstl
ett
ershoul
dbei
nUpperCase.
I
fsev er
alwordsar
eusedt ofor
m anameofthecl
asseachi
nnerwor
dsfi
rstl
ett
ershoul
d
beinUpperCase.
ExampleclassMyFir
stJavaCl
ass

 Met hodNames-Allmethodnamesshoul
dst
artwi
thaLowerCaselet
ter.
I
fsev er
alwordsar
eusedtoformthenameoft
hemethod,t
heneachinnerwor
d'sf
ir
st
l
ettershoul
dbeinUpperCase.
Examplepubli
cvoi
dmyMet hodName()

22
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

 Progr
am Fil
eName-Nameoft heprogram fil
eshouldexact
lymatcht
heclassname.
Whensav i
ngthefil
ey oushoul dsavei tusi
ngt hecl
assname( Rememberj
avaiscase
sensi
ti
ve)andappend' .j
ava'totheendoft hename.(ift
hefi
lenameandtheclassnamedo
notmatchyourprogram wi l
lnotcompi l
e).
Example:Assume'My Fi
rstJavaProgram' i
stheclassname.Thenthefi
l
eshouldbesaved
as'MyFi
rst
JavaProgram. j
ava'

 publ
icst
ati
cvoi
dmain(
Str
ingargs[]
)-j
avapr
ogram processi
ngst
art
sfr
om t
hemai
n()
methodwhi
chisamandat
orypartofev
eryj
avaprogram.
2.Jav
aIdent
if
ier
s
Al
lJavacomponent srequi renames.Namesusedf orclasses,vari
ablesandmet hodsarecal
led
i
denti
fi
ers.Injavatherear esev eralpointstorememberabouti denti
fier
s.Theyareasf ol
l
ows:
 Al lidenti
fi
ersshoul dbegi nwi thalett
er(At oZorat oz) ,
currencycharacter(
$)oran
under scor
e(_).Itcannotst artwit
hadi git.
 Af terthefir
stchar acterident i
fi
erscanhav eanycombi nati
onofchar act
ers.
 Ak eywor dcannotbeusedasani denti
fier.
 Mo stimportantl
yi dentif
iersar ecasesensi ti
ve.
 E xampl esoflegal identi
fiers:age,$salary,_val
ue,__1_value
Exampl esofill
egal identif
iers:123abc, -
salary
3.Dat
aTy
pes
Vari
ablesar ereservedmemor ylocati
onst ostor
evalues.Thismeanst hatwheny oucr
eatea
vari
abl
ey our eservesomespacei nmemor y.Basedont hedatatypeofav ar
iabl
e,theoperat
ing
syst
em allocatesmemor yanddecideswhatcanbest oredinthereser
vedmemor y.Theref
ore,by
assi
gningdifferentdatatypestovari
ables,y
oucanstoreint
egers,
decimal
s,orcharacter
sinthese
vari
abl
es.
Therearetwodat aty
pesav ail
abl
einJav a:
 Primiti
v eDataTy pes
 Reference/ ObjectDataTypes

3.
1. Pr
imi
ti
veDat
aTy
pes
Ther
eareei
ghtpr
imit
ivedat
aty
pessuppor
tedbyJav
a.Pr
imi
ti
vedat
aty
pesar
epr
edef
inedbyt
hel
anguage
andnamedbyakeyword.

data Mi
nimum v
alue Maxi
mum v
alue def
aul
t Descr
ipt
ion
ty
pe

by
te -
2^7 2^
7-1 0 8-
bitsi
gnedt
wo'
scompl
ement
i
nteger
.

shor
t -
2^15 2^
15-
1 0 16-bi
tsi
gnedt
wo'
scompl
ement
i
nteger.

i
nt -
2^31 2^
31-
1 0 32-bi
tsi
gnedt
wo'
scompl
ement
i
nteger.
23
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

l
ong -
2^63 2^
63-
1 0l 64-bi
tsi
gnedt
wo'
scompl
ement
i
nteger.

f
loat 0.
0f 32-
bitI
EEE754f
loat
ingpoi
nt.

doubl
e 0.
0d 64-
bitI
EEE754f
loat
ingpoi
nt.

bool
ean Tr
ue/
fal
se Tr
ue/
fal
s f
alse Repr
esent
sonebi
tofi
nfor
mat
ion.

char '
\u0000'
(or0)
. '
\uf
fff
'(or65,
535) asi
ngl
e16-
bitUni
codechar
act
er.

3.
2. Ref
erenceDat
aTy
pes
Referencev ari
ablesarecreat edusingdefi
nedconst ructorsoftheclasses.Theyareusedt
o
accessobj ects.
 Cl assobj ect
sandv arioust ypesofarr
ayv ari
ablescomeunderr efer
encedatatype.
 Def aultvalueofanyr eferencev ar
iabl
eisnull.
 Ar eferencevariabl
ecanbeusedt orefertoanyobj ectofthedeclaredtypeoranycompat
ibl
e
ty
pe.
Exampl e: Ani
mal ani
mal =newAni mal("gi
raff
e");
4.Var
iabl
es
Eachvariabl
einJavahasaspeci f
ictype,whichdet
erminesthesizeandlayoutofthe
vari
abl
e'smemor y
;ther angeofv al
uest hatcanbestoredwi
thi
nthatmemory;andt
hesetof
operat
ionsthatcanbeappliedtothevari
able.
Youmustdecl ar
eallvar
iablesbef
oretheycanbeused.Thebasi
cform ofav
ari
abl
edeclar
ati
oni
s
shownher e:
dat
atypevar
iabl
e[=val
ue]
[,var
iabl
e[=val
ue].
..
];
Heredat atypei soneofJav a'
sdat atypesandv ar
iabl
eist henameoft hev ari
abl
e.To
declaremoret hanonev ari
abl eoft hespeci fi
edtype,
y oucanuseacomma- separat
edli
st.
Foll
owi ngarevalidexampl esofv ariabledecl arati
onandinit
iali
zat
ioni
nJav
a:
i
nta, b,c; / /Declarest hreeints, a, b,andc.
i
nta=10, b=10;/ /Exampl eofinitialization
byteB=22; / /ini
ti
alizesaby tet ypev ariabl
eB.
doublepi =3.14159; /
/decl aresandassi gnsav al
ueofPI.
chara=' a'
; / /thecharv ari
ableai siniti
ali
zedwit
hv al
ue' a'
5.Ty
peconv
ersi
on/
cast
ing
Casti
ngbetweenpr imiti
vety
pesmostcommonl yoccurswit
ht henumer
ict
ypes;
 Booleanvaluescannotbecasttoanyotherpri
miti
vetype.
Tocreateaconversionbetweentwoincompati
blety
pes,youmustuseacast.Acasti
ssi
mpl
yan
expl
ici
ttypeconversion.I
thast
hisgeneral
for
m:
(
tar
get
-t
ype)val
ue
inta;by t
eb; b=( by
te)a;
Adiff
erentty
peofconver
sionwilloccurwhenafl
oati
ng-
poi
ntval
ueisassi
gnedtoanint
egertype:
t
runcati
on.Asyouknow,integer
sdonothav ef
ract
ional
component
s.Thus,whenafl
oati
ng-poi
nt
24
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

val
ueisassi gnedtoanint
egerty
pe,thefr
act
ional
componenti
slost
.
Example:intc;doubled=323.142;c=(i
nt)d
Syst
em. out.
print
(c)
//323
6.Jav
aKey
wor
ds
Thefollowi
ngli
stshowsther
eser
vedwordsi nJav
a.Theser
eser
vedwor
dsmaynotbeusedas
constantorvar
iabl
eoranyot
heri
dent
if
iernames.
abstr
act asser t bool
ean br eak

by
te case cat
ch char

cl
ass const cont
inue def
aul
t

do doubl
e el
se enum

ext
ends f
inal f
inal
l
y 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
i
c r
etur
n

shor
t st
ati
c st
ri
ctf
p super

swi
tch sy
nchr
oni
zed t
his t
hrow

t
hrows t
ransi
ent t
ry v
oid

v
olat
il
e whi
l
e

7.Comment
s
Javasuppor t
ssi nglelineandmul t
i-
li
necomment sverysi
milartocandc++.Al
lchar
act
ers
avai
labl
ei nsi
deanycommentar ei gnoredbyJavacompil
er.Commentsar
everyi
mport
antto
expl
ainthepurposeoft hecodeorf uncti
onswhichi
mprov
ereadabil
i
ty.
publi
cclassMy FirstJavaProgram{
/*Thisismyf irstjavaprogram.
Thisisanexampl eofmul ti
-l
inecomment s.
*/
publi
cstati
cv oidmai n(St
ri
ng[ ]
args){
//Thisisanexampl eofsinglelinecomment
/*Thisisalsoanexampl eofsi ngleli
necomment.*
/
System.out.
pr int
ln(
"Hell
oWor ld");
}
}

25
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

8.Li
ter
als
Aliteralisasour cecoder epresentat
ionofaf i
xedvalue.Theyarerepr
esenteddirect
lyi
nthecode
withoutanycomput ati
on.Literal
scanbeassi gnedtoanypr i
miti
vetypevari
able.
Forexampl e:
bytea=68; chara=' A'
Stri
ngl i
t er
alsinJav aarespeci fi
edl i
ketheyareinmostot herl
anguagesbyenclosingasequence
ofchar actersbet weenapai rofdoubl equotes.Examplesofstr
ingl
iter
alsar
e:
"HelloWor ld"
"t
wo\ nlines"
"\"
Thisi sinquot es\"
"
Javal anguagesuppor t
sf ewspeci alescapesequencesforStri
ngandcharlit
eral
s.Theyare:
Not atio Character
n r
epresent ed

\
n Newl
i
ne

\
f For
mfeed

\
b Backspace

\
s Space

\
t t
ab

\
" Doubl
equot
e

\
' Si
ngl
equot
e

\
\ backsl
ash

9.Const
ant
s
Tostorevaluest
hatneverchange,
youneedtodeclareaconst
ant—j
ustaddt
hekey
wor
dfi
nalt
o
thedeclar
ati
onli
neli
kefinal
Stri
ngMANUFACTURER;
Thevalueofaconstantcanbeassi
gnedonlyonce,
Example:fi
nalSt
ri
ngMANUFACTURER=“ J.B.Li
mited”
;
10. St
ri
ng
Stri
ngswhichar ewidelyusedinJavaprogrammingar
easequenceofcharacter
s.Int
heJav
a
programmi
ngl anguage,str
ingsar
eobject
s.TheJavapl
atf
orm pr
ovi
destheSt
ri
ngclasst
ocr
eat
e
andmanipulat
est r
ings.Themostdir
ectwaytocr
eateastr
ingi
stowrit
e:

publ
iccl
assSt
ri
ngExampl
e{
publ
icst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Str
ings1="
java"
;//
creat
ingstr
ingbyJav
ast
ri
ngl
i
ter
al
charch[
]={
's'
,
't
',
'
r'
,'
i
',
'
n',
'
g',
'
s'}
;
26
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

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
ngbynewkey
wor
d
Sy
stem.
out
.pr
int
ln(
s1)
;
Sy
stem.
out
.pr
int
ln(
s2)
;
Sy
stem.
out
.pr
int
ln(
s3)
;
}
}

St
ri
ngMet
hods
Herei st heli
stofsomemet hodssuppor tedbySt r
ingclass:
Stri
ngt oLower Case(Local el ocale):Conv er
tsallofthechar actersint hisSt
ri
ngt ol
owercase
usingt her ul
esoft hegiv enLocal e.
Stri
ngt oSt ri
ng():Thisobj ect(whichisalreadyast r
ing!
)isitsel
freturned.
Stri
ngt oUpper Case():Conv ertsallofthechar act
ersinthisStri
ngt ouppercaseusingt
herul
esof
thedef aultlocale.
Stri
ngt r i
m( )
:Returnsacopyoft hestr
ing,wi t
hleadingandt r
ail
i
ngwhi t
espaceomitt
ed
Stri
ngt oLower Case():Conv ertsallofthechar act
ersinthisStri
ngt olowercaseusingt
herul
esof
thedef aultlocale.
i
ntl engt h(
): Returnsthel engthoft hi
sstring.
Stri
ngconcat (
Stri
ngst r):Concat enat
esthespeci fi
edstri
ngt otheendoft hi
sst
ri
ng.
Str
ingsubstr
ing(
intbegi
nIndex,
intendI
ndex):Ret
ur nsanewstri
ngt hati
sasubst
ri
ngofthi
sstr
ing.used
toret
urnthesubstr
ingoft
hemai nStr
ingbyspecif
yingthest
art
ingindexandt
helasti
ndexoft
hesubstr
ing.

Stringstr=" Soft
war et
estinghelp";
System.out .
pri
ntl
n(str
.substring(
8,12))
;
/
/ I
twillstartfr
om 8thcharact erandextractt
hesubst
ri
ngt
il
l12t
hchar
act
er
System. out.pr
int
ln(
str.
subst r
ing(15,19)
);
Out put
Test
hel
p
bool
eanequal
s(Obj
ectanObj
ect
):Compar
est
hisst
ri
ngt
othespeci
fi
edobj
ect
.

St
ri
ngr
epl
ace(
):Ther
epl
ace(
)met
hodi
susedt
orepl
acet
hechar
act
erwi
tht
henewchar
act
ersi
naSt
ri
ng.

St
ringstr="Shot"
;
Str
ingreplace=str.
replace(
'o'
,'
u'
); Shot
System.out.
pri
ntl
n(str)
; shut
System.out.
pri
ntl
n(repl
ace);

St
ri
ng[
]spl
it
(St
ri
ngr
egex):
Spl
i
tst
hisst
ri
ngar
oundmat
chesoft
hegi
venr
egul
arexpr
essi
on.

Ex
ampl
e1:
Str
ingspl
i
tti
ng

publ
i
ccl
assSt
ri
ngMet
hods{
27
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

publicstaticv oi
dmai n(
Stri
ng[
]args){
Stri
ngst r=" welcomet oSoftwareEngi
neer
ing,
Woldia,
Ethi
opia"
;
Stri
ng[
]spl it=str.spli
t(
","
);
for(St
ringobj :split
){ welcometoSoftwareEngi
neer
ing
Syst
em. out.
printl
n(obj)
; Woldia
} Ethi
opia
}
}
Acti
vi
ti
es:
1)Countthenumberofchar acter
sinthestr
inginexampleone?
2)Findthel
astoccurrenceoflett
er‘
W’ f
rom thegi
ventext
?
3)Wr i
teanalgori
thm t
hatextr
act“sof
twareEngineer
ing”f
rom agiv
enpar
agr
aph?
4)Wr i
teaprogram t
hatcountthenumberofwor dsofagivenprogr
am?

11. Ar
ray
s
Arraysareobj
ect sthatst oremul t
ipl
ev ari
ablesofthesamet ype.Theel ement sofanarraycanbe
eit
herprimit
ivet ypesorr ef
erencet ypes.Tor ef
ertoapar t
icularelementi nanar r
ay,wespecif
y
thenameoft her eferencet othear r
ayandt heposi
tionnumberoft heelementi nthearray
.The
posit
ionnumberoft heel ementi scalledtheelement ’si
ndexorsubscr ipt.Thef i
rstel
ementin
everyarr
ayhasi ndexzer o.Ani ndexmustbeani ntvalueorav alueofatypet hatcanbepromoted
toint—namely,byte,shortorchar ,butnotlong;other
wi se,
acompi lat
ionerroroccurs.

 Anarrayi
sahomogenousnon-
pri
mit
ivedat
aty
peusedt
osav
emul
ti
pleel
ement
s(hav
ing
thesamedat
aty
pe)i
naparti
cul
arvar
iabl
e.

 Anar
rayisusedtostoreacol
l
ect
ionofdat
a,buti
tisof
tenmor
eusef
ult
othi
nkofanar
ray
asacol
lect
ionofvar
iabl
esoft
hesametype.

 Thenew keywor
discr
uci
alt
ocr
eat
inganar
ray
.Wi
thoutusi
ngi
t,wecannotmakear
ray
ref
erencev
ari
abl
es.

 Ar
ray
sinJav
adonothav
ein-
bui
l
tremov
eoraddmet
hods.

 Ar
ray
sinJav
aar
est
rongl
yty
ped.

 f
orl
oopandf
or-
eachl
oopcoul
dbeusedf
orl
oopi
ngt
hroughal
lthear
rayel
ement
s.

 Ar
rayi
ndi
cesal
way
sst
artf
rom 0.Thati
s,t
hef
ir
stel
ementofanar
rayi
sati
ndex0.

 I
fthesi
zeofanar
rayi
sn,
thent
hel
astel
ementoft
hear
raywi
l
lbeati
ndexn-
1

 Wheneverwetrytoaccessanelementusi
nganindexlessthan0orgreatert
hanthearray
l
engt
h,JVM abort
stheprogram byr
aisi
nganexcept
ionofIndexOut
OfBoundsExcept
ion

 Anar
rayel
ementv
aluecanbeaccessedr
andoml
yjustbyusi
ngt
hei
ndexi
ndi
cat
edbyt
he
28
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

ar
ray
.

 Li
kewi
sepr
imi
ti
vedat
aty
pes,
wecanal
soi
mpl
ementanar
rayofobj
ect
sinJav
a.

 anar
rayi
sacont
ainerofobj
ect
str
eat
edasr
efer
ences.

 Ar
ray
sinJavaarenon-pr
imi
ti
vedat
aty
pes.But
,anar
raycanhol
dbot
hpr
imi
ti
veandnon-
pr
imi
ti
vedat
atypevar
iabl
es.

 Oncewedecl
aret
hear
ray
,wecannotchangeorupdat
eit
ssi
zer
unt
ime.

 Ar
raywi
thnonamei
scal
l
edananony
mousar
rayper
for
medf
ori
nst
antuse.

 Ar
raycanbedupl
i
cat
edusi
ngt
hecl
one(
)pr
oper
tyf
orbot
hsi
ngl
eandmul
ti
-di
mensi
onal
ar
ray
s

I
nsteadofdecl ar
ingindivi
dualv ar
iabl
es,suchasnumber0,number1,.
..,andnumber
99,you
declar
eonear rayvari
ablesuchasnumber sandusenumber
s[0]
,number
s[1],
and.
..
,number
s[99]
torepresenti
ndivi
dualvari
ables.

11.
1.OneDi
mesi
onalAr
ray
Touseanar r
ayinapr ogram,youmustdecl areav ari
ablet
oref
erencethear
ray,andyoumust
specifythet y
peofar raythev ar
iabl
ecanr eference.Herei
sthesy nt
axfordeclar
inganar
ray
vari
able:
dataType[]array
RefVar;/
/preferr
edway
Exampl e:
Thef ol
lowingcodesnippetsar
eexampl esofthissyntax:
double[]my Li
st;
//pr
eferr
edway
Cr
eat
ingAr
ray
s:
Youcancr eateanar r
aybyusi ngt henewoper atorwiththef
oll
owingsyntax:
arr
ay RefVar=newdat aType[arraySi
ze];
Declari
ng an ar rayv ar
iable,creating an array ,and assi
gni
ng the refer
ence oft
he ar
rayt
o
thev ar
iablecanbecombi nedi nonest atement ,asshownbelow:
dataType[]arrayRefVar=newdat aType[arr
aySize];
Alt
er nati
velyyoucancr eatear r
aysasf oll
ows:
dataType[]arrayRefVar={value0,value1,.
..
,val
uek} ;
e.
g St r
ing[
]names={"
John"
,"Mary"
,"David",
"Sar
ah"
};
Thear r
ayel ementsareaccessedt hrought heindex.Array i
ndi
ces are 0-
based;thatis,they
star
tf r
om 0t oarr
ayRefVar.
length-1.
Exampl e:
Foll
owingst atementdecl
aresanar rayv ari
abl
e,my Li
st,
creat
esanarrayof10elementsofdouble
ty
peandassi gnsit
srefer
encet omy List:
double[
]my Li
st=newdouble[10];

El
emen 100 3 90 0 8 56.
6 1 32 23 1
29
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

t 4

i
ndex 0 1 2 3 4 5 6 7 8 9

my
List
[9]=1,
myLi
st[
0]=10

Exampl
e:Comput
eSum andAv
erageofAr
rayEl
ement
s
cl
assMai n{
publ icst aticv oidmai n(St
ri
ng[]args){
i
nt []number s={ 2,-9,0,5,12,-
25, 22,9,8,12}
;
i
ntsum =0;
Doubl eav erage;
//accessal lelement susingforeachl oop
//addeachel ementi nsum
for( intnumber :number s){
sum +=number ;
}
//gett het otal numberofel ement s
i
ntar ray Lengt h=number s.l
ength;
//cal culatet heav erage
//conv erttheav eragef r
om inttodoubl e
av erage=( (doubl e)sum /(double)arr
ayLengt
h);
Sy stem. out.println("
Sum ="+sum) ;
Sy stem. out.println("
Av er
age="+av er
age);
}
}
Out
put
:

Sum =36
Aver
age=3.
6

11.
2.Mul
ti
dimensi
onalAr
ray
s
I
nJav a,mul ti
dimensi onal arr
aysareactuall
yarraysofarray
s.Todeclar
eamul t
idi
mensionalar
ray
vari
able,specifyeachaddi ti
onali
ndexusi nganothersetofsquarebr
acket
s.Forexample,t
he
fol
lowingdecl aresat wo-di mensi
onal ar
rayvari
ablecall
edtwoD.
i
nttwoD[ ][
]=newi nt[
4][5]; //4row and5col umn
Thisall
ocat ea4by5ar rayandassi gnsittotwoD
Youcanal socr eat
eamul ti-
dimensionalarr
aywi t
hdefaultval
uesbyomitt
ingt
hev al
uesinthe
i
niti
ali
zationst atement.
Forexampl e:
i
nt[
][
]mat
rx={
i {1,
2},
{3,
4},
{5,
6}}
;
30
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

exampl eofmul tidimensi onal arr ay


publiccl assTwoDAr ray Exampl e{
publicst aticv oidmai n( String[ ]ar gs){
//decl aringandi nit
ializingar ray s
i
ntar r1[][]={ {1,2,
3} ,
{4,5, 6},{7,8,9} };
i
ntar r2[][]={ {2,2,
2} ,
{2,2, 2},{2,2,2} };
//Pr intingAr ray 1inmat rixf or mat
Syst em. out .
println("Ar ray 1- ")
;
for(inti =0;i<3;i++){ / /f or-loopf ornumberofr ows
for(intj =0; j
<3;j++){ / /f or -
loopf ornumberofcol umns
Sy st em. out .pri
nt(ar r1[i][
j]+"" );
}
Sy stem. out .
pr i
ntln();
}
//Pr intingAr ray 2inmat rixf or mat
Syst em. out .
println("Ar ray 2- ")
;
for(inti =0;i<3;i++){ / /f or-loopf ornumberofr ows
for(intj =0; j
<3;j++){ / /f or -
loopf ornumberofcol umns
Sy st em. out .pri
nt(ar r2[i][
j]+"" );
}
Sy stem. out .
pr i
ntln();
}
//cr eat inganot herar raywi tht hesamedi mensionst ostorether
esul
t
i
ntar r3[][]=newi nt[3][3];
//Mul tiplyingar r
1andar r2, stor ingr esult
sinarr3
Syst em. out .
println("Mul ti
plicat ionofAr ray1andAr ray2-");
for(inti =0;i<arr1.lengt h;i++){
for(intj =0; j
<ar r
2. l
engt h;j
++){
ar r3[i][
j]=0;
for (i
ntk=0; k<ar r3.lengt h; k++){
ar r3[ i
][j
]+=ar r1[i]
[k]*ar r2[k] [
j];
}
Sy st em. out .pri
nt(ar r3[i][
j]+"" );
}
Sy stem. out .
pr i
ntln();
}
}
}
Activi
t y:
1)Wr iteaJav apr ogr am t hatcal culatesum ofalldiagonalel
ement
sof5*
5doubl
edi
mensi
onal

31
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

ar
ray
.Out
putshoul
dbe211.

2)Wr
it
eaJav
aprogram tofi
ndsum ofev
enandoddnumber
?
3)Wr
it
eaj
avapr
ogram thatcomput
eanddispl
ayt
hemediaofone-
dimensi
onal
arr
ayel
ement
s?

4)Cr
eat
easampl
ecl
assandCr
eat
eaonedi
mensi
onal
arr
ayoft
hiscl
asst
ype?
12. Basi
cOper
ator
s
Javaprov
idesasetofoper
ator
stomani
pul
atev
ari
abl
es.Wecandi
vi
deal
ltheJav
aoper
ator
sint
o
thefol
l
owinggroups:
12.
1.TheAr
it
hmet
icOper
ator
s
Assumei
ntegerv
ari
abl
eAhol
ds10andv
ari
abl
eBhol
ds20,
then:
Opera Descr
ipt
ion Exampl
e
tor

+ Addi
ti
on-Addsv
aluesonei
thersi
deoft
heoper
ator A+Bwi
l
lgi
ve30

- Subt
ract
ion-Subt
ract
sri
ghthandoper
andf
rom l
efthand A-Bwi
l
lgi
ve-
10
oper
and

* Mult
ipl
icat
ion-Mul
ti
pli
esv
aluesonei
thersi
deoft
he A*Bwi
l
lgi
ve200
oper
ator

/ Di
vi
si
on-Di
vi
desl
efthandoper
andbyr
ighthandoper
and B/Awi
l
lgi
ve2

% Modul
us-Di
vi
deslefthandoper
andbyr
ighthandoper
and B%Awi
l
lgi
ve0
andr
etur
nsr
emainder

++ I
ncr
ement-I
ncr
easet
hev
alueofoper
andby1 B++gi
ves21

-
- Decr
ement-Decr
easet
hev
alueofoper
andby1 B-
-gi
ves19

12.
2.TheRel
ati
onalOper
ator
s
Assumevar
iabl
eAhol
ds10andv
ari
abl
eBholds20,t
hen:
Operat
or Descr
ipt
ion Exampl
e

== Checksi
fthev
aluesoft
wooper
andsar
eequal
ornot
,ify
est
hen (
A==B)i
snot
32
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

condi
ti
onbecomest
rue. t
rue.

!
= Checksift
heval
uesoftwooper
andsar
eequal
ornot
,ifv
aluesar
e (
A! =B)i
s
notequalt
hencondi
ti
onbecomestr
ue. t
rue.

> Checksiftheval
ueofleftoper
andisgreatert
hant
hev
alueofr
ight (
A>B)isnot
operand,i
fyesthencondit
ionbecomestrue. t
rue.

< Checksiftheval
ueofleftoper
andislessthant
hev
alueofr
ight (
A<B)i
str
ue.
operand,i
fyesthencondit
ionbecomestrue.

>= Checksi
ftheval
ueofl
eftoperandi
sgreat
ert
hanorequal
tot
he (
A>=B)i
snot
val
ueofri
ghtoper
and,
ifyesthencondi
ti
onbecomestr
ue. t
rue.

<= Checksift
hev al
ueofl
eftoper
andisl
essthanorequal
tot
hev
alue (
A<=B)i
s
ofri
ghtoperand,
ify
esthencondi
ti
onbecomestrue. t
rue.

12.
3.TheBi
twi
seOper
ator
s
Javadef
inesseveralbi
twi
seoperat
ors,whi
chcanbeappli
edt
ot heintegert
ypes,l
ong,i
nt,
short
,
char
,andbyte.Bi
twiseoper
atorworksonbit
sandperf
ormsbit
-by-
bitoperat
ion.
AssumeifA=60( 00111100);andB=13(00001101)
;nowinbinar
yf ormattheywi
llbeasfol
l
ows:

Oper
ator Descr
ipt
ion Exampl
e

& Binar
yANDOper at
orcopi
esabitt
othe (A&B)wil
lgi
ve12whi
chi
s
resul
tifi
texi
stsi
nbothoper
ands. 00001100

| Bi
naryOROperatorcopi
esabi
tifi
texi
stsi
n (A|B)wil
lgi
ve61whi
chi
s
ei
theroper
and. 00111101

^ Bi
nar
yXOROperat
orcopiesthebi
tifi
tisset (A^B)wil
lgi
ve49whi
chi
s
i
noneoper
andbutnotboth. 00110001

~ Binar
yOnesComplementOperat
ori
sunar
y (~A)wil
lgiv
e-61whichis
andhastheef
fectof'
fl
ippi
ng'
bit
s. 11000011in2'
scomplement
for
m duetoasignedbi
nary
number.

<< BinaryLef
tShif
tOperat
or.Thelef
toper
ands A<<2wi l
lgi
ve240whi
chi
s
valueismovedlef
tbythenumberofbit
s 11110000
specifi
edbytheri
ghtoperand.

>> BinaryRi
ghtShi
ftOper
ator
.Thel
eft A>>2wi
l
lgi
ve15whi
chi
s
operandsval
ueismovedri
ghtbyt
henumber 1111

33
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

ofbi
tsspeci
fi
edbyt
her
ightoper
and.

12.
4.TheLogi
calOper
ator
s
Oper
ator Descr
ipt
ion Exampl
e

&& Call
edLogical
ANDoper
ator
.Ifbot
htheoper
andsar
enon-
zer
othen (
A&&B)is
thecondi
ti
onbecomest
rue. f
alse.

|
| Call
edLogical
OROper at
or.I
fanyoft
het
wooper
andsar
enon-
zer
o (
A||B)i
s
thenthecondi
ti
onbecomest r
ue. t
rue.

! Call
edLogical
NOTOperat
or.Usetorev
ersest
helogicalst
ateofi
ts !
(A&&B)i
s
operand.I
facondi
ti
oni
struethenLogi
calNOToperatorwil
lmake t
rue.
fal
se.

12.
5.TheAssi
gnmentOper
ator
s
Oper
ator Descr
ipt
ion Exampl
e

= Si
mpleassignmentoper
ator
,Assi
gnsv
aluesf
rom r
ight C=A+Bwi l
lassi
gn
si
deoperandstolef
tsi
deoperand val
ueofA+BintoC

+= AddANDassignmentoper
ator,
Itaddsri
ghtoper
andt
othe C+=Ai
sequi
val
entt
o
l
eftoper
andandassi
gntheresul
ttolef
toperand C=C+A

-
= Subt
ractANDassi
gnmentoper
ator
,Itsubt
ract
sri
ght C-
=Aisequi
val
entt
oC
oper
andfrom t
hel
eftoper
andandassignther
esul
ttol
eft =C-A
oper
and

*
= Mult
ipl
yANDassi
gnmentoper
ator
,Itmul
ti
pli
esright C*=Ai
sequi
val
entt
oC
oper
andwit
hthel
eftoper
andandassi
gntheresultt
olef
t =C*A
oper
and

/
= Di
vi
deANDassi gnmentoperat
or,
Itdi
videsleftoperand C/=Ai
sequi
val
entt
oC
wi
thther
ightoperandandassi
gntheresulttoleftoper
and =C/A

%= Modul
usANDassi
gnmentoperator
,Itt
akesmodulus C%=Ai
sequi
val
entt
o
usi
ngt
wooper
andsandassigntheresul
ttol
eftoper
and C=C%A

<<= Lef
tshi
ftANDassi
gnmentoper
ator C<<=2i
ssameasC=
C<<2

>>= Ri
ghtshi
ftANDassi
gnmentoper
ator C>>=2i
ssameasC=
C>>2

&= Bi
twi
seANDassi
gnmentoper
ator C&=2i
ssameasC=C
34
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

&2

^
= bi
twi
seexcl
usi
veORandassi
gnmentoper
ator C^=2i
ssameasC=C
^2

|
= bi
twi
sei
ncl
usi
veORandassi
gnmentoper
ator C|=2i
ssameasC=C|
2

12.
6.Condi
ti
onalOper
ator(
?:)
Conditi
onaloperatori
salsoknownast het er
naryoperat
or.Thisoperat
orconsist
soft
hree
operandsandi susedtoeval
uatebooleanexpr essi
ons.Thegoaloftheoperatori
stodeci
de
whichvalueshouldbeassignedtothev ari
able.Theoperat
oriswrit
tenas:
Vari
ablex=( expressi
on)?val
ueift
rue: v
alueiffal
se.
a=10;
b=(a==1)
?20:30;
System.
out.
pri
ntl
n("Val
ueofbi
s:"
+b)
;

12.
7.i
nst
anceOfOper
ator
Thisoperat
orisusedonlyforobjectreferencevari
ables.Theoperatorcheckswhethert
heobj
ect
i
sofapar ti
cularty
pe(
classtypeori nterf
acetype).instanceOfoperatoriswri
i
tenas:(Obj
ect
ref
erencevari
able)i
nst
anceOf( class/i
nterfacet
ype)
Example:
ClassVehicle{}
publicclassCarext endsVehicl
e{
publi
cstaticvoidmai n(Str
ingar
gs[
]){
Vehicl
ea=newCar ();
booleanresult=ai nstanceofCar;
System.out.pr
int
ln(
resul t
);
}
}

13. Pr
ecedenceofOper
ator
s
Operatorprecedencedet
ermi
nest hegroupingoft ermsi nanexpr essi
on.Thi saff
ectshow an
expressi
onisev al
uat
ed.Cert
ain operat
orshav ehi gherprecedencet han ot
hers;forexample,
themul ti
pli
cati
onoperat
orhashi gherprecedencethantheadditi
onoper at
or:
Category Operator Associ
ativ
it
y

Post
fi
x (
)[].(
dotoper
ator
) Lef
ttor
ight

Unar
y ++--!~ Ri
ghtt
olef
t

35
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

Mul
ti
pli
cat
ive */% Lef
ttor
ight

Addi
ti
ve +- Lef
ttor
ight

Shi
ft >>>>><< Lef
ttor
ight

Rel
ati
onal >>=<<= Lef
ttor
ight

Equal
i
ty ==!
= Lef
ttor
ight

Bi
twi
seAND & Lef
ttor
ight

Bi
twi
seXOR ^ Lef
ttor
ight

Bi
twi
seOR | Lef
ttor
ight

Logi
cal
AND && Lef
ttor
ight

Logi
cal
OR |
| Lef
ttor
ight

Condi
ti
onal ?
: Ri
ghtt
olef
t

Assi
gnment =+=-
=*=/
=%=>>=<<=&=^
=|= Ri
ghtt
olef
t

Comma , Lef
ttor
ight

14. Deci
sion
Javahast hreet ypesofselect
ionstatement s.Thei fstatementei therperfor
ms( sel
ect s)anaction,ifa
condi
ti
oni st rue,orskipsit,i
fthecondi ti
oni sfalse.Thei f…el
sest atementperformsanact ioni fa
condi
ti
oni strueandper for
msadi ff
erentactionifthecondi tionisfalse.Theswitchstat ementperforms
oneofmanydi ff
erentacti
ons,dependingont hev alueofanexpr ession.Theifstatementi sasi ngle-
sel
ecti
onst atementbecauseitselectsorignoresasi ngl
eact ion.Thei f
…elsestat
ementi scalledadoubl e-
sel
ecti
onst atementbecausei tselectsbet weentwodi fferentactions.Theswi t
chst atementi scalleda
multi
ple-
selectionstat
ementbecausei tselectsamongmanydi f
fer
entact i
ons.

14.
1. Thei fStatement
Programsusesel ecti
onst at
ementstochooseamongal
ter
nati
vecoursesofacti
on.Theifstat
ementisa
si
ngle-entr
y/si
ngle-
exitcontr
olst
atement
. Anifstat
ementconsi
stsofaBooleanexpressi
onfoll
owedby
oneormor est
atement s.

Thesy ntaxofani fstat


ementis:
i
f(Boolean_expression)
{
//
Statement swillexecuteift
heBool
eanexpr
essi
onist
rue
}
I
ftheBooleanexpr essionevaluat
estotr
ue,t
henthebl
ockofcodei
nsi
det
hei
fst
atementwi
l
lbeexecut
ed.
36
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

I
fnot
,thef
ir
stsetofcodeaf
tert
heendoft
hei
fst
atement(
aft
ert
hecl
osi
ngcur
lybr
ace)wi
l
lbeexecut
ed.

Exampl e: System.out.print
("Thisisi fstat
ement");
publ i
ccl assTest { }}
publ icst at
icv oidmai n(Str
ingargs[])
{ }
i
ntx=10; Thiswoul dpr oducethef ol l
owingresult
:
i
f(x<20) { Thisisifstatement
14.2. Thei f...
elseStatement
Thei fsingle-selectionstatementper for
msani ndicat
edact iononl ywhent hecondi t
ionis
true;ot herwise,t heactioni sski
pped.Theif…elsedoubl e-
selecti
onst atemental lowsyout o
speci fyanact iont oper f
or m whent heconditionist rueandadi f
ferentact i
onwhent he
condi ti
oni sfalse.Ani fst atementcanbef ol
l
owedbyanopt ionalelsest atement ,which
execut eswhent heBool eanexpr essionisfal
se.Thesy ntaxofani f
...
elseis:
i
f( Boolean_ expr ession)
{/ /Execut
eswhent heBooleanexpr essioni strue
}else{/ /Execut eswhent heBooleanexpr essi
oni sfalse
}
Exampl
e
i
ntx=30;
i
f(x<20) {
Sy stem.out.pr
int("
Thisisifstat
ement")
;
}else{
Sy stem.out.pr
int("
Thisiselsestat
ement")
;
}
14.3. Thei f..
.el
seif..
.el
seStatement:
Ani fstatementcanbef ollowedbyanopt i
onalel
seif.
..
elsest
atement
,whi
chi
sver
yusef
ul
totestv ari
ouscondi t
ionsusingsingl
eif.
..
elsei
fst
atement.

Whenusi
ngi
f,el
sei
f,el
sest
atement
sther
ear
efewpoi
ntst
okeepi
nmi
nd.

 Ani
fcanhav
ezer
ooroneel
se'
sandi
tmustcomeaf
teranyel
sei
f'
s.

 Ani
fcanhav
ezer
otomanyel
sei
f'
sandt
heymustcomebef
oret
heel
se.

 Onceanel
sei
fsucceeds,
noneoft
her
emai
ningel
sei
f'
sorel
se'
swi
l
lbet
est
ed.

Thesyntaxofanif.
..
elsei
s:
i
f(Bool
ean_expr
essi
on1){ publi
cclassTest {
/
/Execut
eswhent
heBool
eanexpr
essi
on1i
str
ue publi
cstati
cv oidmai
n(St
ri
ngar
gs[
]){
}
elsei
f(
Bool
ean_
expr
essi
on2)
{ i
ntx=30;
/
/Execut
eswhent
heBool
eanexpr
essi
on2i
str
ue
i
f(x==10) {
}
elsei
f(
Bool
ean_
expr
essi
on3)
{ System.out.
print
("
Val
ueofXis10"
);
/
/Execut
eswhent
heBool
eanexpr
essi
on3i
str
ue
}el
seif
(x==20) {
}
else{
/
/Execut
eswhent
henoneoft
heabov
econdi
ti
oni
s
-
---
-
t
rue. System.out.
print
("
Val
ueofXis20"
);
} }el
seif
(x==30) {
Exampl
e: System.out.
print
("
Val
ueofXis30"
);
37
I
OT/ Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng
}
else{

Sy
stem.
out
.pr
int
("
Thi
sisel
sest
atement
")
;

14.4. Nest edif


...
elseStatement
I
tisalway slegalt
onesti f
-elsestatementswhichmeansyoucanuseonei
forel
sei
fst
atement
i
nsideanot heri
forelseifstatement .
Thesyntaxf oranestedif.
..elsei
sasf ol
lows:
i
f(Boolean_expr
ession1) {
//Executeswhent heBool eanexpressi
on1ist
rue
i
f(Boolean_expr
ession2) {
//Executeswhent heBool eanexpressi
on2ist
rue
}
}

14.
5.Theswi
tchSt
atement
:
Aswi tchstatemental lowsav ari
abletobet estedforequali
tyagainstalistofvalues.Eachvalue
i
scal l
edacase, andt hev ari
ablebeingswi tchedoni scheckedf oreachcase.
Syntax:
switch(expression){
casev alue:
//Statements
break;//
optional
casev alue:
//Statements
break;//
optional
default:
//Optional
//Statements
}
Thef oll
owingr ulesapplyt oaswi t
chst atement :
 Thev ariableusedi naswi tchstatementcanonl ybeaby te,shor
t, i
nt,
orchar .
 You can hav e any numberofcase st atements wi t
hin a swi t
ch.Each case i s
foll
owedbyt hev al
uet obecompar edtoandacol on.
 Thev al
uef oracasemustbet hesamedat at y
peast hev ari
ableint heswi t
chandi t
mustbeaconst antoral it
eral.
 Whent hev ari
ablebei ngswi t
chedoni sequalt oacase,t hestatement sfoll
owingthat
casewi l
lexecuteunt i
labr eakstatementi sreached.
 Whenabr eakst atementi sr eached,t heswi tchterminates,andt hef low ofcontrol

38
IOT/Comput i
ng–Comput erScience–Regul arPr ogram- 2015E. C ObjectOri
entedPr ogrammi ng
jumpst ot henextl i
nef ol
l
owi ngtheswi t
chst atement .
 Notev erycaseneedst ocont ainabr eak.Ifnobr eakappear s,t
hef l
owofcont rolwillfal
l
throught osubsequentcasesunt il
abr eakisr eached.
 Aswi tchst atementcanhav eanopt ionaldef aul tcase, whichmustappearatt heendof
theswi tch.Thedef aultcasecanbeusedf orper for
mi ngat askwhennoneoft hecases
istrue.Nobr eaki sneededi nthedef aultcase.
Exampl e: break;
publicclassTest { case' D':
publ i
cst at
icvoidmai n(Stri
ngar gs[
]){ Sy stem. out.
pri
ntln("
Youpassed" );
chargrade=ar gs[0].charAt(0); case' F':
switch(grade) Sy stem. out.
pri
ntln("
Bett
ertryagain");
{ break;
case'A'
: def ault:
System. out.
pri
nt l
n("Excellent!
"); Sy stem. out.
pri
ntln("
Inv
ali
dgr ade")
;
break; }
case'B'
: Sy stem. out.
pri
ntln("
Yourgradeis" +grade);
case'C'
: }
System. out.
pri
nt l
n("Well done"); }

15. Repet
it
ionSt
atement
s
Arepet
it
ion(
orl
oopi
ng)st
atementall
owsyoutospeci
fyt
hatapr
ogram shoul
drepeatanact
ion
whil
esomecondi
ti
onremainst
rue.Javahasv
eryfl
exi
blethr
eel
oopingmechanismswhichare
whi
le,
do.
..
whi
le,
and f
orLoops

15.
1.Thewhi
leLoop
Arepet
it
ion(
orl
ooping)st
atemental
l
owsy
out
ospeci
fyt
hatapr
ogr
am shoul
drepeatanact
ion
whil
esomecondi
ti
onr emai
nstr
ue.

Sy
ntax:
whi
l
e(Bool
ean_
expr
essi
on)
{
/
/St
atement
s
}
Whenexecuting,
iftheboolean_
expressionresul
tistr
ue,thentheacti
onsi
nsi
det
hel
oopwi
l
lbe
execut
ed.Thi
swillcont
inueaslongast heexpressi
onresulti
strue.

Keypointofthewhil
eloopi
sthatt
heloopmi
ghtnotev
errun.Whent heexpressi
oni
stest
ed
andtheresul
tisf
alse,
thel
oopbodywi
l
lbeski
ppedandthefi
rstst
atementaft
erthewhi
lel
oop
wil
lbeexecut
ed.

Example: i
ntx=10;
publ
icclassTest{ whil
e(x<15){
publ
icstati
cvoidmai
n(St
ri
ngar
gs[
])
{ Syst
em.out.
pri
nt(
"val
ueofx:
"+x)
;

39
I
OT/ Comput
ing–ComputerSci
ence–Regul
arPr
ogr
am-2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng
x++; val
ueofx:11
System.
out.
pri
nt(
"\n"
); val
ueofx:12
}} val
ueofx:13
} val
ueofx:14
output
val
ueofx:10

15.
2.Thedo.
..
whi
leLoop
Ado. ..whi l
el oopi ssimi l
art oawhi l
el oop, exceptt hatado. .
.whil
eloopi sguar anteedtoexecute
atl eastonet i
me.I nt hewhi l
e,t hepr ogram t est st hel oop-conti
nuation conditi
on att he
begi nni ngoft heloop,bef oreexecut ingt hel oop’sbody ;iftheconditi
oni sf al
se,thebodynev er
execut es.Thedo…whi lest at ementt estst hel oop- continuati
oncondi tionaf terexecutingthe
l
oop’ sbody ;t herefore,t hebodyal way sexecut esatl eastonce.Whenado…whi lestatement
termi nat es,execut ioncont i
nueswi t
ht henextst atementi nsequence.
Synt ax:
do
{
//Stat ement s
}whi le(Bool ean_ expression) ;
Not icet hatt heBool eanex pr essi onappear sattheendoft heloop,sothest atement si
nt heloop
execut eoncebef oret heBool eani stest ed.
IftheBool eanexpr essioni st rue, t
hef lowofcont roljumpsbackupt odo, andt hestat
ement sin
thel oopexecut eagai n.Thi spr ocessr epeat sunt i
ltheBool eanexpressioni sfalse.
Exampl e:
publ iccl assTest { }}
publ icst ati
cv oidmai n(Stri
ngar gs[]){ Out put
i
ntx=10; valueofx: 10
do{ valueofx: 11
Syst em. out.pri
nt("valueofx: "+x) ; valueofx: 12
x++; valueofx: 13
Syst em. out.pri
nt("\n"); valueofx: 14
}whi le(x<15) ;

15.
3.Thef
orLoop
Af orl
oopi sar epeti
ti
oncont
rolstr
ucturet
hatall
owsy out
oeffi
cient
lywr
it
eal
oopthatneedsto
executeaspeci ficnumberofti
mes.Af orl
oopi susef
ulwhenyouknowhowmanyt i
mesat ask
i
st o ber epeated. Thef orr epet
iti
on st
atement,whi
ch specif
iest
hecount
er-
control
l
ed-
repeti
tiondetail
sinasingl
eli
neof
Code.

40
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

Syntax:
for(
initi
ali
zati
on;Bool
ean_expressi
on;updat
e)
{
//St
at ements
}
Exampl e: }
publicclassTest {
publ i
cst at
icvoidmain(St
ringargs[
]){ Output
for(i
ntx=10; x<15;x=x+1) { val
ueofx:
10
System. out.
pri
nt("
val
ueofx: "
+x) ; val
ueofx:
11
System. out.
pri
nt("
\n"
); val
ueofx:
12
} val
ueofx:
13
} val
ueofx:
14

15.
4.Enhancedf
orl
oopi
nJav
a
Theenhancedf orloopwasi ntr
oducedinj
ava5.Thi
sismainlyusedforArr
ays.
Syntax:
for(
decl
arati
on: expression)
{
//St
atements
}
 Declarati
on:Thenewl ydecl
aredbl
ockvari
abl
e,whichisofat ypecompat
iblewi
tht
he
el
ementsoft hear r
ayyouareaccessi
ng.Thevari
ablewillbeavail
abl
ewithint
hef
or
bl
ockandi tsvaluewouldbethesameasthecurr
entarrayel
ement.

 Expr
essi
on:Thi
seval
uatest
othear r
ayyouneedtol
oopt
hrough.Theexpr
essi
oncanbe
anarr
ayvar
iabl
eormethodcal
lthatret
urnsanar
ray
.

Exampl
e }
System.out
.pri
nt("
\n");
publiccl
assTest { Str
ing[]
names
publi
cstaticvoidmai n(
Str
ingargs[
])
{ ={"
James" ,
"Lar
ry",
"Tom","
Lacy
"};
i
nt[]number s={10,20,
30,
40,50}
; for
(Str
ingname: names) {
for(i
ntx: number s){ System.out
.pri
nt(name) ;
System.out.pr
int(
x); System.out
.pri
nt("
,")
;
System.out.pr
int(
",
");

41
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-2015E.C Obj
ectOr
ient
edPr
ogr
ammi
ng
} Output:
} 10,
20,30,
40,
50,
} James,Lar
ry,
Tom,
Lacy,
15.
5.Thebr
eakKey
wor
d
Thebr eakkey wor disusedt ostoptheenti
rel
oop.Thebreakkeywordmustbeusedinsi
deany
l
ooporaswi tchst atement.Thebr eakkey
wordwillst
optheexecuti
onoftheinner
mostloop
andst artexecutingt henextli
neofcodeaf t
ert
heblock.
Exampl e: System.
out.
pri
nt(
"\n"
);
publicclassTest { }
publicstati
cv oidmai n(
Str
ingargs[]
){ }
i
nt[]number s={ 10,20,30,
40,50}
; Output
for
(intx: number s){ 10
i
f(x==30) { 20
break;
}
System. out.
print(x) ;
15.
6.Thecont
inueKey
wor
d
Thecont i
nuekeywor dcanbeusedi nanyoftheloopcont
rolst
ruct
ures.I
tcausest
hel
oopt
o
i
mmedi atel
yjumpt othenextit
erat
ionofthel
oop.
Syntax:
continue;
Exampl e:
publicclassTest {
publicstati
cv oidmai n(St
ringargs[
]){
i
nt[]number s={ 10,20,30,
40,50}
;
for
(intx: number s){
i
f(x==30) {
continue;
}
System. out.
print(x) ;
System. out.
print("\
n");
}}
}
Output
10
20
40
50

42
I
OT/
Comput
ing–Comput
erSci
ence–Regul
arPr
ogr
am-
2015E.
C Obj
ectOr
ient
edPr
ogr
ammi
ng

43
WDU/
Depar
tmentofComput
erSci
enceOOP 2015E.
C

You might also like