Java unit 1
Java unit 1
T-1
J
avaBuz
zwo
rds
Foll
o wingar et
helis
tofb
uzz
wor
ds:
•Simp l
e
•Secure
•Portable
•Obj
ec t
-ori
e nte
d
•Robust
•Mul ti
threaded
•Architect
ur e-
neut
ral
•Int
e rp
reted
•Highp er
for mance
•Distri
buted
•Dynami c
Si
mpl
e:
Javawasde s
igne
dtobeeasyfortheprofe
ssio
nalprogramme rtolearnanduseeff
ect
ivel
y.
Ifwehaves omeprogr
ammi ngexperienc
ethenJavai snohardtobecomemas t
er.
Learni
ngJ avawi l
lb eeve
ne asier,ifweund erstandthec oncept
so fObj
ectorie
ntedpr
ogr
ammi
ng
becaus
eJavainheri
tstheC/C++s yntaxandmanyo ftheobj
ect-
o r
iente
dfeat
uresofC++.
Se
cur
e
Iti
samor
es e
curel
ang
uagec
omp ar
edtoot
herl
ang
uag
e;I
nthi
slang
uag
e,al
lco
dei
sco
ver
edi
nby
tec
ode
aft
erc
omp
ilati
onwhic
hisnotr
eadabl
ebyhuman.
Po
rtab
ili
ty
Ifanylanguagesupp
o r
tspl
atf
ormi nd
ep e
ndentandarchi
tect
uralneut
ralf
eat
urekno
wnasp o
rtab
le.
Thelanguage
slikeC,CPP,
Pascalar
etreate
dasnon-po
rtabl
elanguag
e.I
tisapo
rtab
lel
ang
uag
e.
Ob
jec
t-Or
ient
ed
J
avaisanobj
ect
-or
ient
edpr
ogr
ammingl
anguag
e.Every
thinginJ
avaisanobj
ect
.Obj
ect
-or
iente
dme ans
weorg
aniz
eoursoft
wareasacomb
inat
ionofdi
ffe
rentty
p e
sofobj
ect
sthati
ncorp
orat
esbothdat
aand
be
havio
r.
Ro
bus
t
SimplymeansofRo b
ustares
trong.Itisrob
usto rstrongProgr
ammi ngLang
uagebec
aus
eo fits
capab
ili
tytohandleRun-t
imeEr r
or,auto
mat i
cg arb
ag ecol
lec
tion,t
helacko fpo
int
erconce
pt,
Excep
tio
nHandli
ng.Allt
hes
epoi
ntsmakeItrobustLanguage
.
Mul
tit
hre
ade
d
J
avas
upport
smult
ithr
ead
edp
rog
rammi
ng,whi
chal
lowsy
out
owr
itep
rog
ramst
hatd
omanyt
hing
s
s
imul
tane
ously
.
Amulti
thr
eadedpr
ogr
am co
ntai
nst
woo
rmo
rep
art
sthatc
anr
unc
onc
urr
ent
ly.
Eac
hpar
tofs
uch
p
rog
ramiscal
ledat
hread
.
Ar
chi
tec
tur
e-Ne
utr
al
Archi
tec
turere
pre
sentsp
roc
esso
r.ALang
uageo
rTechnol
ogyissai
dtobeArchi
tec
turalneut
ralwhich
canruno nanyavail
abl
eproc
essor
sintherealworl
dwi t
houtcons
ider
ingthei
rd eve
lop
me ntand
compi
lat
ion.
I
nte
rpr
ete
dandHi
ghPe
rfo
rmanc
e
I
thavehighperformanc eb ec
aus eoffo
llowingreasons;
T hislang uageusesBy tecodewhichi sfaste
rt hano r
d i
narypointercodesoPer
f o
rmanceofthis
languageishi g
h.
Ga r
bagec o
llect
or ,coll
e cttheunus edme mo r
ys paceandi mp rovet hepe
rformanceoft he
applic
ation.
I thasnop oi
nterss othatusingthislanguagewec and e
velopanap pl
icatio
nveryeasi
ly.
I tsupportmul tithreading,bec
auseo fthistimec onsumingp r
o c
esscanb ere
duc e
dtoexec
uting
theprogram.
Di
str
ibut
ed
J
avaisdes
igne
dforthedi
str
ibut
edenvi
ronmento
ftheInt
erne
tb e
c aus
eithand
lesTCP/I
Pprot
oco
ls.
J
avaalsosuppor
tsRemoteMe t
hodInvocat
ion(
RMI).Thisfeatureenab
lesap r
ogram t
oinvoke
met
hodsacr
ossanet
work.
Dy
nami
c
Its upport
sDy namicme moryallocat
iond uetot hismemo rywast
agei sreduceandi mp r
ove
perfor
manc eoftheapp
lic
ation.Theproc
essofal
locat
ingthememorys
pacetotheinputo
ftheprogr
am
atar un-ti
mei sknownasd ynamicme moryall
ocati
on,Topro
grammingtoall
ocatememo r
yspaceby
dynami c
allyweus eanoperatorcal
led'
new''ne
w'o per
atori
sknownasd ynamicme moryall
ocat
ion
operat
or.
OOPCo
nce
pts
:
Thef o
llowingarethebas
ico
opsc
onc
ept
s:
1.Class
2.Obje
ct
3.DataAb str
actio
n.
4.DataEnc aps
ulatio
n.
5.Inheri
tance.
6.Polymorphism.
1
.Cl
ass
Clas
sisabl
ueprintwhichi
scontaini
ngonlyl
isto
fvar
iabl
esandme
tho
dsandnome
mor
yisal
loc
ate
d
fo
rthem.Aclas
si sag
roupofo
bje
c t
sthathascommonpro
pert
ies
.
2
.Ob
jec
t
Anyent
itythathasst
ateandbe
havi
orisknownasanob
jec
t.Fo
rexampleachai
r,pe
n,tab
le,
key
boa
rd,
bi
ke,
etc.Itcanbephy
sic
alorl
ogi
cal
.AnObje
ctcanb
ede
fine
dasaninst
anceo
fac l
ass.
Example
:Adogisanobj
ectb
ecauseithass
tat
esl
ikec
olo
r,name
,br
eed
,et
c.aswe
llasb
ehavi
orsl
ike
waggi
ngthet
ail
,bar
king
,eat
ing,
etc.
3.
Dat
aAb
str
act
ion
Hidingi
nte
rnalde
tailsandshowingfunct
ional
ityi
skno
wnasab s
trac
tio
n.Fo
rexamp
lep
honec
all
,we
don'
tknowtheint
ernalproce
ssi
ng.
InJava,
weuseabstractcl
assandint
erfac
etoachie
veab
str
act
ion.
4.
Dat
aEnc
aps
ulat
ion
Bind i
ng( orwrappi
ng )cod
eandd at
at o
getherint
oas ing
leuni
tareknownase nc
apsulat
ion.For
examp lecapsul
e,i
tiswrappedwit
hdiff
erentmedic
ines
.
Aj avac l
assistheexampleofenc
apsul
ati
o n.J
avabeanist
heful
lye
ncap
sulat
edc
lassbe
c aus
eallthe
datame mb er
sareprivat
ehere.
5
.Inhe
rit
anc
e
Whe
noneobj
ectacq
uire
sal lthepr
oper
tie
sandbehavi
orso
fapare
ntobj
ect
,iti
skno
wnasi
nhe
rit
anc
e.
I
tpr
ovi
desc
odereusab
ili
ty.Itisuse
dtoachi
ever
untimepol
ymor
phis
m.
Be
nef
itso
fInhe
rit
anc
e
Soft
war eReusabilit
y( amo ngp r
oje
cts)
Incre
asedReliabili
ty(r es
ultingfromr euseands haringo
fwell
-te
stedc
ode
)
CodeSharing(withinap roj
ect)
Consis
tencyofInterface(amo ngr el
atedobje
cts)
Soft
war eComp onents
RapidProtot
yping(quic kl
yas semblefromp re-
e xis
tingcompo
nents)
Poly
mo rphis
mandFr ame wo rks(high-le
velreusablecompo
nents)
Info
rmat i
onHi ding
6.
Pol
ymo
rphi
sm
Ifonetaskisper
f o
rme dbyd
iffe
rentways,i
tisknownasp ol
ymo r
phis
m.
Forexamp le
:
Toconvincethecusto
me rdi
ffer
ently,
Todraws omething,f
orexample,shape
,tr
iangl
e,re
ctangl
e,et
c.
InJava,weus emethodover
loadi
ngandme thodove
rridi
ngtoachie
vepol
ymo
rphi
sm.
Pr
oce
dur
alVsOb
jec
tOr
ient
edPr
ogr
ammi
ng
Pr
oce
dur
eOr
ient
edPr
ogr
ammi
ng Ob
jec
tOr
ient
edPr
ogr
ammi
ng
1
.In POP,pro
gram isdi
vid
edi
ntos
mal
l 1
.In OOP, prog
ram i
s d
ivi
ded i
nto p
art
s
p
art
scal
ledf
uncti
ons
. c
all
edo
bje
cts
.
2
.InPOP,Import
anc
eisnotgiventodat
abut 2
.I nOOP,Import
anceisg
ivent
othedat
arat
her
t
ofunc
tionsaswel
lass
e q
ue nceo
facti
ons thanpr
oced
uresorfunc
tio
nsbec
aus
ei two
rks
t
obedo
ne. asare
alworld
.
3. POPf
oll
owsTo
pDo
wnap
pro
ach. 3. OOPf
oll
owsBo
tto
mUpap
pro
ach.
4.POPd
oesno
thaveanyac
ces
ssp
eci
fie
r. 4.OOP has acce
sss pec
ifi
ers name
d Pub
lic
,
Pri
vat
e,Pr
ote
cted,
etc
.
5
.In POP,Datacan move fr
eel
yfr
om 5
.I nOOP,ob
jec
tsc anmo veandcommunicat
e
f
unc
tio
ntof
unc
tio
nint
hesys
tem. wit
heac
hothert
hr o
ughmemberf
unct
ions
.
6. Toaddne
wdat
aandf
unc
tio
ninPOPi
sno
t 6. OOPp r
ovi
desane
asywayt
oad
dne
wdat
aand
soeas
y. func
tio
n.
7
.InPOP,Mostfunct
ionusesGlob
aldat
afor 7
.InOOP, d
at acanno tmoveeasil
yfr
omf unc
tio
n
s
har
ingthatcanb eacce
ssedfree
lyfr
om t
ofunct
ion,i
tc anbekeptpubl
icorp
rivat
esowe
f
unc
tio
ntofuncti
oninthesys
tem. c
ancontr
o ltheacc
es so
fdata.
8. POP do
esnothaveanyprop
erwayf
or 8. OOP pr
ovi
desDat
a Hi
dings
opr
ovi
desmo
re
hid
ingd
atas
oiti
sle
ssse
cur
e. se
cur
ity
.
9. I
nPOP,
Ove
rlo
adi
ngi
sno
tpo
ssi
ble
. 9. InOOP,ove
rlo
adi
ngisposs
ibleint
hefo r
mo f
Func
tio
nOverl
oad
ingandOp
erato
rOver
loading
.
1
0.Exampl
eofPOPar
e:C,VB,FORTRAN, 1
0.ExampleofOOP ar
e:C++,J
AVA,VB.
NET,
Pasc
al. C#.NET.
His
tor
yOfJ ava
J
avawasdevelo
pedb
yJame
sGo
sli
ng,
Pat
ric
kNaug
hto
n,Chr
iswar
th,
EdFr
ankandMi
keShe
rid
onat
SunMi cr
osy
s t
emsint heyear1991.
Thislang
uagewasi niti
all
yc all
e das“OAK”b utwasrenamedas“Java”i
n1 995
.Bet
wee
nt hi
sini
tial
desi
gnofoakandthep ubli
canno uncemento fj
avai
.e.i
nb e
twee
n1991and1995,manymorede
vel
ope
r s
cont
rib
utedtothed
es i
gnande voluti
onofjava.
Thepri
marymoti
vati
onbehi
nddevel
opi
ngj
avawast
heneedf
orcre
ati
ngapl
atf
ormind
epend
ent
Lang
uage(
Archi
tec
tureNe
utr
al)
,thatcanb
euse
dtocre
ateas
oft
warewhi
chcanbee
mb e
ddedin
vari
ouse l
ectro
ni cd
evicessuchasr emo tecontrol
s,microovensetc
.
Theprob l
em wi thC,C++a ndmo sto therlanguagesisthat,theyaredesi
gnedtoc ompileo nspeci
f i
c
tar
getedCPU( i.e.t
he yareplatf
ormd ependent)
,butjavaisp l
atfo
rmI ndep
endentwhi chc anruno na
vari
etyofCPU’ sunderdiff
erentenvironme nts.
Thesecondaryfacto
rt hatmo t
ivatedthed evelo
pme ntofj
avai stodeve
lopt
heap pl
icati
onst hatcanr un
onInternet
.Us ingj
avawec and evelo
pt hea ppl
icati
onswhi c
hc anrunoninter
neti.e.Applet.Sojavais
aplat
formI ndependentLanguageusedf ordevelopi
ngprogr
amswhi c
har ep
latf
ormI ndependentandc an
runoninternet.
Co
mme
nts
The
reare3typ
esofcomment
sinj
ava.
1.
Singl
eLineComment
2.
Mul t
iLineComment
3.Doc
umentati
onComment
1.
JavaSi ngleLineCo mme nt
Thes inglel i
nec omme nti susedtocommentonl
yoneli
ne.
Syntax:
/
/Thisi ss ingleli
nec omme nt
Examp le:
pub li
cc lassCo mme ntExamp le
1
{
pub l
ics t
aticvoidmai n(String[
]arg
s)
{
inti =10;/
/Here,iisavar i
able
Sy s t
em. out.
println(i);
}
}
2.J
avaMul t
iLineCo mme nt
Themul til i
nec omme nti susedtocommentmulti
plel
ine
sofc
ode
.
Syntax:
/
*
This
is
multil ine
comme nt
*/
Examp le:
publicc l
as sCo mme ntExamp l
e2
{
publics taticvoidmai n(String[
]ar g
s)
{
/
*Le t'sd eclareand
pri
ntvar iableinjava.*/
inti=10;
System. o
ut.pr
intln(
i);
}
}
3.JavaDo cume ntat
ionComment
Thed ocume nt
ationcomme nti
suse
dtoc
reat
edo
cume
ntat
ionAPI
.Toc
reat
edo
cume
ntat
ionAPI
,yo
u
needtous ej
avad o
ctool.
Syntax:
/
**
This
is
docume ntat
ion
comme nt
*/
Dat
aty
pes
J
avadefi
neseig
htp r
imi
tivet
ype
sofdata:byt
e,sho
rt,i
nt,l
ong
,char
,fl
oat
,do
ubl
e,andb
ool
ean.
The
p
rimi
tivety
pesareal
soc
ommo nl
yre
fer
redtoassi
mp l
ety
pes.
I
nte
ger
s:Thi
sgr
oupi
ncl
ude
sby
te,
sho
rt,
int
,andl
ong
.
Name Widt
h Range
Long 64 –9,
2 2
3,372,036,85
4,775
,808to9,
223,
372
,036,
854,
775
,807
Int 32 –2,
147,483,
648t o2,1
47,
483,647
Short 16 –32,7
68t o32,767
Byte 8 –128to127
Sy
ntax:byt
eb,c;
i
nti;
s
horts;
l
ongdi
stanc
e;
Examp le:
classLi ght
{
publics tati
cvo idmai n(
Stringargs[
])
{
intlight spe
e d=1 86000;
longd ays=1 000,s e
conds,
distance;
/
/ approxi mat espeedofl
ightinmi l
espe
rse
cond
second s=d ay s*2 4*60*60;
distanc e=li ghtspee
d*s e
cond s;
Sy s
tem. out.pr i
nt("In"+days);
Sy
ste
m.o
ut.
pri
nt(
"day
sli
ghtwi
llt
rave
lab
out"
+di
stanc
e+"mi
les
.”)
;
}}
o
utp
ut:
In1
000d
aysl
ightwi
llt
rave
lab
out1
607
0400000000mi
les
.
Fl
oat
ingp
ointt
ype
s:Fl
oat
ing
-po
intnumb
ers
,al
sokno
wnasr
ealnumb
ers
,ar
eus
edwhe
neval
uat
ing
e
xpr
ess
ionst
hatr
equi
ref
rac
tio
nalp
rec
isi
on.
The
rear
etwoki
nds
:fl
oatandd
oub
le.
Name Widt
hinBi
ts Ap p
roxi
mateRange
Doubl
e 64 4.9e–32
4to1.
8e+308
flo
at 32 1.
4e–045to3.
4e+038
Syntax:f l
oathightemp, lo
wtemp;
Do ubleradius,p
i;
Examp l
e: /
/Comp utetheareaofacir
cle
.
clas
sAr ea{
publics
taticvoidmai n(Stri
ngarg
s[]){
doublepi
=3.1416,r=1 0.8,a;
a=p i*r*r ;
Syst
e m.out.
println("
Are aofci
rcl
eis"+a)
;} }
Charac
ters:I
nJ ava,t
hedatatypeusedt
ost
orec
har
act
ersi
schar
.
Widt
ho fchar:1
6b it
.
Rangeofchar:0to65,5
36.
Ther
earenone gati
vecharsinjava.
Synt
ax:carc=’A’,c1
=’X’,
c2=’Z’;
Bo o
lean:J avahasap r
imi t
ivetype
,c al
ledBo
ole
an,f
orl
ogi
calval
ues
.Itc
anhaveo
nlyo
neo
ftwo
possiblevalues,tr
ueo rfals
e.
Examp le
://Demo nst
rateb o
oleanvalues.
classBo olTes
t{
publicstaticvoidmain(St r
ingargs
[]){
booleanb ;
b=f alse;
System. out.
printl
n("bis"+b );
b=t rue;
System. out.
printl
n("bis"+b );
if
( b
)
Sy st
e m.out.pr
intln(
"Thi si
se xe
cute
d .
");}}
Var
iab
les
Thevar
iab
lei
stheb
asi
cuni
tofs
tor
agei
naJ
avap
rog
ram.Av
ari
abl
eisd
efi
nedb
ythec
omb
inat
iono
f
ani
dent
ifi
er,
aty
pe,
andano
pti
onali
nit
ial
ize
r.
De
clar
ingaVar
iab
le:
I
nJava,
allvar
iab
lesmus
tbed
ecl
are
dbe
for
ethe
ycanb
eus
ed.
Sy
ntax:t
ypei
dent
ifi
er[=val
ue]
[,i
dent
ifi
er[
=val
ue].
..
];
Thet
ypei
soneofJ
ava’
sat
omicty
pes
,orthenameo
fac
las
sori
nte
rfac
e
Theid
ent
ifi
eri
sthenameoft
hevar
iabl
e.
Examp
leso
fvar
iab
led
ecl
arat
ionso
fvar
ioust
ype
s.
i
nta,b,
c; //
d e
clare
sthre
eints
,a,b,andc.
i
ntd=3,e ,
f=5;/ /dec
lare
sthre
emo r
ei nts
,ini
tia
l i
zing/
/dandf
.
b
ytez=22 ; //i
niti
aliz
esz.
d
oublep
i=3. 1
4159;//decl
are
sanapproximatio
no fpi.
c
harx=' x'
;
Co
nst
ant
s
I
nte
gerCo
nst
ant
s:
Aninte
gerco
nstantisaseque
nceofd
igi
tsf
rom 0t
o9wi t
houtdec
imalpoi
ntsorf
ract
ionalpar
torany
ot
hersy
mb o
ls.
Ther
eare3ty
pesofinte
ger
sname l
yde
cimali
nte
ger
,oc
talint
ege
rsandhe
xadeci
malint
eger.
Deci
malInteg
ersconsi
stsofasetofd
igi
ts0to9p r
ece
dedbyanop
tio
nal+o
r-s
ign.Sp
ace
s,c
ommas
andnondi
gitc
haracte
rsarenotp
ermit
tedbe
tweendi
git
s.
Example inty=12
3; /
/her
e123isadecimalinte
gercons
tant
Oc
talI
nte
ger
sco
nst
antc
ons
ist
sofanyc
omb
inat
iono
fdi
git
sfr
om0t
hro
ugh7wi
thaOatt
heb
egi
nni
ng.
Example
intX=O1
23;
//he
re01
23i
sao
ctali
nte
gerc
ons
tant.
Hexadecimalint
ege
rconstantispr
ecede
dbyOXorOx,theymayc
ont
ainal
phab
etsf
romAt
oFo
rat
of.
Thealphabet
sAt oFref
ersto10to15indec
imaldi
git
s.
Examp le
intx=Ox12//her
eOx12isaHe xa-
De c
imalint
ege
rconstant
Re
alCo
nst
ant
s:
RealCo
nst
antsco
nsi
stsofafract
ionalpartinthe
irr
epr
ese
ntat
ion.
The
seq
uant
iti
esar
ere
pre
sent
edb
y
number
scont
aini
ngf
ract
ionalpart
slike26.082
.
Example
fl
oatx=6.3;/
/he
re6.3isado
ublec
ons
tant
.
fl
oaty=6.3f
;//
here6.
3fisafl
oatc
ons
tant
.
Si
ngl
eChar
act
erCo
nst
ant
s:
A Si
ngl
eChar
act
erc
ons
tantr
epr
ese
ntas
ing
lec
har
act
erwhi
chi
senc
los
edi
nap
airo
fquo
tat
ion
s
ymbols
.
charp='
o k'
;//pwillholdthevalue'O'andkwi llbeomitt
ed
chary='
u';/ /
ywillholdthevalue'u'
chark='34';/
/kwillholdthevalue'3,and'4'willbeo
mi t
ted
chare='';//ewillholdthevalue'',ablanks p
ac e
chars='
\45 '
;//
swillholdthevalue'',ab l
anksp ac
e
Allchar
ac t
ercons
tantshaveane quivalentint
egervaluewhic
har
ecal
ledASCI
IVal
ues
.
St
ringCo
nst
ant
s
Ast
ringconst
antisase
tofcharact
erse
ncl
osedi
nd o
ubl
equot
ati
onmarks.Thec
haract
ersinas
tri
ng
c
ons
tantsequencemaybeaalphabet
,number
,spec
ialc
harac
terandb
lankspac
e.Examp l
eofs
tri
ng
c
ons
tantsare
"VI
SHAL"" 1234""
GodBle
ss""!.
..
..
?"
Sc
opeandLi
fet
imeo
fVar
iab
les
Thesc
opeo
favaria
blede
fine
sthes
ecti
ono
ftheco
deinwhichthevari
abl
eisvis
ibl
e.Asag
ene
ralr
ule
,
var
iabl
est
hatar
edefi
nedwithi
nablo
ckar
enotacc
essi
bleo
uts
idethatbl
ock.
The
rear
ethr
eet
ype
sofvar
iab
les
:
1
)ins
tanc
evar
iab
les
2
)cl
assvar
iab
les
3)l
ocalvar
iab
les
1
.Ins
tanc
eVar
iab
les
Avari
ablewhic
hisd
ecl
are
dins
ideac
las
sando
uts
ideal
ltheme
tho
dsandb
loc
ksi
san
i
nst
ancevari
abl
e.
Ge
neralsc
opeofani
nst
ancevar
iab
leist
hroug
houtthec
lasse
xcep
tins
tat
ic
met
hods.Lif
eti
meofanins
tanc
evari
abl
eisunti
ltheob
jec
tst
aysinmemor
y.
2
.Cl
assVar
iab
les
Avari
abl
ewhichi
sdecl
aredi
nsi
deac
las
s,o
uts
ideal
ltheb
loc
ksandi
smar
keds
tat
ici
s
kno
wnasaclas
svari
able
.
Gener
alsc
opeofacl
assvar
iabl
eisthr
oug
houtthecl
assandthel
ife
timeofac
las
svar
iab
lei
s
unti
lthee
ndofthep
rogr
amo rasl
ongast
heclassi
sloade
dinmemo ry.
Theli
fet
imeofavari
ableref
erst
ohowlongt
hevariabl
ee xi
stsbef
oreiti
sd e
stro
yed.Des
tro
ying
var
iab
lesre
fer
stod
eal
loc
ati
ngthememo
ryt
hatwasal
lott
edtothevar
iabl
eswhendec
lari
ngit
.
3.
Loc
alVar
iab
les
Allothervari
abl
eswhichar
eno
ti ns
tanc
eandc
las
svar
iab
lesar
etr
eat
edasl
ocalvar
iab
les
i
nc l
udingthepar
amete
rsinamethod.
Sco
peofalocalvariab
leiswit
hintheb
locki
nwhichi
tisde
clare
dandt
hel
ife
timeo
fal
ocal
var
iab
leisuntilthecont
roll
eave
stheblo
ckinwhi
chiti
sdecl
ared.
Op
erat
ors
1
.Ar
ithme
ticOp
erat
ors
:Thef
oll
owi
ngt
abl
eli
stst
hear
ithme
tico
per
ato
rs:
Ope
rat
or Result
+ Addit
i on
– Subtraction(als
ounar ymi
nus
)
* Multiplicati
on
/ Divis
i on
% Mo d
ul us
++ Incr
eme nt
+= Addit
i onassignment
–= Subtractionassig
nme nt
*= Multiplicati
onassig
nme nt
/
= Divis
i onassignment
%= Mo d
ul usassignment
–– Decr
e me nt
Examp l
e:/
/Demo nst
ratet
hebasi
carit
hme t
ico
per
ato
rs.
clas
sBas i
cMath{
publi
cstat
icvoidmain(St
ringar
gs[
]){
Syst
em.out.p
rintl
n("I
nteg
erArit
hme t
ic"
);
inta=1+1;
intb=a*3;
intc=b/4;
intd=c-a;
inte=-d
;
Syste
m.out
.pr
int
ln(
"a="+a)
;
Syste
m.out
.pr
int
ln(
"b="+b)
;
Syste
m.out
.pr
int
ln(
"c="+c
);
Syste
m.out
.pr
int
ln(
"d="+d
);
Syste
m.out
.pr
int
ln(
"e="+e
);}}
2
.Bi
twi
seOp
erat
ors
:
Op
erat
or Re
sul
t
~ Bit
wiseunaryNOT
& Bit
wiseAND
| Bit
wiseOR
^ Bit
wiseexcl
usiveOR
>> Shif
tri
ght
>>> Shif
tri
ghtzerofill
<< Shif
tle
ft
&= Bit
wiseANDas s ig
nme nt
|= Bit
wiseORas si
g nme nt
^= Bit
wiseexcl
usiveORas si
gnme
nt
>>= Shif
tri
ghtassignme nt
>>>= Shif
tri
ghtzerofillassi
gnment
<<= Shif
tle
ftassi
gnme nt
3.
Rel
ati
onalOp
erat
ors
Operat
or Res
ult
== Eq
ualto
!= No
tequalto
> Gr
eatert
han
< Le
ssthan
>= Gr
eatert
hanoreq
ualto
<= Le
ssthanoreq
ualto
4.
Boo
leanLo
gic
alOp
erat
ors
Oper
ato
r Res
ult
& Lo
gicalAND
| Lo
gicalOR
^ LogicalXOR( exc
lusi
veOR)
|| Short-circ
uitOR
&& Short-circ
uitAND
! LogicalunaryNOT
&= ANDas sig
nme nt
|= ORas signment
^= XORa ss
ignment
== Equalto
!= Notequalto
?: Ternaryif-t
hen-el
se
Ar
ray
s:
AnAr
rayi
sthec
oll
ect
iono
fel
eme
ntso
fsi
mil
ard
atat
ypewhi
char
ere
fer
redb
yac
ommo
nname
.
Arraysofanyt
ypecanb
ecre
ate
dandmayhaveo
neo
rmo
red
ime
nsi
ons
.Ane
leme
nti
nanar
rayc
anb
e
ac
ce s
sedbyusi
ngit
sind
ex.
1
.OneDi
mens
ionalAr
ray
:
Ao
ned
ime
nsi
onalar
rayi
ses
sent
ial
lyal
isto
fli
ket
ype
dvar
iab
les
.
Sy
ntax:d
atat
ypear
ray
name
[];
Her
e,typ
edeclarest
heb as
etypeoft
hearr
ay.Theb
asety
pedete
rminest
hedat
atypeo
feac
hel
eme
nt
t
hatcompri
sesthearray
.
Arr
ay_namere f
erst
onameo farr
ay,
andal
lele
ment
sarere
fer
redbyt
hisco
mmo nname
.
Eg
:intmont
hdays[
];
Alt
houghintheabovee xamp
lei
tde
claresanarr
ayvari
ablewit
hnamemo nt
hdays,b
utnoar ray
ac
tuall
yexi
sts
.Infact
,theval
ueo
fmonth_day
siss
ett
onull
,whic
hr e
pre
sent
sanarraywithnoval
ue.
Toli
nkmo nt
hdayswithanac
tual
,p hy
sicalarr
ayo fi
ntege
rs,y
oumustal
loc
ateo
neus
ing“
new”and
ass
igni
ttomonthday
s.ne
wisaspe
cialope
r at
orthatal
loc
atesmemo
ry.
Sy
ntax:ar
rayname=newdat
aty
pe(
siz
e)
Monthd
ays=newint[
12];
No
wmo
nthd
ayswi
llr
efe
rtoanar
rayo
f12i
nte
ger
s.
Examp l
eProgr
am:
clas
sAr ray
{
publi
cstati
cvoi
dmain(
Str
ingar
gs[
]){
intmonth_day
s[];
mont
h_day
s=ne wi nt[
12];
mont
h_day
s[0]=31 ;
mont
h_day
s[1]=2 8;
mont
h_day
s[2]=31 ;
mont
h_day
s[3]=30;
mont
h_day
s[4]=31 ;
mont
h_day
s[5]=30;
mont
h_day
s[6]=31 ;
mont
h_day
s[7]=31 ;
mont
h_day
s[8]=30;
mont
h_day
s[9]=31 ;
mont
h_day
s[10]=30;
mont
h_day
s[11]=31;
Sy
ste
m.o
ut.print
ln("
Ap r
ilhas"+mo
nth_d
ays
[3]+"d
ays
.")
;}}
Arr
ayscanbeini
tiali
zedatthet
imeo
fde
clar
ati
on.
AnArrayIni
tial
izeri
sal i
stofc
omma-s
epar
ate
dexpr
ess
ionss
urr
ound
edb
ycur
lyb
rac
es.
Examp l
e:
clas
sAut o
Ar r
ay{
publi
cstat
icvoidmai n(
Stringarg
s[]
){
intmonth_days[]={31,28,31,
30,31
,30,31
,31
,30,
31,
30,31};
Syst
em.out.p
rintln(
"Aprilhas"+mo nt
h_days
[3]+"day
s.")
;}}
2
.Mul
tid
ime
nsi
onalAr
ray
s
I
nJava,
mul
tid
ime
nsi
onalar
ray
sar
eac
tual
lyar
ray
sofar
ray
s.
Syntax:twoD[]
[]=ne
wi nt[4]
[5]
;
Thiscre
atesa4by5arrayandass
ignst
otwo
Dar
ray
.
Examp le
:
classTwo DArray{
publicst
aticvoidmai n(St
ringar
gs[]
){
inttwoD[] [
]=newi nt[4][
5];
inti,j
,k=0;
for(
i=0;i<4;i++)
for(
j=0;j
<5 ;j
++){
twoD[ i
][j
]=k;
k++;
}
for(
i=0;i<4;i++){
for(
j=0;j
<5 ;j
++)
System.out.pr
int(
two D[i]
[j]+"")
;
System.out.pr
intl
n();}
}
}
Co
ntr
olSt
ate
ment
s:
Co
ntrolstate
me nt
scanb eputi
ntot
hef
oll
owi
ngc
ate
gor
ies
:
1.
Selecti
onState
me nts
2.Ite
r a
tionStat
eme nt
s
3.JumpSt ate
me nt
s
1
.Se
lec
tio
nst
ate
ment
s:J
avas
upp
ort
stwos
ele
cti
ons
tat
eme
nts
:ifands
wit
ch.
i
f:Thei
fst
ate
menti
sco
ndi
tio
nalb
ranc
hst
ate
ment
.Itc
anb
eus
edt
oro
utep
rog
ram e
xec
uti
on
t
hro
ught
wod
iff
ere
ntp
aths
.
Sy
ntax:
i
f(co
ndit
ion)
state
ment1;
e
lse
state
ment2;
Here
,eachstate
me ntmaybeasi
nglestat
emento
racompo
undstat
ementenc
lose
dinc
url
ybr
ace
s(t
hat
i
s,ablock)
.Thecondit
ioni
sanyexp
r e
ssio
nthatr
etur
nsabo
ole
anvalue
.Theels
e
cl
auseisopt
ional.
Theifwo rkslikethis
:Ifthecond
itioni
st r
ue,the
nstatement1i
sexecut
ed.Ot
her
wis
e,s
tat
eme
nt2(
ifi
t
exi
sts)isexecuted.I
nnoc asewil
lb o
thstate
me nt
sbeexecut
ed.
Examp le
:
inta,b;
if(
a<b )
a=0;
else
b=0;
Here,ifaislessthanb,thenaissettoz
ero.Other
wise,bisse
ttozer
o.
Ne
ste
dif
s:Ane
ste
difi
sani
fst
ate
mentt
hati
sthet
arg
eto
fano
the
rifo
rel
se.Ne
ste
dif
sar
eve
ry
c
ommo ni
nprog
ramming
.Whe ny
oune
stifsanels
es t
ate
mentalwaysre
fer
stothenear
esti
fst
ate
ment
t
hati
swithi
nthesamebl
ockast
heel
seandthatisnota
lre
adyass
ociat
edwit
hane l
se.
Eg
:i f
(i==10){
i
f(j<20)a=b;
i
f(k>100)c=d;
el
sea=c
;
}
e
lse
a=d;
if
-el
se-
ifl
adder
:
Synt
ax:if
(co
nditi
on)
st
atement;
el
seif(
condit
ion)
st
atement;
el
seif(
condit
ion)
st
atement;
…..
e
lse
s
tate
me nt;
Thei
fstat
ement
sareexecut
edf
romthet
opdown.Assoo
nasoneofthec
o nd
iti
onsco
ntr
olli
ngt
hei
fis
tr
ue,
thest
ate
mentass
o c
iate
dwitht
hati
fise
xecut
ed,
andther
esto
ftheladde
risbyp
asse
d.
Swi
tch
Theswitc
hs tateme ntisamul tiwaybranchstatement.
Synt
ax:switch( expressi
on){
caseval ue1:
//
s tatementsequenc e
break;
casevalue2 :
/
/stateme ntseq
ue nce
br
e ak;
….
caseval ueN:
Theval
ueo ft hee xpre
ssioni scomparedwi t
he acho fthelit
eralvalue
sint hecasestat
eme nts.Ifa
matchisfound ,thec o
deseque ncefo
llowingthatcases t
atementisexecut
ed.Ifnoneo ft
heco nstant
s
matche
st heval ueo fthee xpressi
on,thenthed efaultstat
eme ntisexec
uted.Howe ver
,thed e
faul
t
st
atementisop ti
onal.Ifnocas ematchesandnod ef
aultisprese
nt ,
thennofur
theracti
onistake n.
Examp
le:
c
lassSampleSwitc
h
{
p
ublicst
ati
cvoidmain(
Str
ingar
gs[
]){
f
or(
inti=0;
i<6;i++)
s
witch(i
)
{
case0:
Syste
m. o
ut.
pri
ntl
n("
iisz
ero.
");
bre
ak;
case1:
Syste
m. o
ut.
pri
ntl
n("
iiso
ne.")
;
bre
ak;
case2:
Syste
m. o
ut.
pri
ntl
n("
iist
wo .
");
def
ault:
Syste
m. o
ut.
pri
ntl
n("
iisg
reate
rthan3.
");
}
}}
2
.It
erat
ionSt
ate
ment
s:J
ava’
sit
erat
ions
tat
eme
ntsar
efo
r,whi
le,
andd
o-whi
le.
Whi
le:
Itrepeatsas t
ateme ntorblo
ckwhi l
eitscont
rolli
nge xpr
essi
onistr
ue.
Syntax:whi le(c
onditi
on)
{
/
/bodyofloop
}
Thec o
nd it
ioncanb eanyBo o
leanexpre
ssio
n.Theb odyofthel
oopwillbee
xe c
utedaslo
ng
asthec ondi
tionalexpress
ionistrue
.Whe ncondit
ionb e
comesfal
se,co
ntrolpas
s e
stothe
nextlineofcodeimme d
iatel
yfoll
owingthelo
o p
.
Eg :
classWhi l
e
{
p ubli
cstati
cvoi
dmain(St
ringar
gs[
])
{
intn=1 0;
whi le
(n>0){
Sy s
tem.out.
pri
ntl
n("
tic
k"+n) ;
n- -
;
}}
}
d
o-whi
le:
Thedo-
whil
eloopalwaysexe
cut
esit
sbodyatle
astonc
e,bec
aus eit
sc o
ndi
tio
nalexp
res
sionisatt
he
bot
tomoft
helo
op.Ifthi
sexpr
ess
ioni
str
ue,thel
oopwil
lre
peat.Other
wise,
thelo
opte
rminate
s.
Sy
ntax:
d
o
{
//bod
yofl
oop
}whil
e(co
ndi
tio
n);
Eg:
clas
sDoWhi l
e{
publi
cstat
icvoi
dmai n(St
ringar
gs[
]){
intn=10;
do{
Syst
em.out.
pri
ntln(
"tic
k"+n) ;
n--;
}while(
n>0) ;
}}
f
or:
Syntax:for
(ini
tial
izati
on;co
ndit
ion;i
nc/
dec
)
{
/
/body
}
Ifonlyones
tate
me ntisbei
ngrep
eated
,the
reisnone
edf
ort
hec
url
ybr
ace
s.
Thef orl oo
po per
atesasf ollo
ws.Whe nt heloopf i
rststarts,t
hei nitiali
zatio
np o
r t
iono fthel oopis
executed.I tisimp ort
antt ound erstandt hatt heiniti
alizat
ione xp res
sioni sonlyexe cute
do nce.
Next,c
o ndit
ionisevaluated.Ifthisc o
nd i
tionistrue,thenthebodyo ftheloopisexecuted
.I fitisfalse
,
theloopt erminates
.Ne xt,theit
e r
at i
onp orti
ono ftheloopisexecut ed.Thisisusuallyane xp
r es
sion
thatinc rementsord ec
re mentsthel oopcontrolvariabl
e.Thel oopt heni t
erate
s,firs
te valuatingthe
condit
i onalexpre
ssion,thenexecutingtheb odyoftheloop,andthene xe c
utingthei
teratione xp
r es
sion
withe achp ass
.Thisp r
oc es
srepeatsuntilthec o
ntroll
ingexpres
sioni sfalse.
Eg:
classForTi
c k{
publics
taticvoidmain(St
ringarg
s[]
){
intn;
for(
n=10;n>0;n- -
)
System.out
.pri
nt l
n("
tic
k"+n) ;
}}
Us i
ngcommai nforl
oop:
classComma{
publics
taticvoidmain(St
ringarg
s[]
){
inta,b;
for(
a=1,b=4;a<b ;
a++,b--
)
{
System.out
.pri
nt l
n("
a="+a );
System.out
.pri
nt l
n("
b="+b )
;
}}
}
3.
JumpSt
ate
ment
s:
b
reak:Whenabreakst
ate
menti
senc
ount
ere
dins
ideal
oop
,thel
oopi
ste
rmi
nat
edandp
rog
ram
c
ont
rolr
esume
satt
hene
xts
tat
eme
ntf
oll
owi
ngt
hel
oop
.
Examp
le:
c
lassBre
akState
me nt
{
pub
licst
ati
cvoidmai n( St
ringarg
s[])
{
inti;
i=1;
while(tr
ue )
{
if(
i>1 0)
break;
System. o
ut.pr
int
(i+""
);
i++;
}
}
}
Co
nti
nue
:
Thiscommandski
psthewho l
ebodyofthelo
opandexe
cut
esthel
oopwit
hthenexti
ter
atio
n.Onfi
ndi
ng
conti
nueco
mmand ,co
ntrolle
avestheresto
fthest
ateme
ntsinthel
oopandg
oesbacktothet
opoft
he
lo
o pt
oexe
cutei
twiththenextit
erat
ion(val
ue)
.
Example
:
/
*Pr i
ntNumb erfrom1t o10Except5*/
cl
assNumberExc ep
t
{
publ
icstaticvoidmai n(
Stri
ngargs
[])
{
inti;
for(i=1;
i<=10;i
++)
{
if
(i==5)conti
nue;
System.out.
pri
nt(i+""
);
}
}
}
Ty
pec
onve
rsi
onandCas
ting
:
TypeCastingisrequi
redwheneve
rweas
sig
nings
mall
erdatat
ypeval
ueint
obi
gge
rdatat
ypevar
iab
leor
assig
ningb i
ggerdatatyp
evaluetot
hesmal
lerd
atat
ypevari
abl
e.Ther
earet
wot y
peso
fTypeCasti
ng
theyare;
1.I
mp l
icitTypeCasti
ng
2.Expl
icitTypeCasti
ng
1
.Imp
lic
itTy
peCas
ting
Thi
sTypeCas t
ingisr eq
uir
edwhe neverweassi
gni
ngs
mal
lerd
atat
ypeval
uei
ntob
igg
erd
atat
ype
var
iab
le.Iti
salsoknownaswideningorupc
asti
ng
Not
e:I
nt hi
styp
ec as
tingnol
oos
eo finfo
rmati
on.
2
.Exp
lic
itTy
peCas
ting
Programme risrespons
ibletop
erformt histy
pec as t
ing.
ThisTy p
eCas ti
ngi srequir
edwhe neverweas s
i gningbig
gerdatatyp
evaluet
othes
mal
lerd
atat
ype
vari
ab l
e.Itisalsoknownasnar r
owi ngordownc asting
Syntax:(target
-type
)value
Here,targ
et-ty
pes p
ecif
iesthede
siredtypetoconve rtthesp
eci
fiedval
ueto
.
Eg:inta;
byt
eb ;
b=(byt
e)a;
Examp le:
classConver si
on{
publicstati
cvo idmain(
Str
ingarg
s[]
){
byteb;
inti=2 57;
doubled=32 3.
142;
System.out.printl
n("
\nConver
siono
finttoby
te.
");
b=( byte
)i;
System.out.printl
n("
iandb"+i+""+b );
System.out.printl
n("
\nConver
siono
fdoublet
oint.
");
i=( i
nt)d ;
System.out.printl
n("
dandi"+d+""+i );
System.out.printl
n("
\nConver
siono
fdoublet
obyte
.")
;
b=( byte
)d ;
System.out.printl
n("
dandb"+d+""+b );
}}
Co
nce
ptso
fcl
ass
es,
obj
ect
s
Hereisac lasscal
ledBoxthatdef
ine
sthreei
nstanc
evariab
les
:wi
dth,hei
ght
,anddept
h.Cur
rent
ly,
Boxdoesnotcont
ainanyme t
hods
.
cl
assBo x
{
do
ublewidth;
do
ubleheight;
do
ubledepth;
}
Decl
aringobje
ct:
Toactual
lyc
reat
eaBo xo
bje
ct,
youwillus
eastat
eme
ntliket
hefol
lowi
ng:
Bo
xmy b
ox;
//d
ec l
areref
erenc
etoo
bje
ct
mybo
x=newBo x()
;//
alloc
ateaBoxobj
ect
St
ate
ment Eff
ect
Boxmyb
ox; NULL NUL
Mybo
x
widt
h
My
box=ne
wBo
x()
;
hei
ght
de
pth
my
box
Bo
xo b
jec
t
Boxmy b
ox=newBox()
;//c
reat
eaBoxobj
ectcal
ledmy
box
thene
wo pe
rat
ord
ynamical
lyal
loc
ate
sme moryfo
ranobj
ect
.
Examp le
:
classBox
{
doublewidth;
doubleheig
ht;
doubledept
h;
}
classBoxDe mo
{
pub l
icst
aticvoidmai n(St
ringargs
[])
{
Bo xmybox=ne wBo x( )
;
doublevol;
my box.
wi d
th=1 0;
my box.
height=2 0;
my box.
depth=1 5;
vol=my box.width*my bo
x.heig
ht*my bo
x.d
ept
h;
System.out.p
rintln(
"Volumei s"+vol)
;
}
}
Me
tho
ds:cl
ass
esus
ual
lyc
ons
isto
ftwot
hing
s:i
nst
anc
evar
iab
lesandme
tho
ds.
Sy
ntax:r
etur
nty
peme
tho
dname
(par
ame
ter
-li
st)
{
/
/bo
dyo
fme
tho
d
}
Her
e,t
ypesp e
cif
iesthety
peofd
ataret
urnedb
ytheme
thod
.Thiscanb
eanyval
idty
pe,
i
ncl
udingclasst
ypesthatyo
ucreat
e.I
fthemetho
ddo
esnotr
etur
navalue
,it
sret
urntyp
e
mustb
evo i
d .
Met
hodsthathavear
etur
ntyp
eothe
rthanvo
idr
etur
naval
uet
othec
all
ingr
out
ineus
ing
t
hefol
lowingfo
rm:retur
nvalue
;
Examp l
e :
//
Ad dingaMe thodt otheBo xClass
ClassBo x
{
doublewi dth, height,dep
th;
voidvo l
ume (){
System. out.print("Volumei s");
System. out.println(width*he ig
ht*d e
pth)
;
}}
classBo xDe mo 3{
pub l
icstaticvo idmai n(Stringargs
[]){
Bo xmy box1=ne wBo x()
;
Bo xmy box2=ne wBo x();
my box1.wid t
h=1 0;
my box1.height=2 0;
my box1.depth=1 5;
my box2.wid th=3;
my box2.height=6;
my box2.depth=9;
my box1.volume ();
my box2.volume (
);
}}
Examp
le:
Pro
gramf
orRe
tur
ningaVal
ueandad
dingame
tho
dthatt
ake
spar
ame
ter
s
classBox
{
doublewid th,he i
ght,de
pth;
doublevolume (
){
returnwid th*he i
ght*d ept
h;
}
voidset
Di m( d o
ub l
ew, doubleh,
doubl
ed){
wi dt
h=w;
height=h;
depth=d ;
}
}
classBoxDe mo 5{
pub l
icst
at icvo i
dmai n(Stri
ngargs[
]){
Bo xmybox1=ne wBox();
Bo xmybox2=ne wBo x()
;
doublevol;
my box1
.setDi m( 1
0,20,15);
my box2
.set Dim( 3,6,9);
vol=my bo x1.volume();
System.out .
pr i
ntln("
Vo l
umei s"+vol);
vol=my bo x2.volume ()
;
System.out .
pr i
ntln("
Vo l
umei s"+vol);
}}
Me
tho
dOve
rlo
adi
ng:
InJavaitispos
si b
letodef
inetwoormo r
eme t
hodswi t
hinthesamecl
assthatsharet
hes
amename,
aslongasthei
rp aramet
erdecl
arat
ionsared
iff
erent.Whenthisist
hecas
e,themethod
sar
esai
dtob
e
ove
rloade
d,andthep r
oce
ssisref
err
edtoasmethodoverl
oadi
ng.
Me
tho
dove
rlo
adi
ngi
soneo
ftheway
sthatJ
avas
upp
ort
spo
lymo
rphi
sm.
Whenanover
loadedmethodi
si nvoked,Javaus e
st hetyp
eand /
o rnumb e
ro fargume nt
sasit
sguideto
de
termi
newhichve r
sionoftheo verlo
adedme thodt oactuall
yc al
l.Thus ,ove
rloadedmet
hodsmus t
di
ffe
rinthetypeand/
ornumb ero fthei
rp arame t
ers.Whi l
eo verl
oadedme thodsmayhaved i
ffe
rent
r
eturnt
ype
s,t
her e
turntyp
eal
o neisinsuffic
ienttodist
inguishtwove r
sionsofame thod.
Example
:
cl
assOverl
oadDe
mo
{
vo
idte
st(){
Sy st
em. out.pri
ntln("
Nop arame t
ers"
);
}
voidtest(inta){
System.o ut.pri
ntln(
"a:"+a) ;
}
voidtest(inta,intb){
System.o ut.pri
ntln(
"aandb :"+a+""+b )
;
}
doubletest (
d o
ublea){
System.o ut.pri
ntln(
"doub l
ea: "+a) ;
returna*a;
}}
classOve rload{
pub l
icstat i
cvo i
dmai n(Stringar gs
[]){
Ove r
loadDe moo b=ne wOve rloadDemo();
doubleres ult;
ob.test
();
ob.test
(10);
ob.test
(10, 20);
result=o b .
test(
123.
2 5
);
System.o ut.pri
ntln(
"Re sultofo b
.test
(12
3.25)
:"+r
esul
t);
}
}
Co
nst
ruc
tor
s
construct
orinJavaisaspecialmemb e
rme thodwhic
hwi llb
ec al
ledi
mp li
cit
ly(
automat
icall
y)by
theJ VM wheneverano b
jectiscre
atedforplaci
nguserorpro
gramme rdefi
nedval
uesinplaceof
defaultvalue
s.Inas inglewo rdco
nstruct
orisas peci
alme mberme t
hodwhichwi l
lbec all
ed
automaticall
ywheneverobj
ectiscr
eated
.
Thepurpo
seofconst
ructoristoini
tiali
zeano bj
ectcal
ledo
bje
ctiniti
ali
zat
ion.Cons
truct
orsare
mainl
ycreat
eforini
tial
izi
ngtheobj
ect.Ini
tial
izat
ionisapr
ocessofassi
gni
nguserde
fine
dv al
ues
att
hetimeofal
locat
ionofme mor
yspace.
Sy
ntax
cl
assName
()
{
..
..
..
.
..
..
..
.
}
Di
ffe
renc
ebe
twe
enMe
tho
dandCo
nst
ruc
tor
Me
tho
d Co
nst
ruc
tor
1 Me
tho
dcanb
eanyus
erd
efi
nedname Co
nst
ruc
tormus
tbec
las
sna
me
2 Me
tho
dsho
uldhaver
etur
nty
pe I
tsho
uldno
thaveanyr
etur
nty
pe(
eve
nvo
id)
Methodshoul
dbecall
edexpl
ici
tly
I
twillb
ecal
ledaut
omat
ical
lywhe
neve
rob
jec
tis
3 e
itherwithobj
ectr
efe
renceo
rclass
c
reat
ed
r
eferenc
e
Methodisno
tpr
ovi
dedb
yco
mpi
leri
n Thej
avacompi
lerpr
ovid
esade
faul
tco
nst
ruc
tor
4
anycase
. ifwedono
thaveanyco
nstr
uct
or.
Ty
peso
fco
nst
ruc
tor
s
Ba
sedo
ncr
eat
ingo
bje
ctsi
nJavac
ons
truc
torar
ecl
ass
ifi
edi
ntwot
ype
s.The
yar
e
1
.De
faul
tornoar
gume
ntCo
nst
ruc
tor
2
.Par
ame
ter
ize
dco
nst
ruc
tor
.
1
.De
faul
tCo
nst
ruc
tor
Ac
ons
truc
tori
ssai
dtob
ede
faul
tco
nst
ruc
tori
fando
nlyi
fitne
vert
akeanyp
arame
ter
s.
I
fanyc lassd o
esno tco
ntai
natle
astoneus
erde
fine
dconst
ruct
orthant
hesys
tem wil
l
c
reatead e
faultconst
ruct
oratt
hetimeofcompi
lat
ionitisknownassys
temdefi
ned
d
efaultc
o nstr
ucto
r.
No t
e:Sy
s t
emd efi
neddef
aultconst
r uc
tori
screate
db yjavacompil
erandd
oesnothaveany
statementinthebodyp
art.Thisconst
ruct
orwillbeexecute
dever
ytimewhene
veranobj
ect
iscreat
edifthatcl
assdoe
sno tco
ntainanyus
erd e
finedconst
ruc
tor.
Examp l
e:
classTest
{
inta,b;
Test()
{
a=10;
b=20;
System.out
.pr
int
ln(
"Val
ueo
fa:
"+a)
;
System.out.
pri
ntl
n("
Valueofb
:"+b
);
}
};
classTestDemo
{
publicstat
icvo
idmain(
Stri
ng[]ar
gs)
{
Testt1=newTest(
);
}
};
2
.Par
ame
ter
ize
dco
nst
ruc
tor
I
fanyconst
ruc
torco
ntai
nl i
stofvari
ableinitssig
nat
ureisknownaspare
met
riz
ed
c
ons
truc
tor
.Aparamet
eri
zedco
nst
ruct
orisonewhic
htake
ssomepar
amete
rs.
Examp le
:
classTest
{
inta,b;
Test(i
ntn1,intn2)
{
a=n1;
b=n2 ;
System.out.
p r
intl
n("Val
ueofa="+a)
;
System.out.
p r
intl
n("Val
ueofb="+b)
;
}
};
classTestDemo 1
{
publicstat
icvoidmain(St
ringk[
])
{
Testt1=newTe st
(10,
20);
}
};
Co
nst
ruc
torOve
rlo
adi
ng:
Inad
diti
ontoove
rlo
adingnor
malme t
hod
s,y
oucanals
ooverl
oadconst
ruc
tormet
hods.
Wecand ef
inemulti
plecons
truc
tor
swithsameclassnameb utthe
yshoul
ddiff
erbye
ithe
rty
peo
r
numberofpar
ameter
s.
Examp le:
classBo x
{
doublewi dt
h,he ight,depth;
Bo x(
d oubl
ew, doub leh,d o
ub led)
{
wid t
h=w;
height=h;
depth=d ;
}
Bo x(
)
{
wid t
h=he ight=d epth=0;
}
Bo x(
d oubl
elen)
{
wid t
h=he ight=d epth=l e
n;
}
doublevo l
ume ()
{
returnwidth*he i
ght*d epth;
}
}
publicc l
assTest
{
pub l
ics t
ati
cvo idmai n( Stringargs[
])
{
Boxmy bo
x1=ne wBo x(10,20,15)
;
Boxmy bo
x2=ne wBo x();
Boxmy bo
x3=ne wBo x(7 );
doublevol;
vol=my bo
x1.vo l
ume (
);
System.out.println("Vo lumeo fmybox1i
s"+vol)
;
vol=my bo
x2.vo lume ();
System.out.println("Vo lumeo fmybox2i
s"+vol);
vol=my bo
x3.vo lume ();
System.out.println("Vo lumeo fmybox3is"+vo
l);
}
}
“
thi
s”ke
ywo
rd
So
meti
mesame
tho
dwi
llne
edt
ore
fert
otheo
bje
ctt
hati
nvo
kedi
t.Toal
lowt
his
,Javad
efi
nest
he“
thi
s”
ke
ywo
rd.
Thati
s,t
hisi
sal
way
sar
efe
renc
etot
heo
bje
cto
nwhi
cht
heme
tho
dwasi
nvo
ked
.
Ke
ywo
rd“
thi
s”i
sus
edt
oso
lvet
hep
rob
lemo
fIns
tanc
eva
riab
lehi
ding
.
Gar
bag
eCo
lle
cti
on:
Obj
ectsi
njavaared
ynamic
allyal
loc
ate
db yusi
ngt
hene
wop
erat
or,
butho
wsuc
hob
jec
tsar
ede
str
oye
d
andthei
rmemo r
yrel
eas
edfo
rlate
rreal
loc
atio
n.
I
ns o
mel anguag
e s
,suchasC++,d ynamicall
yal l
ocat
edobj
ectsmustb emanual
lydelet
edbyuseofa
d
ele
teoperat
or.Javatakesadiff
ere
ntapproach;ithandl
esdeall
ocat
ionaut
omatical
ly.Thete
chni
que
t
hatacc
omp li
shesthisiscal
ledg
arbagec
olle
ction.
Itwor
ksl
iket
his
:whe nnoref
ere
ncestoanobj
ecte
xis
t,t
hato
bje
cti
sas
sume
dtob
enol
ong
erne
ede
d,
andt
hememor
yoccup
iedbyt
heobj
ectcanber
ecl
aimed.
Thefinali
z e
()Me t
ho d:
Sometime sano bj
ectwi llnee
dtoperfo
rms omeac t
ionwhenitisdest
royed.Fore
xample,
ifano b
jecti
s
hold
ings omeno n-Javar es
ourcesuchasaf il
ehand l
e,theny o
umi g
htwantt omakes uret hese
res
ourcesar efr
eedb efo
reano bj
ectisde
stro
yed.Tohandl
esuchs it
uatio
ns,Javapr
ovi
desame chanism
cal
ledfinali
z at
ion.Byus ingfi
naliz
atio
n,youcandefi
nespe
c i
ficact
ionsthatwil
locc
urwhe nano bj
ect
isj
ustab o
utt obereclaimedbythegarbag
ecoll
ecto
r.
Insidethefinal
ize()me t
hod,youwil
lspecif
ythoseac
tionsthatmus tbeper
for
me dbe
foreano
bje
cti
s
destr
o y
ed.
Syntax:protect
edvoidfi
nali
ze()
{
//f
inali
zati
onc o
dehere
}
He r
e,theke ywordprot
ect
edisas p
ecif
ierthatpre
vent
sac ce
sstofinali
ze()bycod
edefi
nedout
sid
eit
s
class.
Itisimp or
tanttounderst
andthatf
inali
ze()isonl
ycal
ledjustpr
iortogarb
ageco
lle
cti
on.
Us
ingOb
jec
tsasPar
ame
ter
s(Par
ame
terPas
singMe
tho
ds)
:
I
nge
ner
al,
the
rear
etwoway
sthatac
omp
ute
rlang
uag
ecanp
assanar
gume
ntt
oas
ubr
out
ine
.
1
.cal
l-b
y-val
ue:
Thisappr
oachco
piestheval
ueo
fanar gumentint
ot hefor
malp aramete
ro fthe
s
ub r
outi
ne.The
ref
ore
,chang
esmadetot
hepar
ame
tero
fthesub
rout
inehavenoeff
ecto
nt hear
gument.
Examp le:
classTest{
voidme th(i
nti,intj
){
i*=2 ;
j/=2;
}}
classCallByValue
{
publicstat
icvo i
dmai n(
Str
ingargs
[]){
Testob=ne wTe st()
;
inta=1 5,b=2 0;
System.out.p
rintln(
"aandbbefo
recall
:"+a+""+b
);
ob.me t
h(a,b);
System.out.p
rintln(
"aandbaft
ercall:
"+a+""+b)
;
}}
o
utp
ut: aandbb
efo
rec
all
:152
0
aandbaf
terc
all
:152
0
2
.cal
l-b
y-r
efe
rence
:Inthisap
p ro
ach,ar
efe
rencet
oanargume
nt(notthevalueo
fthearg
ument)is
p
assedtot
heparamet
er.Thechange
smadetothep
arame
terwi
llaf
fectthear
gumentus
edtoc
allthe
s
ubrout
ine
.
Examp le2:classTest{
inta, b;
Test(i
nti ,
intj){
a=i ;
b=j ;
}
voidme th(Testo){
o.a*=2 ;
o.b/=2;
}}
classCallByRe f
{
publicstati
cvo idmain(St
ringar
gs[
])
{
Testob=ne wTe st
(15,
20);
System.out.printl
n("ob
.aandob.
bbef
orecal
l:"+o
b.a+""+o
b.b
);
ob.me t
h(ob);
System.out.printl
n("ob
.aandob.
baft
ercall
:"+ob
.a+""+ob
.b)
;
}}
Re
cur
sio
n:
Recur
sionisthepr
oces
sofdefi
nings
ome
thi
nginte
rmso fi
tse
lf.Asi
tre
lat
est
oJavap
rog
rammi
ng,
re
cursi
onistheat
tri
butet
hatal
lowsame
tho
dtocal
lit
sel
f.
Ame
tho
dthatc
all
sit
sel
fiss
aidt
ober
ecur
sive
.
Example:
cl
assFactori
al
{
intf
act(i
ntn)
{
if
(n==1)
ret
urn1;
re
turnfact(
n-1
)*n;
}
}
cl
assRecursio
n
{
pub
lics
tati
cvoidmain(Str
ingarg
s[])
{
Fact
ori
alf=newFac to
rial(
);
Sys
tem.out
.pr
intl
n("
Fac t
ori
alof3is"+f
.fact
(3))
;
Sys
tem.out
.pr
intl
n("
Fac t
ori
alof4is"+f
.fact
(4))
;
Sys
tem.out
.pr
intl
n("
Fac t
ori
alof5is"+f
.fac
t(5)
);
}}
Ac
essCo
ntr
ol(
Memb
erAc
ces
s):
J
avasup
portsric
hs e
tofacc
esss
pec
ifi
ers
,the
yar
e:
1.
publi
c,
2.
pri
vate
3.
pro
tected
4.
def
aultaccessl
evel
.
1.
publi
c:Whename mbero
fac
las
sismo
dif
iedb
ythep
ubl
ics
pec
ifi
er,t
hent
hatme
mbe
rcanb
e
acce
ssedb
yanyo
the
rcod
e.
Eg
:pub
lici
nta;
2
.pr
ivat
e:Whenamembero
fac
las
siss
pec
ifi
edasp
rivat
e,t
hent
hatme
mbe
rcano
nlyb
eac
ces
sedb
y
o
thermember
sofi
tsc
las
s.
Eg
:pr
ivat
eintb
;
3.
pro
tec
ted
:Thi
sisap
pli
edo
nlywhe
ninhe
rit
anc
eisus
ed.
Whenthememberofacl
assi
sdecl
are
daspr
otec
ted,
thenthatmemberc
anb
eus
edb
yal
lthec
las
seso
f
samep
ackag
ebutbyonl
ysubc
las
seswhic
hbel
ongtodif
fer
entpac
kag
es.
Herepac
ka g
eisesse
nti
all
y,ag
roup
ingo
fcl
ass
es.
i.
e.Pac
kag
eac
tsasac
ont
aine
rfo
rcl
ass
esand
sub
ord
inatepac
kag
es.
Eg
:pr
ote
cte
dintc
;
4.d
efaul
t:Whe
nnoacces
sspe
cifi
erisuse
d,thenbydef
aultt
heme mberofac
lassi
spubl
icb
utwi
thi
n
it
sownp ac
kag
ei.
e.t
hismembercanbeuse
db yal
lthecl
asse
sthatbe
long
stosamepac
kag
e.
Tab
le:
clas
sme
mbe
rac
ces
s
p
rivat
e No-mo
dif
ier p
rot
ect
ed p
ubl
ic
Samec
las
s y
es ye
s y
es y
es
Same pac
kage No y
es y
es y
es
subcl
ass
Samep ac
kagenon- No y
es y
es y
es
subcl
ass
Diff
erent p ac
kage No No y
es y
es
subcl
ass
Diff
erent p ac
kage No No No y
es
non-s
ub cl
ass
Examp l
e: /
/thispro
gramd e
mo nst
rate
st hedi
ffe
rencebet
weenp
ubl
icandp
rivat
e.
classTe st
{
inta;//defaultacce
ss
pub l
icintb ;/
/publi
cac cess
privateintc; /
/pri
vateac c
ess
voidsetc(inti){//s
etc '
svalue
c=i ;
}
intgetc(){//getc'
svalue
returnc ;
}}
classAc cessTest
{
pub l
icstaticvoidmai n(Str
ingargs
[])
{
Testob=ne wTe st
();
ob.a=1 0;
ob.b=2 0;
//ob.c=1 00;//Err
or!//ThisisnotOK, cisapri
vatevari
abl
e
ob.set
c(100);//OK //
Yo umus tacce
ssct hro
ughitsme t
hods
System. out.
p r
intl
n("a,b,andc:"+ob.a+""+
ob.b+""+o b.
getc
());
}}
Ne
ste
dandI
nne
rcl
ass
es:
I
tisp
oss
ibl
etod
efi
neac
las
swi
thi
nano
the
rcl
ass
;suc
hcl
ass
esar
ekno
wnasne
ste
dcl
ass
es.
Thesc
opeofaneste
dclassisb
oundedbythesc
op eofitsenc
los
ingcl
ass
.Anest
edc
las
shasacce
sst
othe
members,i
nclud
ingprivat
eme mbers
,oftheclassi nwhichiti
snest
ed.Ho
weve
r,t
heencl
osi
ngcl
ass
doe
snothaveacc
esstothememb e
rsofthenest
edc lass.
Ther
earetwot y
pesofnest
edclas
ses:st
ati
candno n-
stat
ic.Astati
cneste
dc l
assiso nethathasthe
st
ati
cmo di
fie
rapplie
d.Beca
useitisst
atic
,itmustacce
sstheme mber
sofitsenc
losingclasst
hrough
anobj
ect
.Thatis,i
tcanno
trefe
rtome mbersofi
tsencl
osi
ngcla
ssd i
rec
tly
.Becauseofthisrest
ric
tio
n,
st
ati
cneste
dclasse
saresel
domus e
d.
Themo s
timp ortantty
peofnest
edclas
sistheinnerclass
.Aninnercl
assi
sanon-st
ati
cnest
edclas
s.
Ithasacce
s stoalloft
hevariab
lesandmethodsofit
so ut
ercl
assandmayref
ert
othemdir
ectl
yinthe
samewayt hatothernon-
stat
icmemb er
softheoute
rclassdo
.
Examp le
://Demo nstrateani nnerclas
s.
classOut er
{
intouter_x=1 00;
voidtest()
{
Innerinne r=ne wI nne r()
;
inner.display(
);
}
//thisisani nnerc l
as s
classInne r
{
voidd i
splay()
{
Sys t
em. out.pri
ntln("
d ispl
ay: o
uter_x="+o
ute
r_x)
;
}}
}
classInne rClassDemo
{
pub l
icstaticvo i
dmai n(Stri
ngar g
s[])
{
Out e
ro uter=ne wOut er
( )
;
outer.t
e s
t();
}}
Exp
lor
ingSt
ringc
las
s:
St
ringi
sthemo
stc
ommo
nlyus
edc
las
sinJ
ava
’sc
las
sli
brar
y.
Thefi
rstt
hingtounder
standaboutstr
ingsi
sthateverys
tri
ngy
ouc
reat
eisac
tual
lyano
bje
cto
fty
pe
Str
ing
.Evenst
ringco
nstantsar
eactuall
yStr
ingob
ject
s.
Forexamp l
e,i
nthestat
e ment
Sy
stem.out.
print
ln(
"ThisisaStr
ing,
too
");
Here“ThisisaStri
ng,t
oo”isaStr
ingco
nstant
.
Theseco
ndt hi
ngtounde
rst
andabo
utst
ring
sisthatobj
ect
soft
ypeSt
ringar
eimmutable
;onceaStri
ng
obj
ecti
screate
d,i
tscont
ent
scanno
tbeal
ter
ed.Whilet
hismaysee
mlikeaseri
ousr
est
rict
ion,i
tisnot,
fo
rtwor e
asons:
•
Ifyouneedtoc
hangeastr
ing,
youcanalwayscr
eat
eanewo
nethatc
ont
ainsthemod
ifi
cat
ions
.
•
Javadef
inesapee
rclas
so fSt
ring
,cal
ledSt
ring
Buff
er,
whi
chall
owsst
ring
st ob
eal
ter
ed.
St
ring
scanb
eco
nst
ruc
tedi
navar
iet
yofway
s.Thee
asi
esti
stous
eas
tat
eme
ntl
iket
his
:
St
ringmy
Str
ing="
thi
sisat
est
";
t
hiss
tat
eme
ntd
isp
lay
smy
Str
ing
:Sy
ste
m.o
ut.
pri
ntl
n(my
Str
ing
);
t
heo
per
ato
r+i
sus
edt
oco
ncat
enat
etwos
tri
ngs
.
Fo
re xampl
e,
St
ringmyStr
ing="
I"+"l
ike"+"
Java
.";
Examp l
e:/
/Demo nstratingStr
ings.
clas
sStringDemo
{
publi
cstati
cvoidmai n(Str
ingargs
[])
{
Stri
ngstrOb1="Fir s
tSt ri
ng";
Stri
ngstrOb2="Se condSt r
ing";
Stri
ngstrOb3=s trOb1+"and"+s tr
Ob2;
Syst
em.out.pr
intln(strOb1)
;
Syst
em.out.pr
intln(strOb2);
Syst
em.out.pr
intln(strOb3);
}
}
TheStri
ngc l
assc ontainssever
alme t
hod
sthaty
ouc
anus
e.Fe
woft
hemar
e:
e
qual
s()
:us
ingt
hisme
tho
dwec
anc
omp
aret
hee
qual
ityo
ftwos
tri
ngs
.
l
eng
th():
Youc
ano
btai
nthel
eng
tho
fas
tri
ngb
ycal
li
ngt
hel
eng
th()me
tho
d.
c
har
At(
):Yo
ucano
btai
nthec
har
act
eratas
pec
ifi
edi
nde
xwi
thi
nas
tri
ngb
ycal
li
ngc
har
At()
.
Syntax:
b
o o
leanequal
s(St
ringo
bje
ct)
i
ntl e
ngth()
c
harc harAt(
inti
ndex)
Examp l
e://
De mo nstrati
ngsomeSt ringmethod
s.
classStr
ingDe mo 2
{
publics
taticvoidmai n(
Stri
ngar g
s[])
{
Strings
trOb 1="Fir stStr
ing"
;
Strings
trOb 2="Se condStri
ng "
;
Strings
trOb 3=s trOb1;
System.out.
p r
intln("Lengt
ho fst
rOb1 :
"+s t
rOb1
.l
engt
h()
);
System.out.
p r
intln("Charatindex3i nstr
Ob1:
"+s t
rOb1
.char
At(
3))
;
if
( s
trOb1
.equals(
s trOb2))
System.out.
p r
intln("str
Ob1==s tr
Ob 2")
;
else
System.out.
p r
intln("str
Ob1!=strOb2");
if
( s
trOb1
.equals(
s trOb3))
System.out.
p r
intln("str
Ob1==s tr
Ob 3")
;
else
System.out.
p r
intln("str
Ob1!=strOb3");
}
}