Core Java QBAns-1
Core Java QBAns-1
THANSWERS
PROGRAMMINGINCOREJAVAI
V
SEM BCA
UNITI
PARTA
Mult
ipl
eChoi
ce
Questi
ons
Simpl e,Smal l
andFami l
iar
Jav aisasmal landsimplel anguage.Jav adoesnotusepoi nters,preprocessorheader
fi
les,got ostatementandmanyot hers.Italsoel i
minatesoper atoroverl
oadingand
mul ti
pleinheri
tance.Jav aismodel ledonCandC++l anguages.Soi tisfamili
art
o
programmer s.
Mul ti
threadedandI nt
eractive
Mul ti
threadedmeanshandl ingmul tipl
et ask-simultaneously.Javasuppor tsmulti
thr
eadedpr
ogr
ams
Hi ghPer f
ormance
Jav aper f
ormancei si
mpr essiveforani nterpretedlanguage, mainlyduet otheuseof
i
nt ermediateby tecode.t
hei ncorporationofmul ti
threadi
ngenhancest heov er
all
executi
on
speedofJav apr ograms.
2.Explainthestructureofajavaprogram wit
hanexample.
AJav aprogram maycont ai
noneormor esecti
ons.
Document ati
onSect ion
Thedocument at
ionsectioncomprisesasetofcommentl i
nesgi
vingt
henameoftheprogr
am,the
authorandot herdet
ai l
s,
.Javapermitsboththesi
ngle-
li
necommentsandmul
ti
-l
inecomments.
/** */knownasdocument ationcomment .Thi
sfor
m ofcommenti
susedforgener
ati
ng
document ati
on
automatical
ly. LUI
PackageSt atement
Thef i
rstst at emental l
owedi naJav afileisapackagest atement .Thisstatementdecl ares
apackagenameandi nformst hecompi l
erthatthecl assesdef inedherebel ongt othi
s
package.Forex ampl e:packagest udent ;Thepackagest atementi soptional.
Impor tSt at ement s
Thenex tthingaf terapackagest atement( butbef or
eanycl assdef i
niti
onsmaybeanumberof
impor tst atement s. Forexampl eimpor tstudenttest.Thisst atementinstructsthe
interpretert ol oadt het estclasscont ainedint hepackagest udent.
InterfaceSt atement s
Ani nterfacei sl ikeacl assbuti ncludesagr oupofmet hoddecl arati
ons.Thi sisalso
an opt ionalsect i
on and i sused onl ywhen we wi sh t oi mplementt he mul t
ipl
e
i
nher it
ancef eat uresint heprogr am.
ClassDef ini t
ions
A Jav a pr ogr am maycont ain mul ti
ple class definit
ions.Cl asses aret he pr i
mar yand
essent ialel ement sofaJav apr ogram.
Mai nMet hodCl ass
Sinceev eryJav ast and-alonepr ogram requiresamai nmet hodasi tsstarti
ng
point ,thiscl assi stheessent i
al partofaJav aprogram.Asi mpl eJavapr ogram
maycont ainonl ythispart.
3. Expl
aint
hecont
ri
but
ionofJav
aVi
rt
ualMachi
nei
nexecut
ingaJav
apr
ogr
am.
All
languagecompi l
erstr
ansl
atesourcecodei ntomachi
necodef oraspecifi
ccomputer.Java
compileral
sodoest hesamething.TheJav acompil
erproducesani nt
ermedi
atecodeknownas
byt
ecodef oramachi net
hatdoesnotexist.Thismachi
neiscall
edt heJavaVirt
ualMachineand
i
texist
sonl yi
nsidethecomputermemor y.Iti
sasimulat
edcomput erwi t
hint
hecomputerand
doesallmajorfunct
ionsofarealcomput
er .
Thevir
tualmachinecodeisnotmachi
nespecifi
c.Themachi
nespeci
ficcodeknownasmachi
ne
code)isgener
atedbyt heJav
aint
erpr
eterbyact
ingasanint
ermedi
arybetweenthev
irt
ual
machineandther eal
machine.
3.Li
standExpl
aint
hedi
ff
erentdat
aty
pesusedi
nJav
a.
Ever
yvari
abl
ei nJavahasadat
atype.Datatypesspeci
fyt
hesizeandt y
peofval
uesthatcanbe
st
ored.Javalanguageisr
ichi
nitsdatat y
pes.Thev ari
etyofdatatypesav
ail
able,al
low t
he
pr
ogrammertoselectt
hety
peappr
opriat
etotheneedsoftheappl
icat
ion.
I
nt egerTy pes
Integertypescanholdwhol enumber ssuchas123, -96,and5639.Thesizeoft hevaluesthat
canbest oreddependsont heint
egerdatatypewechoose.
FloatingPointTypes
Integertypescanholdonl ywhol enumber sandt hereforeweuseanot hertypeknownasf loat
ingpoint
typet oholdnumber scont aini
ngfract
ionalpartssuchas27. 59and-
1.
Char acterType
Inor dertostorecharacterconstantsi
nmemor y,
Jav aprovi
desachar acterdat
at y
pecalledchar.The
chart ypeassumesasi zeof2by tesbut,basicall
y,i
tcanhol donlyasinglecharact
er.
Bool eanTy pe
Bool eantypeisusedwhenwewantt otestapar ti
cularconditi
ondur
ingtheexecut i
onoft heprogr
am.
Ther ear eonlytwov aluest hatabooleantypecant ake:trueorfal
se.
Thegeneral
for
m ofdeclar
ati
onofav ar
iabl
eis:
Avari
ablemustbedecl
aredbef
orei
tisusedinthepr
ogr
am.Av
ari
abl
ecanbeusedt
ost
orea
val
ueofanydataty
pe.
Vari
ablesar
esepar
atedbycommas,
Adecl
arat
ionst
atementmustendwi
thasemi
col
on,
Somev
ali
d
decl
arati
onsar
e:
i
ntcount;
fl
oatx,y;
doubl
epi;
6.Howdodi ff
erenttypesofoperator
sinJav
ahelpinwri
ti
ngapr ogr
am foranyt
ypeofappl
icat
ion?
Jav aoper at
orscanbecl assi
fi
edi
ntoanumberofr
elat
edcategor
iesasbelow:
1.Ar i
thmet i
coperators
2.Relat ionaloperat
ors
3.Logi cal operat
ors
4.Assi gnmentoper ators
5.Incrementanddecr ementoperat
ors
6.Condi ti
onaloperators.
7.Bitwi seoper at
ors
8.Speci aloperat
ors
7. Explai
nCommandLi neArgumentsinJavawi t
han
exampl e.COMMANDLI NEARGUMENTS
Theremaybeoccasi onswhenwemayl i
keourprogram t oacti
napar t
icul
arway
dependi ngontheinputprovi
dedattheti
meofexecut ion.Thisi
sachievedinJava
programsbyusi ngwhatar eknownascommandl i
near guments.Commandl ineargument
s
arepar ameterst
hataresuppli
edtotheappli
cati
onpr ogram atthet
imeofi nv
okingitf
or
execution.
Wecanwr i
teJavaprogramsthatcanrecei
veanduset heargument
spr ovi
dedinthecommandl
i
ne.
Compi l
eandr unt heprogr am wit
hthecommandl i
neasf oll
ows:
j
av aComLi neTestSi mpl eObject
_Ori
entedDi st
ri
butedRobustSecurePortabl
e
Mul ti
threadedDy nami c. Thenumberof
argument si sobtainedbyst atementcount=ar gs.
length;
Theoutputoftheprogr
am
woul dbeasf oll
ows: Numberofar gument s=8
1: Javai sSi mple!
2: Jav ais
Object _Oriented!3: Jav a
i
sDi stri
but ed!
4 : Jav a i s
Robust !5:Jav a
i
s Secur e! 6 :
Jav aisPor table!
7: Jav ais
Mul ti
threaded!8: Java
i
sDy nami c!
Not ehowt heoutputst atementconcatenatesthestri
ngswhilepr
int
ing.
8.Expl
ainthedif
ferentt
ypesoftokensi
n
Java.Javalanguageincl
udesfi
vety
pesoftokens.
Theyare:
•Reser
vedKey
wor
ds
•I
dent
if
ier
s
•Li
ter
als
•Oper
ator
s
•Separ
ator
s
.Key wor ds
Key wor dsar eanessent i
alpartofalanguagedef init
ion.Theyimplementspecificfeaturesofthe
language.Jav alanguagehasr eserved60wor dsaskey words.Thesekeywor ds,combi nedwi t
h
oper atorsandsepar atorsaccordingtosy nt
ax,form defini
ti
onoftheJav alanguage
Ident i
fi
ers
Identifi
ersar eprogrammer -desi
gnedt okens.Theyar eusedfornami ngclasses,met hods,vari
abl
es,
obj
ect
s,
labels,packagesandi nter
facesinapr ogram.
.
Literals
LiteralsinJav aareasequenceofchar acters(di
gits,let
ter
s,andothercharacters)thatrepresent
const antv aluestobest or
edi nvari
ables.Javalanguagespeci f
iesfi
vemaj ortypesofl i
teral
s.
Theyar e:
Integerl i
terals
•Fl oat i
ngpoi ntli
teral
s
•Char
act
erl
i
ter
als
•St
ri
ngl
i
ter
als
•Bool eanlit
eral
s
• Oper at
ors
Anoper at
orisasy mbolthattakesoneormor eargumentsandoper
atesont hem t
opr oducearesul
t.
Separators
Separator
sar esymbolsusedt oi ndi
cat
ewheregroupsofcodear
edividedandarranged.They
basical
lydefi
netheshapeandf uncti
onofourcode.Someoftheseparator
sareparentheses()
,
braces{},
bracket
s[],
semi col
on; comma, per
iod.
11.Compareandcont r
astJavaandC++.
•Jav adoesnotsupportoper
atorover
loading.
•Jav adoesnothavetemplat
eclassesasi nC++.
•Jav adoesnotsupportmult
ipl
einher
itanceofcl
asses.Thi
sisaccompl
i
shedusi
nganew
featurecal
l
ed"int
erf
ace".
•Javadoesnotsuppor
tglobal
var
iabl
es.Ev
eryv
ari
abl
eandmet
hodi
sdecl
aredwi
thi
nacl
assand
for
mspartofthatcl
ass.
•Jav
adoesnotusepoi
nter
s.
•Jav
ahasrepl
acedt
hedestruct
orf
unct
ionwi
thaf
inal
i
ze()
funct
ion.
•Ther
ear
enoheaderf
il
esi
nJav
a.
12. Li
standt heexpl
aintheusageofdi
ffer
enttypesofv
ari
abl
est
hatar
eusedi
naJav
apr
ogr
am.
Javavar
iabl
esareactuall
yclassi
fi
edint
othr
eekinds:
i
nst
ance
v
ari
ablesclass
v
ari
ableslocal
v
ari
ables
I
nst anceandcl assv ari
ablesar edecl aredi nsideacl ass.Instancev ariablesar ecr eat edwhen
theobj ectsareinst anti
atedandt hereforet heyar eassoci atedwi t
ht heobj ects.Theyt ake
diff
erentv al
uesf oreachobj ect.Ont heot herhand, classv ariablesar e' global t
oacl assand
belongt otheent i
r esetofobj ectst hatcl asscr eat es.Onl yonememor yl ocationi scr eat edfor
eachcl assv ari
able.
Variablesdeclaredandusedi nsi demet hodsar ecalledl ocalv ari
ables.Theyar ecal ledso
becauset heyar enotav ail
ablef oruseout sidet hemet hoddef ini
ti
on.Local variablescanal so
bedecl aredinsidepr ogram bl ockst hatar edef inedbet weenanopeni ngbr ace{andacl osi
ng
brace} .Thesev ariablesar evisiblet othepr ogr am onl yfrom t hebegi nni ngofi tspr ogr am block
totheendoft hepr ogr am block.Whent hepr ogr am cont r
olleav esabl ock, al
l t
hev ariablesin
thebl ockwillceaset oex ist.Thear eaoft hepr ogr am wher et hev ariablei saccessi blei scall
ed
isscope.
t
I
nJav a,everyvariablehasadef aultv alue.I fwedon' tiniti
ali
zeav ariablewheni tisf i
rstcr eated,
Jav
a
prov i
desdefaultv aluet othatv ariablet ypeaut omat icall
y .
UNITI
I
PARTA
Mult
ipl
eChoi
ce
Questi
ons
1.Whichofthefol
l
owi
ngst
atement
swi
l
lresul
tinani
nfi
nit
eloop?
A.for(
;;
);
B.for
(i=0;
i
<1;i
--
)
C.for
(i=0;
;
i++)
D.allt
heabov e
2.I
nJav a canonl ytestf
orequal i
ty,wher eas canev aluateanyt ype
ofBool eanex pression.
A.switch, if
B.if
,swi t
ch
C.switch, break;
D.if
,cont inue
3.Whichoft hefoll
owi ngisanoper atorusedf orconditionalbranchi nginJav a?
A.{}
B.?:
C.>[]
D.<()
4.Whichoft hefoll
owi ngloopisusedwhent henumberofi ter
ationsar eknown?
A.while
B.if
C.for
D.do-whi le
5.Whichoft hefoll
owi ngisanexitcont r
oll
edl oop?
A.while
B.do-whi le
C.switch
D.for
6.Whichoft hefoll
owi ngisanentrycont r
olledl oop?
A.do-whi le
B.switch
C.if
D.while
7.Namet hebui l
t-i
nmul t
i-
waydecisionstatementi nJava.
A.if
B.if
-else
C.switch
D.do-whi le
8.Anear l
yex i
tfrom al oopcanbeaccompl ishedbyusi ngt he _ st atementinJava
A.cont i
nue
B.break
C.switch
D.goto
9.Whichst at
ementi nJav acausest heloopt obecont inuedwi tht henex ti
terat
ionaf
terski
ppi
nganyst
atement
sin
between?
A.break;
B.goton;
C.cont inue;
D.switch
10.Thedatai
temsi
nJav
aar
eknownas
A.var
iables
B.methods
C.f
unctions
D.f
iel
ds
QuestionsbasedonSki
ll
11.The act
sasatemplatef
oranobject
A.class
B.state
C.behav ior
D.fiel
d
12.A i
nJav ai
sauser
-def
ineddat
atypewithatemplat
ethatser
vest
odef
inei
tspr
oper
ti
es.
A.object
B.class
C.met hod
D.funct i
on
13.The keywordi
nJavaisusedtoi
mplementinher
it
ance
A.impl ement
s
B.extends
C.runnabl e
D.D.cat ch
14.
The
variabl A.membe
est hat
are
declar
ed
insi
de
a
class
are
call
ed
A.instan
ce
var i
abl
es
B.class
variabl
es
C.object
memb
ers
D.D.
object
variabl
es
15.Instan
ce
variab
les
are
also
know
nas
r at
ionmeansthatthemet
hoddoesnotr
etur
nanyt
hing.
var iabl A.priv
ate
es B.publi
c
B.class C.void
var i
able D.D.int
s 19.Theparamet
erli
stinamethodar
eencl
osedin
C.obj ect A.[]
membe B.{
rs }
D.D.
C
obj ect
.
var i
able
s (
16. )
are D
also .
known <
as >
memb
er
var i
abl
esi n
Jav a.
A.i
nst anc
e
var iabl
es
B.class
var i
able
s
C.obj ect
membe
rs
D.D.
obj ect
var i
able
s
17.Any
met ho
d
decl ar
ation
i
na
Jav a
class
consi s
tsof
par ts
A.two
B.three
C.four
D.D.f i
ve
18.The
key wor
di na
met ho
d
decl ar
20.Object
s oper
atori
nJav
aisusedt
oaccesst
hecl
assmember
s
i
n
Java
are
creat
e
d
using
the
operat
or
A.{}
B.()
C.New
D. D.add
21.The
A.?
B.->
C.dot
D.new
22.The areusedtogiveini
ti
alvaluestomember sinaclass
inJav aA.const r
uctor
B.friend
C.finally
D.Runnabl e
23.InJav aiti
spossibletocreatemethodsthathav et
hesamename, butdiff
erentpar
amet
erl
i
stsanddi
ff
erent
defi
ni t
ions.Thi sconcepti
scalled
A.inher i
tance
B.ov erloading
C.Encapsul ati
on
D.D.Abst r
action
24. aremet hodsinJavathatcanbecal l
edwithoutusingtheobject
s.
A.st ati
cmet hods
B.ov erl
oadedmet hods
C.const ructors
D.D.dest ructors
25.Ast ringisgenerall
yasequenceofchar acters.But
,inJav
a, i
tistr
eatedas
A.buf fer
B.obj ect
C.class
D.Package
LongAnswerQuest
ion
1.
Explai
nsimplei
fst
atementi
nJavawi
thanexampl
e.Thegener
al
f
orm ofasi
mplei
fstat
ementi
s
The'statement-
block'maybeasinglestatementoragr oupofst at
ements.Ifthetest
expressi
onist r
ue,thestat
ement-
blockwillbeexecuted;otherwi
sethestatement -
blockwil
lbe
ski
ppedandt heex ecuti
onwil
ljumptot hestat
ement -
x.Itshouldberemember edthatwhenthe
conditi
onistrueboththestat
ementblockandthest atement-xareexecut
edi nsequence.
Consideracasehav
ingtwotestcondi
ti
ons,onef
orwei
ghtandanot
herforhei
ght.Thi
sis
doneusingthecompoundrel
ati
onif(wei
ght<50&&height
>170)count=count+1;Thi
s
wouldhave
beenequival
entl
ydoneusingtwoifstat
ementsasfol
lows:i f(
weight<50)if(
height
>170)count
=count+l
;
Ift
hev al
ueofweightisl
essthan50,thenthef
oll
owingstatementisexecuted.Whichintur
nis
anotheri
fstatement
.Thisi
fstatementtest
shei
ghtandiftheheighti
sgreaterthan170,thenthe
countisi
ncrementedby1
2. HowwouldyouExpl
aini
f-elsest
atementi
nJavawi t
hanexample.
Thei
fel
sest
atementi
sanextensionofthesi
mpleifst
atement
.Thegener
alf
ormi
s
3.Ill
ust
ratetheusageof/elseifl
adderi
nJavawi t
hanexampl e.
Therei
sanotherwayofputti
ngifst
ogetherwhenmul
tipathdeci
sionsar
einvolved.Amult
ipat
hdecisi
on
i
sachainofifsinwhichthest
atementassoci
atedwi
theachelseisanif.I
ttakesthef
oll
owinggeneral
for
m
Theconst ructisknownast heel seifladder.Thecondi t
ionsareevaluatedfrom t
het op(oftheladder
),
downwar ds.Assoonast het ruecondi t
ionisf ound, t
hestatementassociatedwithitisexecutedand
thecont rolistransferredt ot hest atement -
x( skippi
ngt herestoftheladder).
whenal lt
hencondi ti
ons
becomef alse, t
hent hef i
nal el secontainingthedef aul
t-st
atementwi l
lbeexecuted.
Consi deranex ampl eofgr adi ngt hestudentsi nanacademi cinst
ituti
on.Thegradingisdone
accor di
ngt ot hefollowingr ules:
Av eragemar ksGr ade80t o100Honour s
60t o79Fi r
stDi vi
sionSOt o59SecondDi vi
sion40t o49Thi rdDiv
ision0
to39Fai l
Thisgr adingcanbedoneusi ngt heelsei fl
adderasf oll
ows~
i
f (
mar ks>-79)gr ade=" Honour s";el
sei f(marks>59)gr ade=
"FirstDivi
sion";elseif(mar ks>49)gr ade=" SecondDi visi
on";
elseif(mar ks>39)gr ade=" Thi rdDivisi
on";elsegr ade=
"Fail"
;System. out.pri
ntln(
"Gr ade: "+gr ade);
4. Howistheswitchstat
ementsimi
lart
oelse-
ifst
atementi
nJav
a?Expl
ainwi
thanexampl
e.
Thegeneralf
orm oftheswit
chst
atementi
sasshownbelow:
Whent heswitchi
sexecuted,
thev al
ueoft heexpressi
onissuccessi
velycompar edagainsttheval
ues
val
ue- l
,val
ue-2,I
facaseisfoundwhosev aluematcheswit
ht heval
ueoft heexpr essi
on,thent
heblock
ofstatementsthatf
oll
ows
thecasear eexecut
ed.Thebr eakstatementattheendofeachbl ocksignalstheendofa
part
icularcaseandcausesanexi tfr
om theswitchst atementExample:
-
4.Explai
ntheworki
ngofwhi
leloopinJavawit
hanexample.
Thesimplestofal
lthel
oopi
ngst
ructur
esinJavai
sthewhi
lest
atement
.Thebasi
cfor
matoft
he
whil
estatementis
Thewhi l
eisanentry-cont
roll
edloopstatement .Thetestcondi
ti
oni sev
aluatedandi fthecondit
ioni
s
tr
ue,thenthebodyoft heloopisexecuted.Afterexecuti
onofthebody ,
thet estcondit
ionisonceagain
eval
uatedandi fi
tistrue,
thebodyi sexecutedonceagai n.Thi
sprocessofr epeatedexecuti
onofthe
bodycontinuesunti
l t
hetestcondit
ionfinal
l
ybecomesf alseandthecont r
olistransf
erredoutofthe
1oop.Onex it
,theprogram cont
inueswiththest at
ementi mmediatel
yafterthebodyoft heloop.
Exampl
e;
-
6.
Howwoul
dyouexpl
aint
heusageofaf
orl
oopi
nJav
awi
thanexampl
e.
Theforl
oopi herent
sanot r
y-cont
rol
l
edl
oopt
hatpr
ovi
desamor
econci
sel
oopcont
rol
str
uct
ure.
Thegeneral
for
m ofthef
orloopis
Theex ecuti
onoftheforstat ementisasf oll
ows:
1.Ini
ti
ali
zati
onofthecont rolvari
ablesisdonef i
rst
,usingassignmentstatementssuchasi=1and
count=o.Thev ar
iablesi andcountar eknownasl oop-controlvar
iabl
es.
2.Thev al
ueofthecontrolv ari
ablei
st estedusi
ngt hetestconditi
on.
3.Whent hebodyofthel oopi sexecuted,thecontr
olistransf
erredbacktotheforstat
ementaf
ter
eval
uatingthel
aststatementi nthel oop. Exampl e:-
7.Expl
aint
hedo-whil
eloopinJavawi thanexampl e.
Thewhil
eloopconst
ructmakesat estcondi
tionbefor
etheloopi sexecut
ed.Ther efore,t
hebodyof
thel
oopmaynotbeex ecut
edatallifthecondit
ionisnotsati
sfiedatthever
yfirstattempt.On
someoccasionsi
tmightbenecessarytoexecutethebodyoft heloopbefor
et het estisper
for
med.
Suchsi
tuat
ionscanbehandledwit
ht hehelpofthedost at
ement .Thi
stakesthefor m:
Consi
dert
heexampl
e:-
Cany
7. ouj
ust
if
ytheusageofobj
ect
sinJav
awi
thanexampl
e.
Any t
hingwewi shtor epr esentinaJav aprogram mustbeencapsul atedinacl assthatdefi
nest hest
ateand
behav i
ourofthebasi cpr ogr am component sknownasobj ects
Anobj ectinJav aisessent iallyablockofmemor yt hatcontainsspacet ostoreallt hei
nstancev ari
abl
es.
Creati
nganobj ectisalsor ef erredtoasi nstant
iati
nganobj ect.
Obj ectsinJavaar ecr eatedusi ngthenewoper ator.Thenewoper at
orcreatesanobj ectofthespecif
ied
cl
assandr eturnsar eferencet othatobject.Hereisanex ampl eofcr eati
nganobj ectoftypeRect angl
e.
Rectangler ect1//decl arer ect1=newRect angle()//i nstant i
ateRectanglerect1=newRect angle();
Themet hodRect angle()i sthedefaultconst r
uct oroft
hecl ass.Wecancr eateanynumberofobj ectsof
Rect angle.
Ex
ampl
e:-
Cany
8. oui
ll
ust
rat
etheconceptofconst
ruct
orsi
nJav
a.
Allobject
sthatarecr eat
edmustbegi venini
ti
alvalues.Wecandot heseusingt woapproaches.The
fir
stapproachusest hedotoperatortoaccesst heinstancevari
ablesandt henassi gnsval
uestothem
indiv
idual
ly.I
tcanbeat edi
ousappr oachtoinit
ial
izeallthevar
iablesofalltheobjects.
Thesecondappr oacht akesthehelpofamet hodli
keget Datat
oi nit
ial
i
zeeachobj ecti
ndiv
idual
lyusing
st
atement sli
ke,r
ect1.getData(15,
lO);
Itwouldbesimpl erandmor econcisetoiniti
ali
zeanobj ectwhenitisfir
stcr eat
ed.Javasupportsa
specialty
peofmet hod,cal
ledaconst r
uctorthatenablesanobjecttoinit
iali
zeitselfwheniti
screated.
Constr
uctor
shavethesamenameast hecl
assit
sel
f.Theydonotspecif
yareturnt
ype,
notevenvoi
d.
Thisi
sbecausetheyret
urnthei
nst
anceofthecl
assit
self
.
Letusconsi
derourRectangl
ecl
assagai
n.Wecannowr eplacet
hegetDatamethodbyaconstr
uct
or
methodasshownbelow:
10.Explai
ntheconceptofmet hodov erl
oadinginJav awi t
hanexampl e.
I
nJav aiti
spossibl
etocreatemet hodst hathavethesamename, butdiff
erentpar
amet
erl
ist
sand
dif
fer
entdefi
nit
ions.Thi
siscalledmet hodov erl
oading.Methodov
erloadi
ngisusedwhenobj
ect
sare
requi
redtoperf
orm simi
lartasksbutusi ngdiff
erentinputpar
ameter
s.
exampleofcreat
inganoverloadedmet hod.
Here,wear eoverl
oadingt
heconstruct
ormethodRoom ()
.Anobjectrepr
esenti
ngarect
angul
arr
oom wi
l
lbe
createdasRoom r oom1=newRoom ( 25.
0,15.0)
;//
usi
ngconstr
uctor
Ont heotherhand,ift
heroom i
ssquare,t
henwemaycr eatet
hecorrespondi
ngobj
ectasRoom r
oom2=
newRoom ( 20.0)
;//usingconstr
uctor
2
11.
Cany
ouexpl
aint
heconceptofst
ati
cmember
sinJav
aal
ongwi
tht
hei
rli
mit
ati
ons.
12. Howcany
ouexpl
aint
heconceptofwor
kingwi
thcl
assesi
nJav
a?Just
if
ywi
thanexampl
e.
Acl assisauser-
defi
neddatat y
pewi
thatempl
atethatserv
estodefi
nei
tsproper
ti
es.Oncet
he
classtypehasbeendefined,wecancr
eat
e"var
iabl
es"ofthatt
ype.I
nJav
a,thesevar
iabl
esar
e
termedasi nst
ancesofclasses,
whi
charetheactualobj
ect
s.Classesprovi
deaconveni
entmethodforpacki
ngtoget
heragroupof
l
ogi
cal
lyrel
ateddatait
emsandf uncti
onsthatwor
konthem.InJava,thedat
ait
emsar ecal
l
ed
f
iel
dsandthefuncti
onsarecaledmet
l hods
Thebasi
cform ofaclassdefi
nit
ionis:
Ever
ythinginsidethesquar
ebr
acket
sisopt
ional
.Thi
smeanst
hatt
hef
oll
owi
ngwoul
dbeav
ali
dcl
ass
defi
nit
ion:classEmpty
{
}
Exampl e;
-
13.Compar
eandcont
rastwhi
lel
oopwi
thdo-
whi
lel
oop
Whil
eloop
Thesimpl
estofal
lthel
oopi
ngst
ruct
uresi
nJav
aist
hewhi
l
est
atement
.Thebasi
cfor
matoft
he
whil
estat
ementis
Thewhi l
eisanentr
y-cont
roll
edloopstatement.Thetestcondi
ti
onisev
aluat
edandi fthecondit
ioni
s
tr
ue,t
hent hebodyoftheloopisexecuted.Af
terexecuti
onofthebody,
thetestcondit
ionisonceagai
n
eval
uatedandifiti
s
true,
thebodyisex ecutedonceagain.Thi
spr
ocessofrepeat
edexecuti
onoft hebodycont
inuesunt
il
thetestcondi
tionfinal
lybecomesfalseandt
hecontr
olistr
ansf
err
edoutoft he1oop.Onexit,t
he
program cont
inueswi t
hthestat
ementi mmedi
atel
yaft
erthebodyoftheloop.Example;
-
Do-
whi
l
e
Thewhil
eloopconst
ructmakesat estcondi
tionbefor
etheloopi sexecut
ed.Ther efore,t
hebodyof
thel
oopmaynotbeex ecut
edatallifthecondit
ionisnotsati
sfiedatthever
yfirstattempt.On
someoccasionsi
tmightbenecessarytoexecutethebodyoft heloopbefor
et het estisper
for
med.
Suchsi
tuat
ionscanbehandledwit
ht hehelpofthedost at
ement .Thi
stakesthefor m:
Exampl
e:-
UNITI
II
PARTA
Mult
ipl
eChoi
ce
Questi
ons
Compar
1. eandcont rastoverloadingandov erri
dingmet hodsinJavawithexamples?
I
nJav aiti
spossibletocreatemet hodst hathavethesamename, butdi
ff
erentpar
ameterl
i
stsand
dif
fer
entdefi
nit
ions.Thisiscalledmet hodov erl
oading.Methodoverl
oadi
ngisusedwhenobject
sare
requi
redtoperf
orm similartasksbutusingdi ff
erentinputpar
ameters.
exampleofcreat
inganov erloadedmet hod.
Methodinheri
tanceenabl
esust odefi
neandusemet hodsr
epeatedl
yinsubclasseswi
thouthavingtodef
ine
themethodsagaininsubclass.Howev er,t
heremaybeoccasi
onswhenwewantanobj ecttorespondtothe
samemet hodbuthav edi
fferentbehaviourwhent
hatmethodiscall
ed.Thatmeans,weshouldov er
ri
dethe
methoddefinedinthesuperclass.
Outputofabov
ePr
ogr
am i
s:
Superx=100
Suby=200
2.Cany
ouExpl
ainsi
ngl
elev
elofi
nher
it
ancewi
thanexampl
e?
Themechani sm ofder
ivi
nganewcl assfr
om anol doneiscal
ledinheri
tance.Theoldclassisknownas
thebaseclassorsuperclassorparentcl
assandt henewonei scall
edthesubcl assorderi
vedclassor
chil
dclass.
Theinheri
tanceal
lowssubclassestoinher
ital
lthev ar
iabl
esandmet hodsoft hei
rparentcl
asses.
Inher
it
ancemayt akedif
ferentfor
ms:
Pr
ogr
am gi
venbel
owshowsAppl
i
cat
ionofsi
ngl
einher
it
ance
Theconstr
uctori
ntheder
ivedcl
assusest
hesuperkey
wor
dtopassv
aluest
hatar
erequi
redbyt
hebase
const
ruct
or.
Thestat
ement
BedRoom r
oom1=newBedRoom (
14,
12,
10)
;
Di
3. scussaboutAbst
ractmet
hodsandabst
ractcl
assesi
nJav
a.
Wecani ndicat
ethatamethodmustal
waysberedef
inedi
nasubcl
ass,'
thusmaki
ngov
err
idi
ngcompul
sor
y.
Thisi
sdoneusi ngthemodif
ierkey
wor
dabstr
actint
hemethoddef
ini
ti
on.
Example:
abstr
actclassShape
{
ABSTRACTMETHODSANDCLASSES
….
.……
.
.………
abst
ractv
oiddr
aw(}
;
.
..…..
..
..
}
Whenacl asscont
ainsoneormor eabstractmethods,i
tshouldal sobedecl
aredabstractasshownint
he
exampleabove.Whi
leusingabstractclasses,wemustsat i
sfythef ol
l
owingcondit
ions:
Wecannotuseabst r
actclassestoinstanti
ateobject
sdirect
ly.Forexample,Shapes=newShape()i s
i
ll
egalbecauseshapeisanabst r
actclass.Theabst r
actmethodsofanabst ractcl
assmustbedef i
nedi
n
i
tssubclass.Wecannotdeclareabstractconstr
uctors10rabstractstat
icmethods.
Expl
4. aint
heusageoff
inal
izer
()met
hod?
Javasupportsaconceptcal l
edfinali
z ati
on,whichisjustopposi tetoini
tial
i
zation.Javarun-
ti
mei san
aut
omat icgarbagecoll
ecti
ngsy stem.I tautomaticall
yfreesupt hememor yresourcesusedbytheobj ect
s.
Butobjectsmayholdot hernon-objectresourcessuchasf il
edescr i
ptorsorwindowsy stem f
onts.The
gar
bagecol l
ectorcannotfreetheser esources.Inordertof reetheseresourceswemustuseaf i
nalizer
method.Thisissimil
artodest r
uctorsi nC++.Thef inal
izermet hodissimplyf i
nali
ze()andcanbeaddedt o
anycl
ass.Jav acall
sthatmet hodwhenev eriti
saboutt or eclai
mt hespacef orthatobject
~Thef i
nali
ze
methodshouldex pl
ici
tl
ydef i
nethet askst o'beperformed.
Howdoest
5. hest
ri
ngcl
assdi
ff
erf
rom st
ri
ngbuf
fercl
ass?Gi
vet
hesy
ntaxanduseof
f
oll
owi
ngmet
hod
i) i ndexOf(
)ii
)subSt
ri
ng()i
ii
)i
nser
t()iv)
set
CharAt
()
Str
ingmani pul
ati
onisthemostcommonpar tofmanyJavapr
ogr
ams.St
ri
ngsr
epr
esentasequenceof
charact
ers.
Stri
ngsmaybedeclar
edandcreatedasfol
l
ows:
St
ri
ngBuf
ferisapeercl
assofSt ri
ng.WhileSt
ri
ngcreat
esst
ri
ngsoffi
xed_l
ength,
St
ri
ngBuf
fercreat
esstr
ingsoff
lexibl
elengtht
hatcanbemodif
iedi
nter
msofbot hl
engthandcontent
.
Wecani nser
tcharactersandsubstr
ingsi
nthemi
ddleofastr
ing,orappendanotherst
ri
ng
totheend.
6. Cany
oui
ll
ust
rat
ethei
mpor
tanceofv
ect
orsi
nJav
a?Thr
owl
i
ghtont
hedi
ff
erentmet
hods
usedi ni
mplementi
ngv ect
orsinJavawit
hexampl es
Javadoesnotsupportt
heconceptofvari
ableargument
st oaf
uncti
on.Thi
sf eat
urecan
beachievedinJavat hroughtheuseoft heVect orcl
asscontai
nedint hejava.uti
l
package.Thi
sclasscanbeusedt ocr eat
eagener icdynami
carrayknownasv ector
t dobj
hatcanhol ect
sof
anyt ypeandanynumber .Theobject
sdonothav etobehomogenous.Arrayscanbeeasil
y
i
mpl
ement
edasv
ect
ors.Vect
orsar
ecr
eat
edl
i
kear
ray
sasf
oll
ows:
7. I
ll
ust
rat
ewi
thexampl
est
heconceptofwor
kingwi
thar
ray
sinJav
a.
Anarrayisagr oupofcont i
guousorrel
ateddatait
emst hatshar
eacommonname.Whi lethe
complet
esetofv al
uesisref
err oasanar
edt r
ay,theindi
vi
dualval
uesar edel
ecal
l ement
s.Ar
rays
canbeofanyv ari
ablety
pe.Arraysi
nJavamaybedeclaredintwoforms:
Form1typearr
ay name[];
Form2type[]arrayname;
Exampl
e;
-
Thefinalst
epistoputval
uesint
othear
raycreat
ed.Thi
spr sknownasi
ocessi nit
ial
i
zat
ionThi
sis
doneusingthear
raysubscr
ipt
sasshownbelow.
Expl
8. ainwhyweshoul
dusewr
appercl
assesi
nJav
a.
Vector
scannothandlepri
miti
vedatat y
pesli
keint,f
loat,long,char,anddouble.Pri
mi t
ivedata
ty
pesmaybeconv ert
edint
oobjectty
pesbyusingthewr apperclassescont
ainedinthejava.Lang
package.Wr
apperCl
assesforConver
tingSi
mpleTypes
Thewrappercl
asseshaveanumberofuni
quemethodsf
orhandli
ngpr
imit
ivedat
aty
pesandobj
ect
s.
Conv
erti
ngPrimit
iveNumber
stoObjectNumber
sUsingConst
ruct
orMethods
Conv
ert
ingObj
ectNumber
stoPr
imi
ti
veNumber
sUsi
ngt
ypeVal
ue(
)met
hod
Expl
9. aint
hedi
ff
erentmet
hodsav
ail
abl
einSt
ri
ngcl
asswi
thanexampl
es. Some
MostCommonl
yUsedSt
ri
ngMet
hods
10. Expl
aint
hev
ari
oust
ypesofi
nher
it
ancewi
thexampl
es.
Theinherit
anceal l
owssubcl assestoi nheri
tall
thev ar
iablesandmethodsofthei
rpar
entclasses.
I
nheri
tancemayt akediff
erentforms:
•Singleinheri
tance(onlyonesuper class)
•Multipleinheri
tance(severalsuperclasses)
•Hierarchi
cal i
nherit
ance(onesupercl ass,manysubclasses)•Mul
ti
level
inher
it
ance(Der
ivedfrom ader
ivedcl
ass)
Si ngl
einher i
tance
Themechani sm ofder i
vinganewcl assfr
om anol doneiscal
ledinheri
tance.Theoldclassisknownas
thebasecl assorsupercl assorparentcl
assandt henewonei scall
edthesubcl assorderi
vedclassor
childclass.
Thei nherit
anceal l
owssubcl assestoinher
ital
lthev ar
iabl
esandmet hodsoft hei
rparentcl
asses.
Inherit
ancemayt akedi ff
erentfor
ms:
Singleinherit
ance( onlyone
super class)Mul t
ipl
ei nheri
tance
Javadoesnotsuppor tmul t
ipl
einherit
ance.Thatis,cl
assesi nJavacannothav emor ethanone
superclass.Fori nstance,adefiniti
onli
ke
classAex t
endsBext endsC
{
----
--
---
-
}
.Javapr ovidesanal t
ernateapproachknownasi nter
facest osupporttheconceptofmul ti
plei
nheri
tance)
Hier
archicali
nheritance
Anotherinterest
ingappl i
cati
onofi nher
it
anceistouseitasasuppor ttothehier
archi
caldesignofa
program Asanexampl e,AboveFigureshowsaHi er
archi
cal cl
assi
fi
cati
onofaccountsinacommer ci
al
bank.Thi si
spossi blebecausealltheaccountspossescertaincommonf eat
ures.
Mult
il
eveli
nheri
tance
Acommonr equir
ementinobj
ect
-or
ientedpr
ogrammingi
stheuseofaderi
vedcl
assasasupercl
ass.Jav
a
support
sthisconceptandusesi
textensi
vel
yinbui
l
dingi
tscl
assli
brar
y.
11.Howdoy
ouachi
evemul
ti
plei
nher
it
ancei
nJav
a?Suppor
tyouranswerwi
thanexampl
e.
Javadoesnotsupportmult
ipl
einher
it
ance.Thati
s,cl
assesi
nJav
acannothav
emor
ethanone
super
class.Fori
nst
ance,
adefini
ti
onli
ke
cl
assAex t
endsBext endsC
{
--
--
--
--
-- }
Alargenumberofr eal-
li
feappli
cati
onsr
equiret
heuseofmult
ipl
einher
it
ancewher
ebywei nher
it
methodsandpr operti
esfrom sever
aldi
sti
nctcl
asses.Jav
apr
ovi
desanalter
nat
eapproachknownas
i
nter
f acestosupporttheconceptofmult
ipl
einher
it
ance
Thegener
alf
orm ofani
nter
facedef
ini
ti
oni
s
Her
eisanexampl
eofani
nter
facedef
ini
ti
ont
hatcont
ainst
wov
ari
abl
esandonemet
hod
12. Cany
ouexpl
aint
hei
mpor
tanceofv
isi
bil
it
ycont
rolmodesi
nJav
awi
thexampl
es
Visibi
li
tycont rol
isusedt orestr
icttheaccesstocertainvariabl
esandmethodsfrom outsi
detheclass.
javapr ovi
dest hreetypesofv i
sibi
li
tymodifi
ers:publ
ic,pri
vateandprot
ect
ed.Theypr ovi
dedif
ferent
levelsofpr otect
ionasdescr i
bedbel ow
publ i
cAccesspubl i
cVi si
bil
i
tycontroli
sv i
sibl
etoalltheclassesevenout
sidetheclasswhereitisdef
ined.
Exampl e:
ev enoutsi
det heclasswher eiti
sdefi
ned.Ex ample:
fr
iendl yAccess
Whennoaccessmodi fierisspecif
ied,thememberdef aul
tstoali
mitedver
sionofpubl
i
caccessibil
i
t y
knownas" fri
endly
"levelofaccess.
protect edAccess
Thev isi
bili
tyl
evelofa" protect
ed"fiel
dl i
esinbetweenthepubl
icaccessandfri
endl
yaccess.Thatis,the
prot ectedmodi fi
ermakest hefiel
dsv i
siblenotonl
ytoallcl
assesandsubclassesint
hesamepackage
butal sot osubclassesinot herpackages..
pri
v ateAccess
pri
vatefiel
ds enjoy the hi
ghestdegr ee ofprotect
ion.They ar e
accessi
bleonl
ywithinthei
rowncl ass.
pri
vat
eprotect
edAccess
Af i
eldcanbedecl aredwi t
ht wokey wordspriv
ateandpr otectedtogetherl
ike:Pri
vat
epr otect
ed
int
codeNumber;Thisgivesav i
sibi
li
tyleveli
nbetweenthe" pr
otected"accessand"pri
vat
e"access.Thi
s
modifi
ermakesthef i
eldsvi
sibl
ei nall
subclassesregar
dlessofwhatpackaget heyarein
Uni
tIV
Multi
pleChoi ceQuesti
ons(1
mark)Quest ionsbasedon
Understanding
1.HowdoesJav asupportt
heconceptofmul
ti
plei
nher
it
ance?
A.package
B.Overridi
ng
C.Abstractclasses
D.Int
erfaces
2.Aninter
faceisbasi
cal
l
yaki
ndof
A.package
B.fi
nal method
C.cl
ass
D.object
3.Namet hekeywor
dusedt
odef
inemul
ti
plei
nher
it
ancei
nJav
a?
A.int
erface
B.extends
C.implements
D.Package
4.Howdoy oudecl
arev
ari
abl
esi
nint
erf
aces?
A.constants
B.global
C.public
D.protect
ed
5.Howaremethodsdecl
aredinaninter
face?
A.Nocodeiswri
ttenf
ormethods
B.onl
ymethodsaredefi
ned
C.Methodsar
enotall
owedi naninterf
ace
D.AandB
6.Namet hekeywor
dusedbyacl
asst
oinher
itani
nter
face.
A.extends
B.implements
C.Package
D.int
erface
7.I
nJav a,i
nterf
acescandef i
neonl y and .
A.fi
nalfiel
dsandex ecutablemet hods
B.fi
nalfiel
dsandabst ractmet hods
C.vari
ablefiel
dsandabst ractmet hods
D.vari
ablefiel
dsandex ecutablemet hods
8.Javadoesnotsuppor ttheconceptof
A.singlelevelinheri
tance
B.hierarchi
cal i
nherit
ance
C.mul ti
-l
evelinheri
tance
D.Mul ti
pleinheri
tance
9.I
nter
facesinJavaareusedas whosepr
oper
ti
escanbei
nher
it
edbycl
asses
A.subcl asses
B.supercl
asses
C.deri
vedclasses
D.Noneoft heabove
10.Aclasscan anot
hercl
asswhi
l
eimpl
ement
ingi
nter
faces
A.extend
B.overri
de
C.overl
oad
D.create
11.Whichoft
hesekey
wor
dsi
susedt
odef
inepackagesi
nJav
a?
A.Pkg
B.pkg
C.package
D.Package
12.I
nJav a, groupsclassesandi
nter
facest
oget
her A.i
nter
face
B.package
C.abst r
actcl
ass
D.abst r
actmethods
QuestionsbasedonAppl i
cati
on
13.Howmanycl assesofpackagesareavail
abl
einJava?
A.two
B.three
C.four
D.fi
ve
14.
Whi chofthef
oll
owi
ngpackagesar
eusedt
oimpl
ementgr
aphi
cal
useri
nter
facei
nJav
a?A.
j
ava.
lang B.
j
ava.
util
C.j
ava.awt
D.j
ava.appl
et
15.
Namet hepackaget
hatcont
ainscl
assesf
orcr
eat
ingandi
mpl
ement
ingappl
etsi
nJav
a.
A.java.
lang
B.j
ava.uti
l
C.j
ava.awt
D.j
ava.applet
16.
Namet hepackaget
hati
susedbyt
heJav
acompi
l
eri
tsel
f.
A.j
ava.
lang
B.j
ava.
uti
l
C.j
ava.
awt
D.j
ava.
applet
17.Namet hepackaget
hati
sfaci
l
itat
esi
nput
/out
puti
naJav
a
program A.
j
av a.
lang
B.
j
av a.
util
C.
j
ava.
io
D.j
ava.
appl
et
18.
Namet hejav
apackaget
hati
susedt
ohandl
evect
orsi
nJav
a
A.j
ava.
lang
B.j
ava.
util
C.j
ava.
awt
D.j
ava.
applet
19.Apackagei
nJav
aisor
gani
zedi
n manner A.l
i
near
B.dynamic
C.stat
ic
D.hier
archi
cal
20.
Namethekey
wor
dthati
ncl
udesapackagei
ntoaj
avapr
ogr
am A.ext
ends
B.i
mplement
s
C.i
ncl
ude
D.i
mport
21.Whi
choper
atori
susedt
oaccesst
hecl
asst
hatr
esi
desi
naJav
apackage
A. new
B.dot
C.get
D.post
22.Packagenamesi nJav
abegi
nwi
th A.upper
casel
ett
er
B.digi
t
C.l
ower caselet
ter
D.specialchar
acter
23.Whichoft
hef
oll
owi
ngkey
wor
dsi
susedt
odecl
areapackagei
nJav
a?
A.import
B.
package
C.declare
D.def
ine
24.Theclasst
hati
sdef
inedi
nsi
deapackagemustbedecl
aredas
A.public
B.private
C.protect
ed
D.fri
end
25.Theconceptofpackagesi
nJav
aissi
mil
art
o i
not
herpr
ogr
ammi
ngl
anguages
A.ov erl
oading
B.ov err
idi
ng
C.abstractclasses
D.cl
assl
ibr
ari
es
LongQuest
ionAnswer
s
1.Defi
neani
nter
face.Descr
ibet
hev
ari
ousf
ormsofi
mpl
ement
ingi
nter
facei
nJav
a
wit
hexampl
es.
Ani nt
erf
aceisbasical
lyaki nd ofclass.Likeclasses,i
nterf
acescontai
nsmethodsand
var
iabl
esbutwithamaj ordif
fer
ence.Thedi ffer
enceisthatinter
facesdef
ineonl
yabst
ract
methodsandf
inalf
iel
ds.Gener
alform ofint
erf
aceis
I
mpl
ement i
ngint
erfaces
I
nterf
acesareusedas"supercl
asses"whoseproper
tiesareinher
it
edbycl
asses.I
tist
her
efor
e
necessar
ytocreateacl
assthatinher
it
sthegi
veninterf
ace.Thisi
sdoneasfol
lows
Her
et asscl
hecl assname"
impl
ements"t
hei
nter
facei
nter
facename.Amor
egener
alf
orm of
i
mplement
ati
onmaylookl
iket
his:
Exampl
e:-
2.Defineapackage.Expl ainthebenef i
tsofusi ngpackagesi nJav a.
Oneoft hemai nf eat uresofOOPi si t
sabi li
tyt or eusethecodeal readycr eated.Onewayof
achiev i
ngt hi
si sbyex tendingt heclassesandi mpl ementingthei nterfaces.Thi si sl
imitedto
reusingt hecl asseswi thinapr ogram.I fweneedt ousecl assesf rom ot herpr ogramswehav e
tousepackages.Packagesar eJav a'swayofgr oupingav ari
etyofcl assesand/ ori
nterf
aces
together
Byor ganizi
ngourcl assesi ntopackagesweachi evet hefoll
owingbenef its:
1.Thecl assescont ainedi nthepackagesofot herpr ogramscanbeeasi l
y reused.
2.Inpackages, classescanbeuni quecompar edwi thclassesinot herpackages.Thati s,two
classesi ntwodi ff
er entpackagescanhav et hesamename.Theymayber eferredbytheir
full
yqual if
iedname, compr isi
ngt hepackagenameandt heclassname.
3.Packagespr ov i
deawayt o" hide"classest huspr eventi
ngot herprogramsorpackages
from accessi ngcl assest hatar emeantf ori nternaluseonly.
4.Packagesal sopr ov ideawayf orsepar at
ing" design"from "coding".Fir
stwecandesi gn
classesanddeci det hei rr
elationships,andt henwecani mplementt heJav acodeneeded
fort hemet hods.I tispossi bletochanget hei mplement ati
onofanymet hodwi thout
affectingther estoft hedesi gn.
.Javapackagesar
etheref
orecl
assi
fi
edi
ntotwotypes.Thefi
rstcat
egor
yisknownasJav
aAPI
packagesandt sknownasuserdef
hesecondi i
nedpackages.
3.Cl assif
yandexpl ai
nt hetypesofpackagesav ai
labl
einJava.JavaAPIpackages
.Javapackagesar etheref
oreclassif
iedi
ntotwotypes.Thefir
stcategor
yisknownasJav aAPI
packagesandt hesecondisknownasuserdef i
nedpackages.
JavaAPIpr ov
idesal ar
genumberofcl assesgroupedintodi
ff
erentpackagesaccor
dingt
o
funct
ional
ity
.JavaSy stem PackagesandTheirClasses
Usingsy st
em packages
Thepackagesar eorgani
sedinahier
archi
calstr
uctur
e.Thi
sshowsthatthepackagenamedjava
containsthepackageawt,whi
chintur
ncontainsvari
ouscl
assesr
equir
edf ori
mplementi
nggraphi
cal
userinterf
ace.
4.Expl
ainthehier
archicalst
ruct
ureofapackageinJavawit
hanexampleofy ourown.
Thepackagesareorganisedinahier
archi
cal
str
uctur
e.Thi
sshowsthatthepackage
namedjavacontainsthepackageawt,whi
chintur
ncontai
nsvar
iouscl
assesrequir
edfor
i
mplementinggraphical
userint
erf
ace.
Ther
ear et
woway sofaccessingt
heclassesstor
edinapackage.Thef
ir
stapproachistousetheful
ly
qual
if
iedcl
assnameoft heclasst
hatwewantt ouse.Thi
sisdonebyusingt
hepackagename
cont
aini
ngthecl
assandt henappendi
ngtheclassnametoitusi
ngthedotoperat
or.Forexample,
ifwe
wanttoref
ertot
heclassColorintheawtpackage,t
henwemaydosoasf ol
lows:j
ava.awt.
Col
our
5.Wr it
eanot eonJavaAPIpackages.
JavaAPIprovi
desalar
genumberofclassesgroupedi
ntodi
ff
erentpackagesaccor
dingt
o
f
unct
ional
i
ty.Jav
aSy st
em PackagesandThei
rClasses
6.Def i
neanint
erf
ace.Explai
nt heconceptofJav aint
erfaceswit
hsynt
axandexampl e
Anint
erf
aceisbasi
cal
l
yaki ndofclass.Likeclasses,
int
erf
acescontai
nsmethodsandvariablesbutwi
tha
maj
ordif
f ence.
er Thedif
fer
enceisthatinterfacesdefi
neonlyabstr
actmet
hodsandfinal
fields.
Thesy nt
axf
ordefi
ningani
nter
facei
sver
ysi
mil
art
othatf
ordef
ini
ngacl
ass.Thegener
alf
orm ofan
i
nter
facedef
ini
ti
onis
Vari
ablesaredeclaredasf oll
owsstaticfi
nal
t
ypeVar i
abl
eName=Val ue;
Notethatal
lvari
ablesar
edecl aredasconstant
s.Methodsdecl
arat
ionwi
llcont
ainonlyal
istof
methodswithoutanybodyst atement
s.Example
r
eturn-
typemethodNamel(parameter_
li
st);
Hereisanexampl eofaninterf
acedefini
ti
onthatcont
ainst
wov ari
abl
esandonemet hod
Questi
onsbasedonAppl i
cat i
on
1.Howt oaccessint
erfacev ar
iabl
einJav a?Explai
nwi t
hanexampl e
I
nterf
acescanbeusedt odeclareasetofconst antsthatcanbeusedi ndi
ff
erentclasses.I
nter
faces
donotcontainmethods,t
hereisnoneedt oworryaboutimplementinganymethods.Theconst ant
val
ueswillbeavai
labl
etoanycl assthatimplementstheinter
face.Theval
uescanbeusedi nany
method,aspartofanyvari
abledeclarat
ion,oranywherewecanuseaf i
nalv
alue.Example:-
Exampl
e:-
3.Di
scussaboutext
endi
ngani
nter
facei
nJav
awi
thanexampl
e?
Li
keclasses,i
nter
facescanal
sobeex tended.Thati
s,ani
nterf
acecanbesubinterf
acedfr
om other
i
nter
faces.Thenewsubi nt
erf
acewill
inherital
lthemembersofthesuperi
nter
faceinthemanner
si
mil
artosubclasses.Thi
sisachi
evedusingt hekey
wordextendsasshownbelow:
Forexampl
e,wecanputal
ltheconst
antsi
noneint
erf
aceandthemet
hodsintheot
her
.Thi
swi
l
l
enabl
eustousetheconst
antsi
nclasseswher
ethemethodsar
enotr
equi
red.
Whil
eint
erf
acesareall
owedt
oext
endt
oot
heri
nter
faces,
subi
nter
facescannotdef
inet
hemet
hodsdecl
ared
i
nthesuperi
nter
faces
4.Listthestepstofoll
owinordertoworkwi thpackagesinJava.
Inor dert
ocreat
eapackagewemustf ir
stdeclarethenameoft hepackageusingthepackagekey
wor
d
fol
lowedbyapackagename.Thi smustbet hefir
ststat
ementinaJav asourcefi
le(exceptf
or
comment sandwhitespaces).
Thenwedef i
neaclass,j
ustaswenor mall
ydefineaclass.Example:
-
Heret hepackagenameisfi
rstPackage.TheclassFir
stClassisnowconsider
edapartofthi
spackage.
Thisli
stingwouldbesavedasaf i
lecall
edFirst
Class.
java,andlocat
edinadir
ect
orynamed
fi
rstPackage.Whenthesourcefi
leiscompiled,Javawil
l cr
eatea.cl
assfi
l
eandstoreiti
nthe
samedi r
ectory
.
Torecap,cr
eat
ingourownpackageinv
olv
esthef
oll
owi
ngst
eps:
1.Decl
aret
he
packageatt
hebegi
nni
ngofafi
leusi
ngthef
orm
2.Def i
netheclassthati
stobeputi nthepackageanddeclar
eitpubli
c.
3.Createasubdi rect
oryundert hedi
rect
orywher ethemainsour cefi
lesarest
ored.
4.Storetheli
stingastheclassname.j
avafi
leinthesubdi
rect
ory
created.5.Compil
ethefi
l
e.Thi
scr
eat
es
.classfi
lei
nt hesubdi
rector
y
5.Menti
onthev ari
ousmet hodsofaccessi
ngclassesthatareavai
labl
einpackagesinJava.
Expl
ainwithexampleofy ourown.Accessi
ngaPackage
Theimportstat
ementcanbeusedt osearchalistofpackagesforapart
icul
arcl
ass.Thegener
alf
orm
ofimportst
atementforsearchi
ngaclassisasfoll
ows:
Herepackagel i
st henameoft hetopl ev
el package2i
package, sthenameoft hepackagethatisinsi
de
thepackagel ,andsoon.Wecanhav eanynumberofpackagesi napackagehi er
archy.Fi
nall
y,the
explicitclassnamei sspeci fi
ed.
Not ethatt hest atementmustendwi thasemicolon(;)
.Theimportstat
ementshouldappearbef ore
anycl assdef initi
onsi nasour cefi
le.Multi
plei
mpor tstat
ementsareallowed.Thefoll
owingisan
exampl eofi mpor ti
ngapar ticul
arclass:
i
mpor tfi
rstPackage. secondPackage. MyClass;
Afterdef iningt hi
sst atement ,al
lthemember softhecl assMyClasscanbedi rect
lyaccessedusi ng
thecl assnameori t
sobj ects(asthecasemaybe)di rectl
ywit
houtusi ngt
hepackagename.Wecan
alsouseanot herappr oachasf ol
lows:
i
mpor tpackagename. *;
6.Howdoy ouworkwi t
hpackagesi
nJav a?Explainwit
hanexampleofy ourown.
Creat
ingpackages
Inor dert
ocreateapackagewemustf ir
stdeclarethenameofthepackageusingthepackagekey
wor
d
fol
lowedbyapackagename.Thi smustbet hefir
ststat
ementinaJavasourcefi
le(exceptf
or
comment sandwhitespaces).
Thenwedef i
neaclass,justaswenormall
ydefineaclass.Her
eisanexample:
cr
eat
ingourownpackage
i
nvolvesthefol
lowingst
eps:
1. Decl
arethepackageatt
hebegi
nni
ngofaf
il
eusi
ngt
hef
orm
2. Defi
netheclassthatistobeputi nthepackageanddecl arei
tpubli
c.
3. Creat
easubdi r
ectoryundert hedir
ectorywher ethemainsour cefi
l
esar estor
ed.
4. St
orethelist
ingast heclassname.j
avafilei
nthesubdirect
ory
created.
5. Compil
et hefil
e.Thiscreates.cl
assfi
leinthesubdi
rect
ory.AccessingaPackage
Theimportst at
ementcanbeusedt osear chalistofpackagesforapar t
icularcl
ass.Thegener
alf
orm
ofi
mpor tstatementforsear chingaclassi sasfoll
ows:
Thef
oll
owi ngisanexampleofi mport
ingapart
icul
arcl
ass:
i
mportf
ir
stPackage.
secondPackage.
MyClass;
Usi
ngapackage
Thel
ist
ingbelowshowsapackagenamedpackage1cont ai
ningasi
ngl
ecl
assCl
assA.
Thi
ssour
cefi
leshoul
dbenamedClassA.j
avaandst or
edinthesubdi
rect
orypackagel
asstat
edear
li
er.
Nowcompil
ethi
sjavafi
l
e.Ther
esul
tantClassA.
classwil
lbestor
edinthesamesubdir
ect
ory.
Uni
tV
Multi
pleChoi ceQuest i
ons(1
mar k)Quest i
onsbased
onApplicat i
on
1. isaconcept
ual
programmingpar
adigm wher
eapr ogr
am i
sdi
vi
dedi
ntot
woormor
e
subprogramswhi chcanbei mpl
ementedatt
hesamet i
meinparall
el.
A.mul t
ipleinterf
ace
B.mul t
ithreading
C.mul t
ipleinheri
tance
D.mul t
i-programmi ng
2.Theabili
tyofaoper at
ingsy
stem t
oexecut
esev
eral
processessi
mul
taneousl
yiscal
l
ed
A.multi
-programmi ng
B.multi
-threading
C.multi
tasking
D.paral
l
el processi
ng
3.A i
ssi
mil
art
oapr
ogr
am t
hathassi
ngl
efl
owofcont
rol
.
A.pr ocess
B.thread
C.task
D.met hod
4.Whatdoesathr
eadcont
ain?
A.begi
nning
B.bodyofathr
eas
C.endi
ng
D.al
ltheabove
5.Theabil
it
yofal anguaget
osuppor
tmul
tit
hreadsi
sknownas A.
paral
l
elprocessi
ng
B.concurrency
C.multi
taski
ng
D.multi
processi
ng
7. ist
hehear
tandsoul
ofat
hreadi
nJav
a
A.run()method
B.sleep()method
C.wait()method
D.start
()method
8.I
nJava,thr
eadsar
eimpl
ement
edi
nthef
orm of
A.methods
B.cl
asses
C.i
nter
faces
D.obj
ect
s
9.I
nJav a, methodcausest
het
hreadt
omov
etor
unnabl
est
ate.
C.sl
eep() A.r
un() B.wai
t(
)
D.star
t()
10.Thest art
()met hodcausest
het
hreadt
omov
eto
A.starti
ngst ate
B.sleepmode
C.runnabl estate
D.i
ni t
ialstat
e
11.Whi choft
hefol
l
owi
ngmet
hodshel
ptobl
ockat
hread?
A.sleep()
B.suspend()
C.wait()
D.alltheabove
12.I
nhowmanyst at
esdoesathr
eadresi
de?
A.three
B.four
C.fiv
e
D.six
QuestionsbasedonSki
ll
13.Whenapr ematur
edeathofat
hreadisdesi
red, met
hodi
susedi
nJav
a
A.suspend(
)
B.wai t
()
C.stop()
D.ki
ll(
)
14.HowdoesJav aassi
gnpri
ori
tyt
oat
hread?
A.assign()met hod
B.yiel
d()met hod
C.asssignPriori
ty(
)method
D.setPriori
ty()method
15.
Namet hei
nter
faceusedt
ocr
eat
ethr
eadsi
nJav
a
A.Yi
eld
B.Runnable
C.Threads
D.Synchroni
ze
16.A i
sami
staket
hatcanmakeapr
ogr
am gowr
ong.
A.Ex cepti
on
B.Error
C.fai
lure
D.fault
17.Allsyntaxer
ror
sbel
ongt
o cl
assofer
ror
s
A.run-ti
me
B.compi le-t
ime
C.typo-error
D.execut i
on
18.
Whi chofthefol
lowi
ngar
ecompi
l
eti
meer
ror
s?
A.missingsemicol
on
B.usageof=inst
eadof==
C.mismatchofbracket
s
D.Allt
heabove
19.I
fasy ntacti
cal
lycor
rectpr
ogr
am pr
oducesawr
ongr
esul
t,t
hent
heer
rori
ster
medas
A.run-t
imeer ror
B.compi l
e-ti
meer r
or
C.typo-
error
D.executi
on-error
20. i
sacondi
ti
ont
hati
scausedbyar
un-
ti
meer
rori
napr
ogr
am
A.fault
B.fail
ure
C.Excepti
on
D.err
or
21.I
nat ry-
cat
chbl
ock, key
wor
dhandl
est
heexcept
ion
A.tr
y
B.throw
C.catch
D.Excepti
on
22.I
nat r
y-cat
chbl
ock,
the bl
ockcont
ainsst
atement
sthatcauseanexcept
ion
A.try
B.throw
C.catch
D.Throwable
23.Namet hekeywor
dinJav
athatguar
ant
eest
ohandl
eanexcept
ion,
regar
dlessofwhet
herornotan
excepti
onisthr
own
A.fi
nal
B.try
C.catch
D.final
ly
24.Namet hekey
wor
dinJav
athati
susedt
ohandl
euserdef
inedexcept
ions
A.throw
B.try
C.fi
nally
D.catch
25. ismechani
sm t
opr
ovi
demeanst
odet
ectandr
epor
tar
unt
imeer
rori
napr
ogr
am
A.Errorhandli
ng
B.Excepti
onhandling
C.Messagehandling
D.Noneoft heabove
LongAnswerQuest i
ons
Questionsbasedon
Appli
cation
1.Def i
neat hread.Expl
ainthev ari
ousmethodsi nwhi cht hr
eadscanbecr eatedinJava.
Athr
eadi ssimilartoaprogram thathasasinglefl
owofcont r
ol.I
thasabegi nning,abody,andanend,
andex ecutescommandssequent iall
y.I
nfact
,allmainpr ogramsi njavacanbet houghofassi ngl
e-
thr
eadedpr ograms.Auni queproper t
yofJavaisit
ssuppor tformultit
hreadi
ng.Thatis,Javaenables
ustousemul t
ipleflowsofcontrolindevel
opi
ngpr ograms.Eachf l
owofcont rolmaybet houghtofasa
separateti
nypr ogram (
ormodul e)knownasat hreadt hatrunsinpar al
lelt
oother s
Creati
ngthreadsi nJav aissimple.Thr
eadsar eimpl ementedintheform ofobjectsthatcont
aina
methodcall
edr un().Ther un()methodisthehear tandsoul ofanythread;I
tmakesupt heenti
rebody
ofathreadandi stheonl ymet hodinwhichthet hread'
sbehav i
ourcanbei mplement ed.Ther
un()
methodshouldbei nv okedbyanobj ectoftheconcer nedthread.Thiscanbeachi evedbycreati
ngthe
thr
eadandiniti
atingitwi t
ht hehelpofanotherthreadmet hodcall
edst art(
).
Anewthreadcanbecr eatedintwoway s.
1.Bycreatingat hreadclass:DefineaclassthatextendsThreadcl
assandoverr
ideitsrun()
methodwi ththecoder equi
redbyt het
hread.
2.Byconv erti
ngacl asstoat hread:Defi
neacl assthati
mplementsRunnabl
eint
erface.The
Runnablei nter
facehasonl yonemet hod,run(),
thati
stobedefinedi
nthemethodwi ththecodet
o
beexecut edbyt hethr
ead.
TheThr
eadcl
asscanbeext
endedasf
oll
ows
3.Li
standexplainthev ar
iousstat
esinwhi
chathr
eadresides.
Duri
ngt hel
if
etimeofat hr
ead,t
her
earemanyst
ates,
itcanenter
.Theyi
ncl
ude:
1.Newbornstat
e
2.Runnabl
estate
3.Runni
ngstate
4.Bl
ockedstate
5.Deadstat
e
NewbornSt ate
Whenwecr eateat hreadobject,t
hethreadisbor
nandi ssai
dtobeinnewbornstate.Thethreadi
s
notyetscheduledf orrunning.Atthi
sstate,
wecandoonl yoneofthefol
l
owingthingswithit
:
Schedul
eitf orrunningusingstart()method.Ki
ll
itusi
ngstop()method.
RunnableState
Ther unnabl
estatemeanst hatthethr
eadisreadyforexecuti
onandi swai
ti
ngfort
heavail
abil
i
tyofthe
processor.Thatisthethreadhasj oinedt
hequeueoft hreadsthatarewait
ingforexecuti
on.Ifall
threadshaveequalpri
ori
ty,thentheyaregi
ventimeslotsforexecut
ioninr
oundrobinf
ashion,i
.e.
,fi
rst
-come, f
ir
st-
serv
emanner
Runni
ngSt ate
Runni
ngmeanst hattheprocessorhasgivenitsti
met othethr
eadfori
tsexecuti
on.Thethreadr
uns
unt
ili
trel
inquishescontr
oloni t
sownori tispreemptedbyahigherpri
ori
tythr
ead.Arunningthr
ead
mayreli
nquishitscontr
olinoneoft hefol
lowingsit
uations.
I
thasbeensuspendedusi ngsuspend()met hod.Asuspendedthr
eadcanber evi
vedbyusing
t
her esume()method
DeadStat
e
Ever ythr
eadhasal ifecycle.Arunningt hreadendsi tsli
fewheni thascompl etedexecuti
ngi t
s
run()met hodIti
sanat url Death.Howev er,
wecanki l
litbysendingt hest
opmessaget oitat
anyst atethuscausingapr emat ur
edeat ht oit
.At hreadcanbeki lledassoo
Bl
ockedSt ate
At hreadissaidtobebl ockedwheni ti
spr eventedfrom ent er
ingintotherunnablestat
eand
subsequent l
ythe-r
unningst at
e.Thishappenswhent hethreadissuspended, sl
eeping,or
wai ti
nginordertosat i
sfycert
ainrequirement s.Ablockedt hreadisconsidered"notrunnable"
butnotdeadandt hereforeful
lyqualifi
edt orunagain.
3.Whatarethev ar
iousmethodsinJav atostopandblockathr
ead?
Expl
ainStoppingandblocki
ngat hread
Wheneverwewantt ostopathreadfrom r
unningf
urther
,wemaydosobycal
l
ingi
tsst
op(
)met
hod,
l
ike:
aThread.st
op()
;
Thisst atementcausest het hreadtomov et othedeadst ate.At hreadwi llal
somov etothe
deadst ateaut omat i
cal
lywheni treachest heendofi tsmet hod:Thest op()met hodmaybeused
whent hepr emat uredeathofat hreadi sdesired.Bl ockingaThr ead
Athreadcanal sobet empor aril
ysuspendedorbl ockedf r
om ent er i
ngint otherunnabl
eand
subsequent lyrunningstatebyusi ngei theroft hef oll
owi ngthreadmet hods: sleep()//blockedfor
aspecifiedt i
mesuspend()//bl ockedunt il
fur t
heror der swait(
)//
blockedunt ilcert
aincondit
ionoccur s
Thesemet hodscauset hethreadt ogoi nt
ot hebl ocked( ornot-
runnabl e)state.Thet hr
eadwillr
etur
nto
therunnablest atewhent hespeci fiedt i
mei sel apsedi nt hecaseofsl eep() ,theresume()met hodis
i
nv okedint hecaseofsuspend() ,andt henot i
fy ()met hodi scalledint hecaseofwai t()
.
4.
Howdoy
ouassi
gnpr
ior
it
iest
oat
hreadi
nJav
a?Expl
ain.
Thr
eadprior
it
y
InJava,eacht hr
eadi sassi
gnedapr i
orit
y, whichaf
fectstheorderi
nwhichitisscheduledfor
runni
ng.Thet hreadsthatwehav ediscussedsof arareofthesamepr i
ori
ty.Thethreadsofthe
samepr iori
tyaregivenequaltr
eatmentbyt heJavaschedulerand,
ther
efore,t
heyshar ethe
processoronaf irst
-come,fi
rst
-ser
vebasi s.Javapermitsustosetthepri
orit
yofat hreadusing
thesetPrior
ity
()met hodasfoll
ows:
Theint
Numberisanint
egerv
aluet
owhi
cht
het
hread'
spr
ior
it
yisset
.TheThr
eadcl
assdef
ines
sev
eralpr
ior
it
yconst
ants:
Forathreadoflower.pr
ior
it
yt ogai
ncont
rol
,oneoft
hef
oll
owi
ngt
hingsshoul
d
happen:1.I
tst
opsr unni
ngatt heendofr
un().
2.I
tismadet osleepusingsleep(
).
3.I
tistol
dt owaitusi
ngwai t
().
6.
Howdoy
oui
mpl
ementt
hreadsusi
ngRunnabl
eint
erf
ace?Expl
ain
I
mpl
ement i
ngt her unnablei nterface
Westatedear l
ierthatwecancr eatet
hreadsintwoway s:onebyusi ngtheextendedThreadclass
andanot herbyi mpl ement ingt heRunnableinterface,Int hi
ssecti
on,weshallseehowt omake
useoft heRunnabl ei nterfacet oimplementthreads
TheRunnabl einterf
acedecl arestherun()met hodt hatisrequi
redforimpl
ement i
ngthreadsin
ourprogr ams.Todot his,wemustper formthest epsl istedbel
ow:
1.Declaret hecl assasi mpl ementingtheRunnabl einterface.
2.I
mpl ementt her un() met hod.
3.Createat hreadbydef i
ninganobj ectthatisinstantiatedfrom t
his"r
unnable"cl
assas
thetar getoft hethread.
4.Callthet hread'sst art()met hodt orunthethread.
7.
Def ineanexcepti
on.Explai
nthev ari
ousmet hodstohandl eexcepti
onsi nJav a
Anex cepti
onisacondit
ionthatiscausedbyar un-t
imeer r
orinthepr ogram.Whent heJava
i
nterpret
erencount
ersaner r
orsuchasdi vi
dinganintegerbyzero,itcreatesanexcepti
on
objectandthr
owsit(
i.
e.,i
nformsust hatanerrorhasoccurred).I
ftheexcept i
onobjecti
snot
caughtandhandledproperl
y,theint
erpr
eterwill
displ
ayaner rormessageandwi l
ltermi
nate
theprogram.
Thebasi
cconcept
sofexcept
ionhandl
i et
ngar hr
owi
nganexcept
ionandcat
chi
ngi
t.
Javausesakeywordtryt
opr ef
aceabl ockofcodethatisli
kel
ytocauseaner r
orcondi
ti
onand
"thr
ow"anexcept
ion.Acatchblockdefinedbythekeywordcatch"cat
ches"t
heexcepti
on"thr
own"by
thetrybl
ockandhandl
esitappropri
atel
y .Thecat
chblockisaddedimmediatel
yaft
erthetr
yblock
Quest ionsbasedonSki l
l
1.Howdoy ouext endat hr
eadcl assinJava?Expl ainwithappr opriat
esy nt
axandexampl e.Extendi
ng
thethr eadcl ass
Wecanmakeourcl assrunnableasat hr
eadbyextendi ngthecl assjava.l
ang.Thread.Thisgiv
esus
accesst oallthet hreadmet hodsdirectly
.Iti
ncl
udest hef oll
owingst eps:
1.Decl arethecl assasex t
endingtheThr eadcl
ass.
2.Impl ementt her un()met hodt hatisresponsi
bleforexecut ingthesequenceofcodet hatthethreadwil
l
ex ecute.
3.Creat eat hreadobj ectandcal lt
hest art
()methodtoi nit
iatethethreadexecuti
onTheThr ead
classcanbeex t endedasf ol
lows:
Cr
eat
ingt
hreadsusi
ngt
het
hreadcl
ass
2.
Drawandexpl ai
nthetr
ansi
ti
ondi
agram t
odescri
bethelif
ecy cl
eofat
hread.Dur
ingt
hel
i
fe
ti
meofat hread,t
her
earemanyst
ates,
itcanent
er.Theyincl
ude:
1.Newbornstat
e
2.Runnabl
estate
3.Runni
ngstate
4.
Blockedst
ate
5.
Deadst at
e
Athr
eadisal
waysi
noneoft
hesef
ivest
ates.I
tcanmov
efr
om onest
atet
oanot
herv
iaav
ari
etyof
waysasshowni
nfi
gur
e.
3.
Compar
eandcont
rastsuspendi
ngandst
oppi
ngat
hreadi
nJav
a
Arunningthreadmayr el
i
nquishit
scontrol
inoneofthefoll
owingsit
uati
ons.
1.Ithasbeensuspendedusi
ngsuspend()method.Asuspendedthr
eadcanbereviv
edbyusi
ngt
he
resume()method.Thi
sapproachisusef
ulwhenwewant ,
tosuspendathr
eadforsometi
meduetocer
tai
n
reason,butdonotwanttoki
ll
it.
Li
4. stsomeoft
hemostcommont
ypesofexcept
ionst
hatmi
ghtoccuri
nJav
a.Gi
ve
sui
tabl
eexampl
es.CommonJav
aExcept
ions
Howdoy
5. ouhandl
euser
-def
inedexcept
ionsi
nJav
a?Expl
ain
Theremaybeti
meswhenwewoul
dli
ket
othr
owourownexcept
ions.Wecandot
hisbyusi
ng
thekey
wordthr
owasfol
l
ows:
Exampl
es:
thr
ownewAr i
thmet
icExcepti
on();t
hrownewNumber Format
Except
ion();
Except
ioni
sasubcl assofThrowableandtheref
oreMyExcepti
onisasubcl
assof
Throwabl
eclass.Anobjectofaclassthatext
endsThrowablecanbethr
ownandcaught
.
Thr
owi
ngourownexcept
ion
Howdoy
6. ouhandl
eexcept
ionsi
nJav
ausi
ngt
ry-
cat
chbl
ock?Expl
ain
Javausesakey wordtrytopr ef
aceabl ockofcodethatisli
kel
ytocauseaner rorcondi
ti
onand
"thr
ow"anex cepti
on.Acat chblockdefinedbythekeywordcatch"catches"theexcepti
on"thr
own"by
thetryblockandhandlesitappropri
atel
y .Thecat
chblockisaddedi mmediatelyaft
erthetr
yblock.
Thef ol
l
owi ngexampleil
lustr
atestheuseofsi mplet
ryandcatchst atements:
Thet r
ybl ockcanhav eoneormor estat ement sthatcoul dgenerat eanexcept i
on.Ifanyonest at ement
generatesanex cept
ion, t
her emai ningst atement sintheblockar eski ppedandexecut i
onjumpst ot he
catchblock)thati splacednex ttothet rybl ock.Thecat chblockt oocanhav eoneormor est at ement s
t hatarenecessar yt
opr ocesstheexcept ion.
Remembert hat(everytryst atementshoul dbefolowedbyatl
l eastonecat chstatement;other wise
compi l
at i
oner r
orwilloccur.) .catchst atementwor kslikeamet hoddef ini
ti
on.Thecatchst atementi s
passedasi ngleparamet er
,whi chisr eferencet otheexcept i
onobj ectthrown(bythetryblock) .Ifthe
catchpar ametermat cheswi tht het y
peofexcept i
onobj ect,
thent heexcept i
oniscaughtandst atement s
inthecat chblockwi ll
beex ecut ed.Ot herwi se,t
heexcept i
oni snotcaughtandt hedefaultexcept i
on
handlerwi l
lcauset heexecut i
ont oterminat eexampl e:
-
Def
7. ineaner
ror
.Compar
ethedi
ff
erentt
ypesofer
ror
sthatar
isei
npr
ogr ngEr
ammi ror
s
aremi st akest hatcanmakeapr ogram gowr ong.
Typesofer rors
Err
or smaybr oadl ybecl assifi
edi ntotwo
categor ies:Compi le-t
imeer rors
Run-timeer rorsCompi le-Ti
me
Err
or s
Allsyntaxer rorswi llbedet ect
edanddi splayedbyt heJav acompilerandt her
eforetheseerror
s
areknownascompi l
e-t
imeer rors.Whenev ert hecompilerdispl
aysaner ror,i
twil
lnotcreatethe
.
classfil
e.I tist herefor
enecessar ythatwef i
xalltheerror
sbeforewecansuccessf ull
ycompi l
e
andr unthepr ogr am.
TheJav acompi lerdoesani cejoboft ell
inguswher etheerrorsareintheprogram.For
exampl e, i
fwehav emissedt hesemi colonattheendofpr i
ntst at
ementt hefoll
owingmessage
wil
l bedi splayedi nthescreen:
Run-
TimeErrors
Somet i
mes, apr
ogram maycompil
esuccessf
ullycreat
ingthe.
classfi
l
ebutmaynotrun
properl
y.Suchprogramsmayproducewrongresult
sduet owronglogi
cormayter
minat
edue
toerror
ssuchasst ackov
ert
1ow{Mostcommonr un-t
imeerror
sare:
@@@@Al
ltheBest
@@@@