Java Notes
Java Notes
OOPt reatsdataasacr i
ti
calel
ementi nthepr ogr
am dev el
opmentanddoesnot
all
ow itt of l
ow freel
yar ound t
hesy st
em.I ttiesdat a morecloselytot he
functi
onst hatoperateoni tanpr otectsitfrom unintenti
onalmodif
icati
onby
otherfuncti
on,OOPal lowsustodecomposeapr obl
em i ntoanumberofent i
ti
es
call
edObj ectsandt henbuilddataandf unct
ions(knownasmet hodsi nJava)
aroundtheseentit
[Link] aandmet hodsmakeupanobj ect.
Obj
ect=dat
a+met
hods
Thedat
aofanobj
ectcanbeaccessedonlybythemethodsassoci
atedwi t
ht hat
obj
ect
.Howev
er,
methodsofoneobjectcanaccesst
hemethodsofot herobjects.
Basi
cconceptofObj ect
-Ori
ent
edProgramming
TheObject-
OrientedProgrammingi
ncl
udes-
Objects
Classes
Dataabst racti
onandencapsul
ation
I
nher i
tance
Polymor phism
Dynami cbi ndi
ng
Messagepassi ng
Objects
Objectsaret hebasi
crun-ti
meentit
iesinanobj ect-
ori
ent
edsyst
[Link]
representaperson,aplace,abankaccount,atabl
eofdataoranyit
em t
hatthe
program hast ohandl
[Link]-
defi
neddat
asuchasv ect
ors,
ti
meandl i
sts.
Ex.
Obj
ect:
Student
Dat
a :
Name
Dat
eofBi
rt
h
Marks
Classes
Sinceobject
scontai
ndata,andcodet
omanipulat
[Link]
resetof
dataandcodeofanobjectcanbemadeauser-
defi
neddatatypewit
hthehelpof
aclass,i
.e.
,obj
ect
sarevari
ableoft
het
ypecl
[Link],
1
wecancr eat
eanynumberofobj ect
sbelongi
ngtothatcl
[Link] ectis
associ
atedwit
hthedataoftypecl
asswithwhicht
heyarecreat
[Link]
efore,a
cl
assi sacol
lect
ionofobj
ectsofsimil
arty
[Link]
e,mango,appleand
orangearemembersoft
heclassfr
uit
.
Fr
uitmango;
Wi
l
lcr
eat
eanobj
ectmangobel
ongi
ngt
othecl
assf
rui
t.
Cl
assesar
euser-
defi
ned dat
aty
pesandbehav
eli
ket
hebui
l
t-i
nty
pesofa
pr
ogrammi
ngl
anguage.
DataAbst r
act i
onandEncapsul at
ion
Thewr appingupofdat aandf uncti
onsi ntoasingl
euni t(cal
l
edCl ass)isknown
asencapsul ati
[Link] ai
snotaccessi bl
etotheoutsidewor l
d,andonl yt
hose
methodswhi charewr appedint heclass,[Link] hodsprovi
de
theint
erfacebet weent heobject’sdataandt [Link] sinsulat
ionofthe
datafr
om di rectaccessbythepr ogram i
scal l
eddatahiding.
Dat
a
I
nfor
mat
ion‘
i
n’ I
nfor
mat
ion‘
out
’
and
Met
hod
Abstr
act
ionreferstotheactofr epr
esent i
ngessent i
alfeat
ureswi t
hout
i
ncludi
ngt hebackgrounddetail
[Link] heconceptof
abstr
acti
onandar edefinedasal i
stofabstractattr
ibutessuchassi ze,weight
and cost,and funct
ions t
o operat
e on these attr
[Link] att
ributes are
sometimescall
eddat amember sbecausetheyhol di nf
ormati
[Link] unct i
ons
hatoperateonthesedataaresometi
mescalledmet hodsormemberf unctions.
I
nher
it
ance
2
Inheri
tanceisthepr ocessbywhi chobjectsofoneclassacqui r
ethepropert
iesof
objectsofanot [Link]
calclassi
fi
cati
[Link]
exampl e,t
hebird‘robin’isapartoft heclass‘
fl
yingbird’whi
chi sagai
napar tof
theclass‘ bi
rd’
.Thepr inci
plebehindt hi
ssortofdi vi
sionist hateachder i
ved
classsharescommonchar acter
ist
icswi t
htheclassfr
om whi chiti
sderiv
ed.
Bird
At
tri
butes
Feathers
Layeggs
Nonfl
ying
Fl
yi
ngBir
d Bir
d
Att
ri
but
es At
tri
butes
……… ………….
……….
Poly morphism
Poly morphism isanotherimportanceOOP concept ,meanst heabi l
i
tytot ake
mor et hanonef [Link] ati
onmayexhibitdifferentbehavi
oursindiffer
ent
i
nst [Link] i
ourdependsupont hetypesofdat ausedi
nt heoperati
on.
Forexampl e,consi
dertheoperati
onofaddit
ion,fortwonumber s,t
heoper at
ion
willgener atea sum.I ftheoper andsarest r
ings,t hen t
heoper at
ion would
produceat hi
rdstri
ngbyconcatenati
on.
Shape
Dr
aw(
)
3
Ci
rcl
eobj
ect Boxobj
ect Tr
iangl
eobj
ect
Dr
aw(
cir
cle) Dr
aw(
Box) Dr
aw(
tri
angl
e)
Here a si
ngl
efunct
ion name can be used t
o handl
e di
ff
erentnumberand
di
ff
erentty
pesofar
gument s.
Dy namicBi
nding
Bindingref
erstotheli
nki
ngofapr ocedurecal
ltot
hecodetobeexecutedin
responsetothecall
.Dynamicbindingmeanst hatt
hecodeassociat
edwit
ha
givenprocedurecal
lisnotknownunt i
lt heti
meofthecal
latr unt
ime.I
tis
associat
edwithpol
ymorphi
sm andinherit
ance.
MessageCommuni cati
on
Anobj ect-or
ientedprogram consist
sofasetofobj ectsthatcommuni cat
ewi t
h
each ot [Link] pr ocess ofpr ogrammi ng i
n an obj ect
-ori
ented l
anguage,
ther
efore,involv
est hefoll
owingbasicsteps:
[Link] eatingclassesthatdefi
neobjectsandt heirbehaviour
.
[Link] eatingobjectsfr
om classdefini
ti
ons.
[Link] ablishi
ngcommuni cationamongobj ects.
Obj
ect
scommunicatewit
honeanotherbysendi
ngandr ecei
vi
ngi
nfor
mat
ion
muchthesamewayaspeopl
epassmessagest
ooneanot
heras:
Obj
ect
1
Obj
ect
4
Obj
ect
3
Obj
ect
2
4
Message
Sendi
ngobj
ect Met
hod() Receiv
ing
o object
Messagepassinginvol
vesspecif
yingthenameoftheobj
ect
,thenameoft
he
method(message)andthei
nformationtobesent
.
Empl
oyee.
sal
ary
(name)
Her
e,Employeeistheobj
ect
,sal
aryi
sthemessageandnamei
sthepar
amet
er
t
hatcont
ainsinf
ormati
on.
JAVA
Javai sagener al-purpose,obj ect-
ori
entedpr ogr ammi nglanguagedev elopedby
SunMi cr osystemsofUSA i [Link] igi
nall
y ,Jav aiscal l
edOAK byJames
Gosling t he i nventoroft he [Link] rstly,Jav a was desi gned f ort he
developmentofsof t
war eforconsumerel ectronicdev i
cesl i
keTVs,VCRs,and
suchot herel ectronicmachi [Link] heprogr am oft hesedev icesar ecal l
ed
machi nei nteractionpr ogram t hatmaket heJav al anguagesimpl e,portableand
hi
ghl [Link] er,CandC++hadl i
mitati
onsi nter
msofbot hr el
i
abi l
it
yand
portabil
ity,thusJav aov ercomenumberoff eat ur
esofC andC++.Themost
str
ikingf eatur eoft helanguagei sthatitisapl atform-neutr
allanguage, i.
e.,Java
i
st hef irstpr ogrammi nglanguaget hatisnott iedt oanypar ti
cularhar dwar eor
operatingsy [Link] ogramsdev elopedi nJav acanexecut edany wher eonany
system.
JavaFeatures
SunMicrosystemsof f
icial
lydescri
besJavawi
tht
hef
oll
owi
ngat
tri
but
es:
[Link] ledandI nterpret
ed
[Link] atf
or m- I
ndependentandPor tabl
e
[Link] ect-Or i
ented
[Link] e
[Link] str
ibut ed
[Link] liar,SimpleandSmal l
[Link] ti
thr eadedandI nteract
ive
[Link] ghPer for
mance
[Link] nami candExt ensibl
e
Thesef
eat
ureshav
emadeJav
athef
ir
stappl
i
cat
ionl
anguageoft
heWor
ldWi
de
Web.
Compil
edandI nt
erpr
eted
Usual
l
yacomput erl
anguagei
seithercompiledori
nterpr
[Link] nes
boththese appr
oaches t
hus making Jav
aat wo-
stage [Link]
st,Jav a
compil
ertr
anslat
essourcecodeintowhati sknownasby tecodeinst
ruct
ions.
5
Bytecodesar enotmachi
neinst
ruct
ionsandt her
efore,i
nthesecondst
age,Java
i
nterpretergenerat
esmachi
necodet hatcanbedirectl
yexecut
edbythemachine
thatisrunningtheJav
aprogr
am.
Platf
orm- I
ndependentandPort
able
Java programs can easil
y moved f
rom one comput ersystem t
o anot her
,
anywhereandany t
[Link]
atingsyst
ems,processors
andsy st
em resourceswil
lnotfor
ceandchangesinJav aprogr
[Link] he
reasonwhyJav ahasbecomeapopul arl
anguageforprogrammingonI nt
ernet
whichinter
connectsdif
fer
entki
ndsofsyst
emswor l
dwide.
Object
-Ori
ented
JavaisatrueObject
-Ori
ent
[Link]
mostever
ythingi
nJav
aisanObj
ect
.
All
program codeanddatar
esi
dewi t
hinobj
ect
sandclasses.
RobustandSecur e
Javaisar obustlanguage.I
tprovidesmanysaf eguardstoensurer
eli
ablecode.I
t
hasst r
ictcompil
et i
meandr untimechecki ngfordat atypes.
Securit
y becomes an i mportant issue for a l anguage that i
s used for
programmi ng on I nt
ernet
.Thr eat of viruses and abuse of r esour
ces is
[Link] st
emsnotonl yverif
yallmemor yaccessbutal
soensurethat
nov i
rusesarecommuni cat
edwi t
hanappl et.
Distr
ibuted
Javaisdesignedasadistr
ibut
edlanguageforcreat
ingappl
i
cat
ionsonnetworks.
Ithast heabil
i
tytosharebothdataandpr [Link]
i
cati
onscanopen
andaccessr emot
eobjectsonInt
ernetaseasil
yastheycandoinalocal
system.
Familiar
,Si
mpleandSmal l
Javai sasmallandsimpl
el [Link]
uresofCandC++t hatar
eei t
her
redundantorsourcesofunreli
[Link] e,Java
doesnotusepoi nter
s,preprocessorheaderfi
les,gotostatementandmany
others.I
tal
soeliminat
esoperatorover
loadi
ngandmul t
ipl
einheri
tance.
Mul ti
thr
eadedandInter
acti
ve
Mul ti
thr
eadi
ngmeanshandl ingmulti
pletaskssi
mul t
aneousl
[Link]
s
mul ti
thr
eadedprogr
[Link] tf
ortheappli
cat
iont
o
fi
nishont askbefor
ebeginni
nganot
[Link],wecanlist
entoanaudio
cl
ipwhi lescrol
li
ngapageandatt hesamet imedownloadanappl etfr
om a
di
st antcomputer
.
HighPer
formance
Javaper
formanceisi
mpressi
vef
orani
nter
pret
edl
anguage,mai
nlyduet
othe
useofi
nter
mediat
ebyt
ecode.
Dy
nami
candExt
ensi
ble
6
Jav aisadynami [Link]
lyl
inkinginnewcl
ass
l
ibrari
es,met hods,and [Link] can al
so det
ermine the ty
peofclass
through a query,making itpossibl
et o ei
therdynamical
lylinkorabortthe
program,dependingont heresponse.
JavaandC/C++
TheJavateam di
dnotincludesomeoft hef oll
owi ngC/C++featur
esinJava:
[Link] adoesnotincludet heCuni quest atementkey wordsgoto,si
zeof
,and
ty
pedef.
[Link] adoesnotcontainthedat atypest ruct,uni
onandenum.
[Link] adoesnotusepoi nter.
[Link] adoesnotincl
udeheaderf i
les.
[Link] adoesnotsuppor toperatorov er
loading.
[Link] adoesnothavet emplateclassesasi nC++
[Link] adoesnotsuppor tmultipl
einheritancesofclasses.
[Link] adoesnotsuppor tgl obalv ari
[Link] er
yv ari
ableandmet hodis
decl
aredwithi
nacl assandf ormspar toft hatcl
ass.
JavaandI nt
ernet
Javai sstronglyassoci at
edwi ththeInt
ernetbecauseoft hef actthatthef ir
st
appli
cationwr it
teni nJav awasHOTJAVA,aWebbr owsert or unappl et
son
Int
[Link]
netuser scanuseJav at ocreateappletpr
ogr amsandr unt hem
l
ocallyusinga“ Java-enabledbrowser”[Link] souse
Java-enabledbr owsertodownl oadanappletlocat
edonacomput eranywher ein
theInternetandr unitonhi slocalcomputer.I
nter
netuserscanal soset upt hei
r
Websi tescont aini
ngJav aappletsthatcouldbeusedbyot herremoteuser sof
Int
ernet.
Jav aandWor l
dWi deWeb
Wor ldWi deWeb( www)i sanopen- endedi nfor
mat i
onr etri
evalsystem designed
tobeusedi ntheInternet’
sdi st
ributedenv i
ronment .Jav awasmeantt obeused
i
ndi stri
butedenv i
ronment ssuchasI nt
[Link]
nce, botht heWebandJav ashar e
thesamephi l
osophy ,Jav acoul dbeeasi lyincorpor atedintotheWebsy stem.
Befor eJav a,thewww wasl i
mi t
edt ot hedi splayofst il
limagesandt exts.
Howev er
,thei ncorpor at
ionofJav ai ntoWebpageshasmadei tcapableof
suppor ti
nganimat i
on, graphics,gamesandawi derangeofspeci alef
[Link]
thesuppor tofJav a,theWebhasbecomemor ei nteracti
veanddy [Link] he
otherhand,wi tht
hesuppor tofWeb,wecanr unaJav apr ogr
am onsomeone
else’scomput eracrosst heInternet.
JAVAEnv i
ronment
Jav aenv
ironmenti ncl
udesalargenumberofdevelopmenttool
sandhundredsof
classesandmet [Link] ool
sar
epar tofthesyst
em knownas
Jav aDevelopmentKi t(JDK)andtheclassesandmet hodsarepartoftheJava
StandardLi br
ary(JSL),alsoknownast heAppl
icati
onProgrammingInterf
ace
(API).
7
JavaDev el
opmentKi t
TheJav aDev elopmentKi tcomeswi t
hacol l
ectionoftoolsthatar
eusedf or
dev
elopingandr unni ngJav apr [Link] ncludes:
appl et v
iewer( forviewi ngJav aappl ets)–Enabl estorunJavaappl
ets.
j avac( Jav acompi l
er )–Whi chr unsappl etsandappli
cati
onsbyr eading
andi nterpr etingby t
ecodef il
es.
j ava( Jav aI nt erpreter)–Whi cht ransl
atesJav asourcecodetoby tecode
fil
est hatt hei nt er
pret ercanunder stand.
j avap( Jav adi sassembl er)–Whi chenabl esust oconvertbyt
ecodef il
es
intoapr ogr am descr ipti
on.
j avah( forC headerf i
les)– Pr oducesheaderf i
lesforusewi t
hnat i
ve
met hods.
j avadoc ( for cr eating HTML document s) – Creat
es HTML f ormat
document ationf r
om Jav asour cecodef i
les.
j db(Jav adebugger )–Whi chhelpsust ofinderror
sinourprogr
ams.
Appl
icat
ionPr
ogr
ammi
ngI
nter
face
TextEdi
tor
HTML
Java Fil
es
Source Jav
adoc
Code
Jav
ac
Header
Java Fi
les
Cl
assFi
le Jav
ah
Jav
a j
db
Java
Program
Output
Twoway
sofusi
ngJav
a
8
Java
SourceCode
Jav
a
Compiler
Jav
aenabled Java
WebBrowser I
nter
pret
er
Out
put Out
put
ASi
mpl
eJav
apr
ogr
am
Cl
assTest
{
publi
cstati
cvoidmain(
str
ingargs[]
)
{
Syst
[Link]
.pr
int
ln(
“Hel
loJava!”
);
}
}
Cl
assDecl
arat
ion
Thef
ir
stl
i
ne
Cl
assTest
9
Themainl
ine
Thet
hir
dli
ne
Publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[]
)
def
inesamet hodnamesmai [Link]
yJavaappl
i
cati
onpr ogram mustincl
udethe
main()[Link]
sist
hestarti
ngpointf
ort
heint
erpr
etertobegintheexecut
ion
oft
hepr [Link]
scont
ainsanumberofkeywordspublic,
stat
icandv oi
d.
Publ i
c–Thekey wor dpubl ici
sanaccessspeci fi
erthatdeclarest hemai n
met hodasunpr otectedandt heref
oremaki nginaccessi bletoal lother
cl
asses.
Static– Nextkey wor dst ati
c,whichdecl ar
esthismet hodasonet hat
belongstot heenti
recl assandnotapar tofanyobject
soft [Link]
mai nmustal waysbedecl ar
edasst at
icsincetheinterpreterusest his
met hodbeforeanyobj ectsarecreated.
Void–v oidstat
est hatt hemai nmet hoddoesnotr eturnanyv alue,but
si
mpl yprint
ssomet extt othescreen.
Pr
ogr
am -2
/
*Comput
esquar
eroot*
/
i
mportjava.
lang.
Math;
cl
assSquqreRoot
{
publi
cstati
cvoi
dmain(
Str
ingar
gs[]
)
{
doubl
ex=5;
doubl
ey;
y=Mat
[Link]
t(x)
;
Sy
stem.
out
.pr
int
ln(
“y=“+y
);
}
}
UseofMathf
unct
ions
Notet
hatt
he
i
mportjava.
lang.
Mat h;
Thepurposeofthi
sstatementistoinstructthei
nter
pret
ertoloadt
heMathcl
ass
fr
om [Link]
ementi ssi mil
arto#incl
udestatementi
[Link],
Mathcl
asscontainsthesqrtmethodr equir
edintheprogr
am.
10
Comment s
Javaper
mitsboththesi
ngl
e-l
i
necomment sandmult
i-l
i
necommentsavai
l
ablein
C++.Thesingl
eli
necommentsbeginwith//andatt
heendoftheli
neasshown
ontheli
nesdeclari
ngxandy .Forlongercomments,wecancreat
emulti
-l
ine
commentsbystart
ingwi
tha/*andendingwith*
/
Pr
ogr
am –3
Cl
assRoom
{
fl
oatlengt
h;
fl
oatbreadt
h;
v
oidgetdata(
fl
oata,
floatb)
{
l
ength=a;
breadt
h=b;
}
}
cl
assRoomArea
{
publ
i
cstaticv
oi dmai
n(Str
ingargs[]
)
{
fl
oatarea;
Room room1=newRoom( );
Room1. get
dat
a(14,
10);
area=room1.l
ength*[Link]
h;
Sy
stem.
out
.pr
int
ln(
“Ar
ea=”+ar
ea)
;
}
}
Here,t
woclassesRoom andRoomAr [Link] classdef
inestwovar
iabl
es
and onemethod to assi
gn val
uestot hesevariabl
[Link]
contai
nthemainmethodthati
nit
iat
estheexecut
ion.
Themai nmethoddeclaresalocalv
ari
ableareaandaRoom t
ypeobjectr
oom1
andassignvaluestot hedatamember sofRoom classbyusi
ngthegetdat
a
[Link]
nal
ly,i
tcal
culatest
heareaandpri
ntsther
esult
s.
Jav
aProgram St
ruct
ure
AJavapr
ogram maycontai
noneormor
esect
ionsas
11
Document
ati
onSect
ion Suggest
ion
PackageSt
atement opt
ional
I
mpor
tSt
atement opt
ional
I
nter
faceSt
atement opt
ional
Cl
assDef
ini
ti
ons
opt
ional
Mai
nMet
hodCl
ass
{
Mai
nMethodDef
ini
ti
on Essent
ial
}
Documentat
ionSecti
on
Thedocumentati
onsecti
oncompr
isesasetofcommentli
nesgi
vingt
henameof
thepr
ogram,theauthorandot
herdetai
l
[Link]‘
//’and‘
/**…….
.*/
’known
asdocumentat
ioncomment.
PackageStat
ement
Thi
sst at
ementdeclar
esapackagenameandi
nfor
mst
hecompi
l
ert
hatt
he
cl
assesdefi
nedherebel
ongt
othi
spackage.
Ex.
:
Packagest
udent;
Thepackagest
atementi
sopt
ional
,i.
e.,ourcl
assesdonothav
etobepar
tofa
package.
Importstatements
Thisstatementmaybenumberofi mportstat
ement
[Link]
ssimilart
othe
#incl
udestatementinC.
Ex.:
I
mpor tst
udent.
test
;
Thisstatementinst
ructsthei
nter
pret
ert
ol oadthet
estcl
asscont
ainedi
nthe
packagestudent.
Interf
aceSt atements
Ani nterf
acei sli
keaclassbuti
ncl
udesagroupofmethoddecl
arat
[Link]
sis
also anopt i
onalsecti
onandisusedonlywhenwewi shtoi mplementthe
mul t
ipleinheri
tancef
eatur
esint
heprogr
[Link]
erf
acei
sanewconceptinJava.
12
ClassDefi
niti
ons
AJav aprogram maycontainmult
ipl
eclassdef
ini
ti
[Link]
assesarethepr
imary
andessentialel
ementsofaJav aprogr
[Link] he
object
sofr eal-
wor
[Link] assesuseddependsont he
complexi
tyoftheprobl
em.
Mainmethodcl
ass
Amai nmethodasit
sstarti
ngpoint
,thi
sclassistheessent
ialpar
tofaJav
a
pr
[Link]
eJavaprogram maycont
ainonl
ythi
spart
.
JavaTokens
AJavapr ogram isacol
l
ect
ionoft
okens,
comment
sandwhi
[Link]
ear
e
fi
vety
pesoft okens:
Key wor ds
Identifi
ers
Liter
als
Oper ators
Separ ator
s
Key
words-Keywords are an essenti
alpartofa language def
init
[Link]
i
mplementspeci
fi
cfeaturesoft [Link]
alanguagehasr eserv
ed60
wor
dsaskeywords.
abstr
act bool
ean br
eak byt
e case char
catch cont
inue do doubl
e el
se fl
oat
I
denti
fi
ers-Identi
fi
ersar
eusedf ornami ngcl
asses,methods,var
iabl
es,obj
ects,
l
abel
s,packages and i nterfaces in a progr
[Link] ai dent
ifi
ersfoll
ow the
f
oll
owingrules:
Theycan hav e alphabet s,digit
s and t
he underscor
e and doll
arsign
character
s.
Theymustnotbegi nwi thadi gi
t.
Upper caseandlower casel et
tersaredi
sti
nct.
Theycanbeofanyl ength.
Ex.
aver age,sum
totalMarks
student _
name
Tot al
CONSTANTS
JAVACONSTANTS
13
VARIABLES
Avariabl
ei sani dent
if
ierthatdenot
esast or
agelocat
ionusedtostor
eadat a
val
[Link] ari
abl
emayt akediff
erentv
aluesatdif
fer
entt
imeduri
ngtheexecut
ion
oft
hepr ogr am.
Ex.
:
average,
height
,tot
al_l
ength
DATATYPES
DATATYPESI
NJAVA
Pr
imi
ti
ve(
Int
ri
nsi
c) Non-
Pri
mit
ive(
Der
ived)
Numer
ic Non-
numer
ic Cl
asses Ar
ray
s
I
nteger Fl
oat
ing-
poi
nt Char
act
er Bool
ean I
nter
face
Si
zeandRangeofInt
egerTy
pes
Type Size Range
by
te 1byte -
128to127
14
shor
t 2by
te -32768to32767
i
nt 4by
te -2147483648to2147483647
l
ong 8by
te -
9223372036854775808to9223372036854775807
SizeandRangeofFloat
ingPoi
ntTy
pes
Type Size Range
byte 1byte -128to127
short 2byte -32768to32767
fl
oat 4byte 3.4e-
38to3.4e+38
double 8byte 1.7e-
308to1.7e+308
Float
ingpointnumber sar
etr
eatedasdoubl
e-pr
eci
sionquant
it
[Link]
cet
hem
tobeinsingle-
preci
sionmode,wemustappendforFtothenumber .
Ex.:
1.
23f
7.
5692F
Charact
erTy pe
Javaprovi
desacharact
erdat
atypecal
l
edchar
.Thechart
ypeassumesasi
zeof
2bytesbut,basi
cal
l
y,i
tcanhol
donlyasi
ngl
echar
act
er.
Bool
eanTypes
Bool
eantypeisusedt
ot estapart
icul
arcondi
ti
onduri
ngtheexecut
ionofthe
pr
[Link]
eareonl
ytwov al
uest
hataBooleanty
pecant
ake:t
rueorfal
se.
Pr am –Readi
ogr ngdat
afr
om key
boar
d
Importjava.
[Link]
nputSt
ream;
classReading
{
publi
cst at
icvoidmain(
Stri
ngargs[
])
{
DataInputSt
ream i
n=newDat aI
nput
Str
eam(
Syst
em.
in)
;
i
ntinNumber=0;
fl
oatfloat
Number=0. 0f
;
Tr
y
{
Syst
[Link]
.pr
intl
n(“
EnteranInteger:
“ )
;
i
ntNumber=Integer
.parseI
nt(
in.r
eadl
ine()
);
Syst
em.
out.
pri
ntl
n(“
Enteraf
loatnumber:“
);
fl
oat
Number=Float
.val
ueOf
(in.
readl
i
ne(
)).
fl
oat
Val
ue(
);
}
cat
ch(
Except
ione){ }
15
Syst
em.
out
.pr
int
ln(
“i
ntNumber=“
+int
Number)
;
Syst
em.
out
.pr
int
ln(
“fl
oat
Number=“+f
loat
Number
);
}
}
ScopeofVar iables
Javavari
ablesar eactuall
ycl
assi
fi
edi
ntot
hreeki
nds:
instancev ar
iable
classv ari
able
localvariabl
e
i
nst anceandcl assv ari
ablesar edecl aredinsideacl [Link]
ancev ari
ablesar e
createdwhent heobj ectsar einstanti
atedandt hereforetheyareassociatedwi th
theobj ect
[Link] akedif f
erentv al
uesf oreachobj [Link] heotherhand,cl ass
variabl
esar eglobalt oacl assandbel ongt otheent iresetofobjectsthatcl ass
[Link] aredandusedi nsidemet hodsar ecall
edl ocalvariabl
es.
Theyar enotav ail
ableforuseout sidet hemet hoddef ini
ti
[Link] ari
ablescan
alsobedecl aredi nsi
depr ogr am blockst hataredef i
nedbet weenanopeni ngand
closingbrace.
Sy
mbolicConst
ants
Aconst
anti
sdeclar
edasf
oll
ows:
f
inal t
ype sy
mbol
i
c-name=v
alue;
Ex.
:
f
inal f
loat PI =3.
14159;
f
inal i
nt MARKS =100;
Symbolicconstant
sarewr i
tt
enincapi tal
s.
Afterdeclar
ati
onofsy mboli
cconstant s,t
heyshoul
dnotbeassi gnedany
othervaluewithi
nt heprogram byusi ngasassignmentst at
ement,e.
g.,
MARKS=200i sill
egal.
Symbolicconstant
saredeclaredfortypes.
Symbolicconstant
scannotbedecl aredinsi
deamet [Link]
usedonlyasclassdatamember si
nt hebeginni
ngoftheclass.
TypeCasting
Theprocessofconvert
ingonedat
atypetoanot
heri edcast
scal
l ing.
Synt
ax:
ty
pe v ar
iabl
e1 = (t
ype)var
iabl
e2;
Ex.
:
i
nt m = 50;
byte n = (byt
e)m;
l
> ong)m;
16
Cast
ingi
ntoasmallerty
pemayr esul
tinalossofdata,e.
g.,cast
ingaf
loat
ing
poi
ntval
uetoani
ntegerwil
lresul
tinalossoft
hefr
acti
onalpart.
From To
byte short
, char,
int
,long,
float
,doubl
e
short i
nt,l
ong, fl
oat,
double
char i
nt,l
ong, fl
oat,
double
i
nt i
nt,f
loat ,
double
l
ong fl
oat,double
fl
oat double
Ex.
:
i
nti
=123456789;
shor
ts=(
shor
t)i
; => -
13035;
f
loatf
1=3.
142F;
i
ntm1=(
int
)f1 => 3
l
ongl
=1234567654321L;
f
loatn1=(
fl
oat
)l
; => 1.
23457e+012
Gett
ingval
uesofvari
ables
Javasupport
stwooutputmet
hodsthatcanbeusedt
osendtheresul
tst
othe
scr
een.
pr i
nt()
method //pri
ntandwait
pr i
ntl
n()method //pri
ntali
neandmov
etonextl
i
ne
OPERATORSANDEXPRESSIONS
Operat
ors
Javaoper
ator
scanbecl
assi
fi
edas:
17
[Link]
hmet i
coperators
[Link]
ors
[Link] oper
ators
[Link] ator
s
[Link] ementoper
ator
s
[Link] ti
onaloperators
[Link]
[Link] aloper
ators
[Link]
thmet
icoperat
ors–
+ Addit
ion
- Subtr
action
* Multi
pli
cat i
on
/ Div
isi
on
% Modulodi vi
sion
Ex.
: a+b, a-b, a*b, a/b, a%b
Note:
Theoperat
or%cannotbeusedwi t
hr ealoper
ands
[Link]
ati
onaloper
ator
s–
< Lessthan
> Great
erthan
<= Lessthanorequalt
o
>= Great
erthanorequalt
o
== Equalto
!= Notequalto
[Link]
caloper
ators–Javahasfol
lowi
ngt
hreel
ogi
cal
oper
ator
s
&& LogicalAND
|
| Logi
calOR
! Logi
calNOT
Ex.
Age>55&&sal ary<10000
Logi
cal
oper
ator
sar
eusedt
otestmor
ethanonecondi
ti
onandmakedeci
sion.
Tr
uthTabl
e
&& || !
Oper
and1 Oper
and2 resul Oper
and1 Oper
and2 r
esul operand r esul
t t t
True True True True True True False True
True Fal
se False True Fal
se True Tr
ue Fal
se
Fal
se True False Fal
se True True
Fal
se Fal
se False Fal
se Fal
se Fal
se
[Link]
gnmentoper
ator
s– I
n addi
ti
on,Jav
a has a setof‘
shor
thand’
18
assi
gnmentoper
ator
soft
hef
orm
v op=exp;
or
,
v=vop(
exp)
;
Her
e,v=var
iabl
e
exp=expr
essi
on
op=short
handassi
gnmentoper
ator
.
Ex.:
x=x+(
y+1)
Her
e,
v=x, op=+,
exp=y
+1
i
.e.
, x+= y+1;
Someshor
thandassi
gnmentoper
ator
s
a=a+1 a+=1
a=a–1 a-
=1
a=a*(
n+1) a*=n+1
a=a/(
n+1) a/=n+1
a=a%b a%=b
5.I
ncr
ementanddecrementoperator
s–Jav
ahast
wov
eryusef
uloper
ator
s
i
ncr
ementanddecr
ementoperators
++ and --
[Link]
ti
onaloper
ator
s“?
:”–
Var
iabl
e=exp1?exp2:exp3;
i
.e.
,
v
ari
abl
e=(
condi
ti
on)? v
alue1:v
alue2;
Her
e,exp1,exp2andexp3ar
eexpr
essi
ons
i
sequalto
19
i
f(exp1)
exp2;
el
se
exp3;
Ex.
:
i
f(a>b)
x=a;
el
se
x=b;
i
.e,
x=(
a>b)?a:
b;
[Link]
wiseoperators–Javahasabitwiseoper at
orsformanipulat
ionofdat
a
atbitl
evel
.Theseoperator
sareusedf ort
esti
ngthebits,orshi
fti
ngthem
ri
ghtorlef
[Link]
twiseoper
ator
smaynotbeappl iedtofl
oatordouble.
Operator Meaning
& Bi
twiseAND
! Bi
twiseOR
^ Bi
twiseexclusiv
eOR
<< Shi
ftleft
>> Shi
ftright
~ One’
scompl ement
[Link]
alOperator
s– Jav asuppor
tssomespecialoperator
sofint
erest
suchasi
nstanceofoper
atorandmembersel
ect
ionoperator(
.).
i
nst anceofoperator–i sanobj
ectrefer
enceoperatorandret
urnstr
ueifthe
objectont helef
t-
hand-sidei
saninst
anceoftheclassgivenonther
ight
-hand
-
[Link] soperatoral
lowsustodeterminewhethertheobjectbel
ongstoa
particul
arclassornor.
Ex.
:
per
soni
nst
anceofst
udent
i
str
uei
ftheobj
ectper
sonbel
ongt
othecl
assst
udent
;ot
her
wisei
tisf
alse.
Dotoperat
or–Thedotoperat
or(
.)i
susedt
oaccesst
hei
nst
ancev
ari
abl
es
andmethodsofcl
assobj
ect
s.
Ex.
:
per
son1.
age /
/ref
erencet
othev
ari
abl
e
20
per
son1.
sal
ary
() /
/ref
erencet
othemet
hodsal
ary
()
Expr
essi
ons
Expr
essi
onsar
eev
aluat
edusi
nganassi
gnmentst
atementoft
hef
orm
Var
iabl
e=expr
essi
on;
Ex.
x=a*b–c;
PrecedenceofAri
thmeticOperators
Therearetwodist
inctpr
ior
it
ylevelsofar
it
hmet
icoper
ator
sinJav
a
Highpr
ior
it
y * / %
Lowpri
ori
ty + -
Thebasi ceval
uati
onpr ocedureincludestwol eft
-t
o-r
ightpassest hroughthe
expressi
[Link]
ngthefirstpass,thehighpri
ori
tyoperators(i
fany)ar eappli
ed
astheyareencount
[Link] helowprior
it
yoperators(i
fany)
areappli
[Link]
on:
x=a–b/
3+c*
2–1
Her
e,a=9,
b=12,
andc=13,t
hen
x=9–12/
3+3*
2-1
Thus,
Fi
rstpass:
Step1: x=9–4+3*2–1
Step2: x=9–4+6–1
Secondpass:
Step3: x=5+6–1
Step4: x=11–1
Step5: x=10
However,theorderofeval
uat
ioncanbechangesbyi
ntr
oduci
ngpar
ent
hesesi
nto
[Link]
essi
on
x=9–12/
(3+3)*2-1
Wheneverparent
hesesareused,t
heexpressionswi t
hinparent
hesesassume
hi
ghestpri
ori
[Link] ormoresetsofpar enthesesappear,theexpr
essi
on
cont
ainedi
ntheli
ft-
mostseti
seval
uat
edfi
rstandt heri
ght-
mostinthel
astas:
Fi
rstpass:
21
St
ep1: x=9–12/
6*(
2–1)
St
ep2: x=9–12/
6*1
Secondpass:
Step3: x=9–2*1
Step4: x=9–2
Thi
rdpass:
Step5: x=7
Typeconversi
onsi nexpressi
ons
I
ftheoperandsar eofdiffer
entt
ypes,t
he‘l
ower’typei
sautomati
cal
l
yconv er
ted
tothe‘
hi
gher ’
typebeforetheoper
ati
[Link]
esul
tisoft
hehigherty
pe.
i
nt i
,x;
fl
oat f;
doubl
e d;
l
ong l
;
x= l / i+ i+ f - d
i
nt i
nt
l
ong f
loat doubl
e
f
loat doubl
e
i
nt doubl
e
i
fby t
e,shortandintv ar
iabl
esareusedi nanexpr essi
on,theresul
tisalway s
promotedtointtoavoidoverf
low.I
fasinglel
ongi susedint heexpr
ession,the
wholeexpr
essionispromotedtolong.I
fanexpressioncontainsafl
oatoperand,
theenti
reexpressi
oni spromotedtofloat
.Ifanyoper andisdouble,resultis
double.
Someotherf
oll
owingchangesareal
sointr
oduced
[Link]
ointcausestr
uncati
onofthefr
acti
onalpart
.
[Link]
oatcausesroundi
ngofdigi
ts.
[Link]
ngofexcesshigheror
derbi
ts.
Casti
ngaValue
Theprocessoflocalconv
ersi sknownascast
oni ingv
alue,i
.e.
,conv
ersi
onby
for
ce.
22
Sy
ntax:
(
type-
name)expr
essi
on
Ex.
:
r
ati
o = a/b
here,variablesaandbar edecl
aredasint
egersintheprogr
am,thedecimalpart
ofther esultofthedivisi
onwouldbelostandrat
iowouldnotrepr
esentacorrect
fi
[Link] oblem canbesolvedbyconv er
ti
nglocal
lyoneofthev ar
iabl
est o
thefloati
ngpoi ntas
r
ati
o = (
fl
oat
)a/b
Theoperator(fl
oat)conver
tstheat ofloat
ingpoi
nt,thenusi
ngtherul
eof
automati
cconversi
on,thedivi
sionisper
formedinfloati
ngpoi
ntmode,thus
ret
aini
ngthefr
acti
onalpar
tofresul
t.
Exampl
e r
esul
t
x =(
int
)7.
5 7
x =(
int
)21.
13/(i
nt)4.
5 21/4=5
x =(
doubl
e)sum/n fl
oati
ngpoi
nt
PrecedenceandAssoci ati
vit
yofoper ators
Eachoper atorinJavahasapr ecedenceassoci atedwithit
.Theoper ator
satthe
higherlevelofpr ecedence are evaluated f
[Link] operator
s oft he same
precedencear eeval
uatedeit
herfrom lefttori
ghtorf r
om righttolef
t,dependi
ng
ont [Link] heassoi cat
ivit
ypropertyofanoper ator
.The
foll
owinglistofoper
ators,
thei
rprecedencel evelandtheirr
ulesofassociati
on.
Oper
ator Associati
vi
ty
() l
efttoright
[] l
efttoright
++ ri
ghttoleft
-- ri
ghttoleft
* l
efttoright
/ l
efttoright
% l
efttoright
+ l
efttoright
- l
efttoright
< l
efttoright
<= l
efttoright
> l
efttoright
>= l
efttoright
== l
efttoright
23
!
= l
eftt
ori
ght
&& l
eftt
ori
ght
|
| l
eftt
ori
ght
Ex.
:
i
f(
x==10+15&&y<10)
Theprecedencerul
essaythatt
headdi
tionoperatorhasahigherpr
ior
it
ythant
he
l
ogicaloper
ator(
&&)andthenther
elat
ionaloperator
s(==and<).
Ther
efor
e,
i
f(x==25&&y<10)
Letussupposet
hatx=20,
y=5t
hen
x==25isfal
se
y<10istr
ue
Sincet
heoperator<hashi
gherpr
ior
it
ycompar
edt
o==,
y<10i
stest
edf
ir
stand
thenx==25istested.
Fi
nal
l
yweget
,
I
f(f
alse&&t
rue)
Ther
esul
tofcompl
excondi
ti
oni
sfal
se.
I
FStatement
Theifst
atementi
sapower f
uldecisionmakingstat
ementandi
susedt ocont
rol
thef
lowofexecut
ionofst
[Link]
cal
lyatwo-
waydeci
sionst
atement
.
Sy
ntex:
i
f(testexpressi
on)
{
st
atement-bl
ock;
}
st
atement -
x;
Thestatement -
blockmaybeasi ngl
estatementoragroupofstat
ements.I
fthe
testexpressioni strue,t
hestatement
-blockwil
lbeexecuted,other
wisethe
stat
ement -
blockwi l
lbeski
ppedandtheexecuti
onwil
lj
umptothestatement
-x.
Ent
ry
24
t
rue
t
est
expr
essi
on
?
f
alse St
atement
-bl
ock
St
atement–x
Nextst
atement
TheIF…ELSEst
atement
Synt
ax:
If(t
estexpr ession)
{
True-blockstatement;
}
else
{
False-blockstatement
;
}
stat
ement -x;
I
ft hetestexpressioni strue,t hent
hetr
ue-
blockstatement
(s)areexecuted,
other
wise,t
hef alse-blockst at
ement(
s)ar
eexecuted,andthen,thecontr
olis
tr
ansfer
redtothest atement-x;
Nesti
ngofI
F…ELSEst
atement
s
Synt
ax:
25
If(t
estcondit
ion-
1)
Stat
ement-1;
elseif(t
estcondi
tion-
2)
stat
ement-
2;
el
sei
f(t
estcondi
ti
on-
3)
stat
ement-
3;
…………….
.
…………….
.
el
se
defaul
t-
stat
ement
;
St
atement
-x;
Thi sconst
ructi
sknownast heelseifladder
.Theconditi
onsareevaluatedfrom
thet opoftheladdertodownwar [Link] hetr
uecondit
ionisf ound,the
statementassociatedwithitisexecutedandt hecontroli
st r
ansferr
edt ot he
statement-
x,skippi
ngther [Link]
false,t
henthefinal
elsecontai
ningthedefault
-st
atementwil
lbeexecuted.
TheSWITCHst
atement
Synt
ax:
swit
ch(expression)
{
casev alue-1:
block-
1
break;
casev alue-2:
block-
2
break;
……….
……….
default:
defaul
t-
block
break;
}
st
atement-x;
Theexpressi
onisani nt
egerorcharacter
,val
ue-1,val
ue-2….( i
.[Link]
withacolon( :
))areevaluatedsequenti
all
[Link] heswi tchi sexecuted,the
valueoft
heexpressionissuccessi
vel
ycompar edagainstthevalue-1,val
ue-2,……
i
facasei sfoundwhosev al
uemat cheswiththeval
ueoft heexpr essi
on,thenthe
blockofstatementsthatfoll
owst hecasear [Link] hesev al
ues
26
shoul
dbeuni quewithi
naswi tchstat
[Link]
ock1,bl
ock2….arej
avastatement
l
ist
sandmaycont ainzeroormor estat
[Link]
ementattheend
ofeachblocksignalstheendofapar t
icul
arcaseandcausesanexitfrom the
swit
chstatement,andtransf
erri
ngthecontr
oltothest
atement-
x.
The?
:oper
ator
Sy
ntax:
var
iabl
e=condi
ti
onalexpr
essi
on?expr
essi
on1:expr
essi
on2
Thecondit
ionalexpr
essi
oniseval
uatedfi
rst
.Ifthecondi
ti
oni str expr
ue, essi
on1
i
sevaluat
edandi fthecondi
ti
onisfal expr
se, ession2i
sevaluated.
Ex.
:
x=(
a>b)?a:
b;
i
f(a>b)i
str
uethen
x=a
ot
her
wise
x=b
TheWHI
LEst
atement
Sy
ntax:
I
nit
ial
i
zat
ion;
whi
le(
testcondit
ion)
{
bodyoft heloop
}
Thewhi l
ei sanent ry-
cont r
oll
edloopstatement .Thet estcondi t
ioni sev al
uated
andifthecondi ti
onistrue,thenthebodyoft heloopi [Link] t
erexecution
ofthebody ,
thetestconditi
onisonceagai nev al
uat edandi fitistrue, t
hebodyi s
executedonceagai [Link] sprocessofrepeatedexecut ionoft hebodycont inues
unti
lthet estcondit
ionfinal
lybecomesf al
seandt hecont rolistransf err
edoutof
[Link] t
,theprogram conti
nueswi t
ht hest atementi mmedi atel
yaf t
erthe
bodyoft heloop.
Ex.
:
………………….
………………….
27
sum =0;
n=1;
whil
e(n<=10)
{
sum =sum +n;
n=n+1;
}
Syst
[Link]
.pr
int
ln(
(“Sum =“+sum)
;
……………
……………
TheDOstat
ement
Synt
ax:
i
nit
ial
ization;
do
{
bodyoft heloop
}
whil
e( testcondit
ion);
Onreadingthedost at
ement ,theprogr
am proceedst oeval
uatethebodyoft he
l
oopf ir
[Link] heloop,thetestconditi
oni nthewhilestatementis
eval
uated.I
ftheconditi
oni str
ue,theprogram conti
nuestoeval
uatethebodyof
thelooponceagai [Link] i
nuesasl ongast heconditi
oni str
ue.
Whent heconditi
onbecomesf al
se,theloopwi l
lbet er
minat
edandt hecontr
ol
goestothestatementthatappearsimmediatel
yaf t
erthewhil
estatement.
TheFORst
atement
Synt
ax:
f i
or(ni
ti
ali
zat
ion;t
estcondi
ti
on;
incr
ement)
{
bodyoftheloop
}
Theexecuti
onoft heforstatementisasfollows:
1.I ni
ti
ali
zationofthecont r
olvari
abl
esisdonef i
rst.
[Link] al
ueoft hecontrolvar
iabl
eistest edusi
ngt hetestcondit
ion.
[Link] heloopisexecutedcont inueagainandagainbecauseofthe
contr
olv ari
[Link] ocesscontinuesti
llthev al
ueoft
he
contr
olvar i
ablefai
lstosati
sfythetestconditi
on.
Ex.
:
f
or(i
=1;
i<=100;
i++)
{
28
Sy
stem.
out
.pr
int
ln(
i)
;
}
TheBREAKst at
ementinloops
Thebreakstatementi
sencounter
edinsidealoop,
theloopi
simmediat
elyexi
ted.
Whent heloopsarenestedthebr
eakwoul donl
yexitf
rom t
heloopcont
aini
ngit.
Thati
s, t
hebreakwil
lexi
tonlyasi
ngleloop.
Ex.
:
1. while(
………..)
{
………
………
if(
conditi
on)
break;
……………
…………. .
}
……………
2. do
{
………
………
i
f(condi
ti
on)
br
eak;
……………
…………..
}whi
le(…………);
……………
3. for(
………..
)
{
………
………
i
f(condi
ti
on)
br
eak;
……………
…………..
}
……………
4. f
or(
………)
{
………
29
for(
………)
{
……………..
i
f(condi
ti
on)
br
eak;
……………
}
…………..
}
……………
CONTI NUEstat
ement
Unlikethebreakstat
ementwhichcausesthel
ooptobeterminated,thecont
inue
ast henamei mpli
es,causest
helooptobeconti
nueswit
hthenextiterat
ionaft
er
skippinganystatementsinbet
[Link]
nuestat
ementt el
lsthecompi l
er.
“Skipthefol
lowingst
atementandconti
nuewit
hthenextit
erat
ion”.
Ex.
:
1. while(
………..
)
{
………
………
if(
condit
ion)
cont
inue;
……………
…………..
}
……………
5. do
{
………
………
i
f(condit
ion)
cont
inue;
……………
…………..
}whi
le(…………);
……………
6. f
or(
………..
)
{
………
30
………
i
f(condit
ion)
cont
inue;
……………
…………..
}
……………
7. for(
………)
{
………
for(
………)
{
……………. .
i
f(condit
ion)
cont
inue;
……………
}
…………..
}
……………
LABELEDLoops
Alabeli
sanyval
idJavavari
abl
[Link]
veal
abelt
oal
oop,pl
acei
tbef
ore
thel
oopwit
hacolonattheend.
Syst
em:
bl
ock1: {
…………
…………
bl
ock2: {
………….
………….
.
}
}
Ex.
: bl
ock:f
or(
inti=1;
i<=100;i
++)
{
………….
…………
i
f(i
==99)
conti
nuebl
ock;
}
CLASS
A cl
assisauser-def
ineddat
at y
pewi t
hat emplat
ethatserv
est odefineits
pr
opert
[Link]
heclasst
ypehasbeendef
ined,
wecancreate“var
iabl
e”ofthat
31
typeusingdeclar
ati
ont hataresimilartothebasict ypedeclar
ati
[Link],
thesevari
abl
esaretermedasi nst
ancesofclasses,whicharetheact obj
ual ect
s.
Syntax:
ass cl
cl assname [ extendssuper
classname]
{
[vari
abledecl
arati
on];
[methodsdeclarati
on]
;
}
Every
thi
nginsi
dethesquarebr
acket
sisopt
ional
.Thi
smeanst
hatt
hef
oll
owi
ng
i
sv al
idcl
ass
class Empt
y
{
}
I
nstancevari
ables
Whatevervar
iablesaredeclar
edinsi
dethebodyofthecl
assdefi
nit
ionar
ecal
l
ed
i
nstancevari
ables–
cl
assRect angl
e
{
i
nta;
i
ntb;
}
TheclassRectanglecontai
nstwoint
egertpei
y nst
ancevar
iabl
es.
Methods
To add methods in a class is mostnecessaryformanipul
ati
ng t
he data
cont
[Link] hodsaredecl
aredinsi
dethebodyoftheclassbut
i
mmedi at
elyaft
erthedeclarati
onofinst
ancevari
abl
es.
Synt
ax:
Typemethodname( par
ameter-
li
st)
{
method- body
;
}
Met
hoddecl
arat
ionshavefourbasicparts:
Thenameoft hemet hod(methodname)
Thety
peoft heval
uet hemethodr et
ur t
ns(ype)
Ali
stofparameter
s( parameter
-l
ist)
Thebodyofthemet hod
Ex.
:
cl
assRect
angl
e
{
i
nta;
i
ntb;
32
v
oidget
dat
a(i
ntx,i
nty
)
{
a=x;
b=y ;
}
}
Ex.
:decl
ari
ngt
womet
hods
cl
assRect
angle
{
i
nta,b;
v
oidget
dat
a(i
ntx,i
nty
)
{
a=x;
b=y ;
}
i
ntr
ect
Area()
{
i
ntarea=a*b;
ret
urn(
area)
;
}
}
CREATINGOBJECTS
Thenew operatorisusedi nJavaf orcreat
inganObj
ectoft
hespeci
fi
edcl
ass
andret
urnsareferencetothatobject.
Synt
ax:
classname decl ared_name;
declared_name=new cl assname();
Ex.
:
Rectangl
e r
ect
1;
rect
1=new Rectangl
e()
;
Thef i
rstst
atementdeclar
esav ari
abl
et oholdtheobjectref
erenceandt
he
secondoneactual
l
yassignstheobj
ectr
efer
encetothev
ariabl
e.
Theabovebot
hstatement
scanbecombinedint
ooneas–
Rect
angl
er ect
1=new Rectangl
e();
Her
e,t
hemet
hodRect
angl
e()i
sthedef
aul
tconst
ruct
oroft
hecl
ass.
33
ACCESSINGCLASSMEMBERS
Si
nce outsi
de the cl
ass,we cannotaccess t
he i
nst
ance vari
abl
es and t
he
methodsdirect
[Link] hi
s,wemustuset heconcernedobjectandthedot
oper
atoras–
obj
ect
name.
var
iabl
e_name;
obj
ect
name.
methodname(par
amet
er-
li
st)
;
Ex.
:
r
ect
1.a=12;
r
ect
2.b=10;
r
ect
1.a=15;
r
ect
2.b=32;
and,
r
ect
[Link]
dat
a(12,
10)
;
r
ect
[Link]
dat
a(15,
32)
;
CONSTRUCTORS
Constr
uctorshavethesamenameast hecl
assi
tsel
f,andt
heydonotspeci
fya
ret
urntype,notevenvoi
[Link]
sisbecauset
heyr
eturnthei
nst
anceofthecl
ass
i
tsel
f.
Ex.
:
cl
assRect
angl
e
{
i
nta;
i
ntb;
Rectangl
e(intx,i
nty) /
/const
ruct
ormet
hod
{
a=x;
b=y ;
}
i
ntrectArea()
{
r
eturn(a*b);
}
}
I
NHERITANCE:EXTENDI
NGACLASS
Thei
nheri
tanceal
l
owssubcl
assest
oinher
ital
lthev
ari
abl
esandmet
hodsof
34
t
hei
rpar
entclasses.I
nheritancemayt akedi f
fer
entfor
ms:
Si
ngleinheri
tance(onl yonesuperclass)
Multi
pleinheri
tance( sever
alsuperclass)
Hier
archicali
nherit
ance( onesuperclass,manysubclasses)
Multi
l
ev eli
nherit
ance( deri
vedfrom aderivedcl
ass)
Defi
ningaSubclass
Synt
ax:
asssubcl
cl assnameextendssuper
classname
{
var
iabledecl
arati
on;
methodsdeclarat
ion;
}
Thekeywordextendssigni
fi
esthattheproper
ti
esofthesuper
classnamear e
ext
endedtothesubcl
[Link]
lnowcont
aini
tsownv ar
iabl
es
andmethodsaswellt
hoseofthesupercl
ass.
A A
B B C D
(
a)Si
ngl
einher
it
ance (
b)Hi
erar
chi
cal
inher
it
ance
A A B
(
c)Mul
ti
lev
eli
nher
it
ance (
d)Mul
ti
plei
nher
it
ance
Ex.
:
Cl
assRoom
{
35
i
ntl
,
b;
Room(
intx,
inty
)
{
l=x;
b=y ;
}
i
ntar
ea()
{
r
etur
n(l
*b)
;
}
}
cl
assBedRoom ext
endRoom
{
i
nth;
BedRoom(intx,i
nty,
intz)
{
super(x,
y);
h=z ;
}
i
ntv
olume()
{
r
etur
n(l
*b*h)
;
}
}
cl
assI
nher
Test
{
publ
icstati
cv oidmain(Str
ingar gs[
])
{
BedRoom r oom1=newBedRoom( 14,
12,
10)
;
Intarea1=r [Link]();
Intvolume1=r oom1. volume();
Sy st
em. out
.pri
ntl
n(“
Area1=“ +area1);
Sy st
em. out
.pri
ntl
n(“
Vol ume=“ +vol
ume`)
;
}
}
Subcl
assConstructor
Asubclassconstruct
orisusedt oconstr
ucttheinstancevar
iabl
eofboththe
subcl
assandthesuper cl
[Link]
assconstr
uctorusesthekeywor
dsuper
36
toinvoke the const r
uctormet hod oft he super
[Link] has fol
l
owing
condi
ti
ons:
supermayonl ybeusedwi thi
nasubclassconst r
uctormethod.
Thecal lt osuperclassconstruct
ormustappearast hefir
ststat
ement
withinthesubclassconst r
uct
or.
Thepar ametersint hesupercallmustmat cht heorderandtypeofthe
instancev ar
iabl
edecl ar
edinthesupercl
ass.
Mult
il
evelI
nherit
ance
Acommonr equi
rementinobj
ect
-or
ient
edpr
ogr
ammi
ngi
stheuseofader
ived
cl
assasasupercl ass.
A Super
class
B I
nter
medi
atesuper
class
C Subcl
ass
Thecl
assAserv
esasabaseclassf
ortheder
ivedclassBwhichi
nturnser
vesas
abasecl
assf
order
ivedcl
[Link]
nABCi sknownasinher
it
ancepath.
cl
assA
{
…………
…………
}
cl
assBextendsA /
/fi
rstl
evel
{
………..
………..
}
cl
assCextendsB /
/secondl
evel
{
…………….
…………….
}
Overr
idingMethods
Ex.
cl
assSuper
37
{
i
ntx;
Super
(i
ntx)
{
thi
s.x=x;
}
voi
ddispl
ay (
)
{
[Link]
.pr
int
ln(
“Superx=“+x)
;
}
}
cl
assSubextendsSuper
{
i
nty;
Sub(
intx,i
nty )
{
super(x)
;
thi
s.y=y;
}
voi
ddispl
ay (
)
{
[Link]
.pr
int
ln(
“Superx=“+x)
;
[Link]
.pr
int
ln(
“Suby=“+y);
}
}
cl
assoversi
deTest
{
publi
cstati
cv oidmain(
Stri
ngargs[
])
{
Subs1=newSub( 100,
200);
s1.
display(
);
}
}
Out
put
Superx=100
Suby=200
FinalVar
iabl
esandMethods
Allmethodsandvari
abl
escanbeov
err
iddenbydef
aul
tinsubcl
[Link]
his
thekeywordfi
nali
susedas:
38
f
inali
ntSIZE=100;
f
inalvoiddi
spl
ay(){……}
Makingamet hodfi
nalensuresthatthefunct
ional
i
tydefi
nedinthi
smethodwil
l
neverbeal t
eredinanyway .Si
mi l
arl
y,t
hev al
ueofaf i
nalvar
iabl
ecanneverbe
changed.
Fi
nalClasses
Aclassthatcannotbesubcl
assedi edaf
scal
l inalcl
[Link]
hist
hekey
wor
d
fi
nali
susedas:
f
inalcl
assAcl
ass
{
……………
……………
}
f
inalcl
assBcl
assext
endsSomecl
ass
{
……………
……………
}
Decl
ari
ngacl
assf
inalpr
event
sanyunwant
edext
ensi
onst
othecl
ass.
Abstr
actmethodsandCl asses
Ex.
:
abstr
actcl assshape
{
………………
………………
abstractvoi
ddr aw()
;
……………. .
…………….
}
Whil
eusingabstractclasses,wemustsati
sfythefoll
owi
ngcondit
ions:
Wecannotuseabst ractcl
assest
oinstant
iateobj
ect
sdir
ectly
.e.g.
,
Shapes=newShape(
);
isi
ll
egalbecauseshapei sanabst r
actcl
ass.
Theabstractmet hodsofanabst r
actcl
assmustbedef i
nedi
nitssubcl
ass.
Wecannotdecl areabst r
actconstruct
orsorabstr
actst
ati
cmethods.
Publi
cAccess
Anyvari
ableormet hodi svi
sibl
etot heentir
eclassinwhichi
tisdef
[Link]
wewantt omakei tv i
siblet
oal lt
hecl assesoutsi
dethiscl
ass?Thi
sispossibl
e
39
bysi
mplydecl
ari
ngthevari
abl
eormethodaspubl
ic.
Ex.
:
publ
ici
ntnumber;
publ
icv
oidsum(){……………..}
Av ari
abl
eormet hoddecl
aredaspubl
ichast
hewi
destpossi
blev
isi
bil
i
tyand
accessi
bleev
ery
where.
40