Java Interview Questions-1
Java Interview Questions-1
ionsto
Pr
eparefory
our
NextJ
AVAI NTERVI
EW
>
01
Que.Ex
plai
nthedi
ff
erencebet
weenHashMapand
Concur
rentHashMap.
Whenwoul
dyouuse
oneovertheother
?
Ans.HashMapi
snott
hread-saf
eanddoesn'
t
guaranteesynchr
oni
zedaccessbymul
ti
ple
thr
eat.
Concur
rent
HashMapisathr
ead-saf
ever
-
si
onofHashMapthatal
l
owsconcurr
entr
ead
andwri
teoper
ati
ons.
Usage:UseHashMapwhent hreadsafetyi
s
notaconcernandyouneedbet terperf
or-
mancef orsi
ngle-thr
eadedorex t
ernal
lysyn-
chroni
zedscenarios.UseConcurr
entHash-
Mapi nmulti
-thr
eadedenvi r
onment swhere
>
02
Que.How doyouhandl
eex
cept
ionsi
namul
ti
-
t
hreadedenvi
ronment
?
Ans.I
namul
ti
-thr
eadedenvi
ronment
,ex
cept
ions
i
nonet hreaddonotpr
opagatetoot
her
.
t
hreads.Tohandl
eexcept
ions:
Try-catchblocks:
Encl
osecodet
hatmight
throw excepti
onsint
ry-cat
chbl
ockswi
thi
n
.
eacht hread.
UncaughtExcepti
onHandler
:UseThr
ead.se-
tUncaughtEx
cepti
onHandl
ertohandleun-
.
caughtexcepti
onsinathr
ead.
Fut
ureandEx ecut orServi
ce:I
fusi
ngEx ecut
or-
Ser
vice,r
etri
evet her esul
tusingFut
ure.get
(),
>
whichthrowsex cept i
onsthatoccurr
ed
duri
ngtaskex ecut i
on.
03
Que.How doest
heJavamemor
ymodelwor
k?
Ans.
.
.
>
04
Que.How doesJava'
sgar
bagecol
l
ect
ionwor
k?
Ans.Java'
sgar
bagecol
l
ect
ion(
GC)i
sanaut
o-
mati
cmemor ymanagementpr ocessthatr
e-
movesobj
ectsthatarenolongerreachabl
e
.
f
rom t
heprogram .Keyconceptsi
nclude:
Generati
onalGarbageCol l
ecti
on:Javadi -
videst
heheapi ntodi
ff
erentgenerations
(YoungGenerati
on,OldGeneration,andPer -
manentGener ati
on/Metaspace)toopt i
mize
.
GC eff
ici
ency.
GarbageCol l
ector
s:Vari
ousalgori
thmsli
ke
Ser
ial,
Paral
lel
,CMS( Concurrent
Mark-Sweep),andG1( Garbage-Fi
rst
)cat
er
>
05
Que. Ex
plai
ntheconceptoft
hreadsaf
etyandhow
t
oensur
eiti
nJava?
.
Ans.Toensur
ethr
eadsaf
ety:
Usesynchroni
zedblocksormethodstopre-
ventconcurr
entaccesstocri
ti
calsect
ionsof
.
code.
Usejava.ut
il
.concur
rent
.l
ocks.
Lockf
ormor
e
.
f
lexi
blelockoperati
ons.
Usethevol
ati
lekeywordtoensurevisi
bil
i
tyof
.
changestovari
ablesacr
ossthreads.
Useclassesli
keAt
omicInt
eger,At
omi cRef
er-
ence,etc.
,f
oratomicoperat
ionswit
houtsyn-
.
chroni
zati
on.
Usecoll
ecti
onsfrom t
hejava.
uti
l
.concur
rent
package,
CopyOnWr
suchasConcur
i
teAr
rayLi
st.
rent
HashMap,
>
FOL
LOW FORMORE.
.!
www.
int
ell
iat
ech.
com