Sie sind auf Seite 1von 6

1.WhichtwomethodyouneedtoimplementforkeyObjectinHashMap?

InordertouseanyobjectasKeyinHashMap,itmustimplementsequalsandhashcode
methodinJava.ReadHowHashMapworksinJavafordetailedexplanationonhowequals
andhashcodemethodisusedtoputandgetobjectfromHashMap.
2.Whatisimmutableobject?Canyouwriteimmutableobject?Immutableclasses
areJavaclasseswhoseobjectscannotbemodifiedoncecreated.Anymodificationin
Immutableobjectresultinnewobject.ForexampleisStringisimmutableinJava.Mostly
ImmutablearealsofinalinJava,inordertopreventsubclassfromoverridingmethodsin
JavawhichcancompromiseImmutability.Youcanachievesamefunctionalitybymaking
memberasnonfinalbutprivateandnotmodifyingthemexceptinconstructor.
3.WhatisthedifferencebetweencreatingStringasnew()andliteral?
Whenwecreatestringwithnew()Operator,itscreatedinheapandnotaddedinto
stringpoolwhileStringcreatedusingliteralarecreatedinStringpoolitselfwhich
existsinPermGenareaofheap.

Strings=newString("Test")

doesnotputtheobjectinStringpool,weneedtocallString.intern()methodwhichisused
toputthemintoStringpoolexplicitly.itsonlywhenyoucreateStringobjectasStringliteral
e.g.Strings="Test"JavaautomaticallyputthatintoStringpool.
4.WhatisdifferencebetweenStringBufferandStringBuilderinJava?
ClassicJavaquestionswhichsomepeoplethingtrickyandsomeconsiderveryeasy.StringBuilderin
JavaisintroducedinJava5andonlydifferencebetweenbothofthemisthatStringbuffermethods
aresynchronizedwhileStringBuilderisnonsynchronized.SeeStringBuildervsStringBufferformore
differences.

5.WritecodetofindtheFirstnonrepeatedcharacterintheString?
AnothergoodJavainterviewquestion,ThisquestionismainlyaskedbyAmazonand
equivalentcompanies.Seefirstnonrepeatedcharacterinthestring:Amazon
interviewquestion

6.WhatisthedifferencebetweenArrayListandVector?
ThisquestionismostlyusedasastartupquestioninTechnicalinterviewsonthe

topicofCollectionframework.AnswerisexplainedindetailhereDifferencebetween
ArrayListandVector.

7.Howdoyouhandleerrorconditionwhilewritingstoredprocedureor
accessingstoredprocedurefromjava?
ThisisoneofthetoughJavainterviewquestionanditsopenforall,myfrienddidn't
knowtheanswersohedidn'tmindtellingme.mytakeisthatstoredprocedure
shouldreturnerrorcodeifsomeoperationfailsbutifstoredprocedureitselffailthan
catchingSQLExceptionisonlychoice.
8.Whatisdifference
betweenExecutor.submit()andExecuter.execute()method?
Thereisadifferencewhenlookingatexceptionhandling.Ifyourtasksthrowsan
exceptionandifitwassubmittedwithexecutethisexceptionwillgototheuncaught
exceptionhandler(whenyoudon'thaveprovidedoneexplicitly,thedefaultonewilljust
printthestacktracetoSystem.err).Ifyousubmittedthetaskwithsubmitanythrown
exception,checkedexceptionornot,isthenpartofthetask'sreturnstatus.Forataskthat
wassubmittedwithsubmitandthatterminateswithanexception,theFuture.getwillre
throwthisexception,wrappedinanExecutionException.

9.Whatisthedifferencebetweenfactoryandabstractfactorypattern?
AbstractFactoryprovidesonemorelevelofabstraction.Considerdifferentfactorieseach
extendedfromanAbstractFactoryandresponsibleforcreationofdifferenthierarchiesof
objectsbasedonthetypeoffactory.E.g.AbstractFactoryextended
byAutomobileFactory,UserFactory,RoleFactoryetc.Eachindividualfactorywouldbe
responsibleforcreationofobjectsinthatgenre.

YoucanalsoreferWhatisFactorymethoddesignpatterninJavatoknowmore
details.
10.WhatisSingleton?isitbettertomakewholemethodsynchronizedoronly
criticalsectionsynchronized?
SingletoninJavaisaclasswithjustoneinstanceinwholeJavaapplication,for
examplejava.lang.RuntimeisaSingletonclass.CreatingSingletonwastrickyprior
Java4butonceJava5introducedEnumitsveryeasy.seemyarticleHowtocreate
threadsafeSingletoninJavaformoredetailsonwritingSingletonusingenumand

doublecheckedlockingwhichispurposeofthisJavainterviewquestion.

11.Canyouwritecriticalsectioncodeforsingleton?
ThiscoreJavaquestionisfollowupofpreviousquestionandexpectingcandidateto
writeJavasingletonusingdoublecheckedlocking.Remembertousevolatile
variabletomakeSingletonthreadsafe.
12.CanyouwritecodeforiteratingoverhashmapinJava4andJava5?
Trickyonebuthemanagedtowriteusingwhileandforloop.
13.Whendoyouoverridehashcodeandequals()?
Whenevernecessaryespeciallyifyouwanttodoequalitycheckorwanttouseyourobjectas
keyinHashMap.
14.Whatwillbetheproblemifyoudon'toverridehashcode()method?
YouwillnotbeabletorecoveryourobjectfromhashMapifthatisusedaskeyinHashMap.
SeehereHowHashMapworksinJavafordetailedexplanation.
15.IsitbettertosynchronizecriticalsectionofgetInstance()methodorwhole
getInstance()method?
Answeriscriticalsectionbecauseifwelockwholemethodthaneverytimesomeonecall
thismethodwillhavetowaiteventhoughwearenotcreatinganyobject)
16.WhatisthedifferencewhenStringisgetscreatedusingliteralornew()operator?
Whenwecreatestringwithnew()itscreatedinheapandnotaddedintostringpoolwhile
StringcreatedusingliteralarecreatedinStringpoolitselfwhichexistsinPermareaofheap.
17.Doesnotoverridinghashcode()methodhasanyperformanceimplication?
Thisisagoodquestionandopentoall,aspermyknowledgeapoorhashcodefunctionwill
resultinfrequentcollisioninHashMapwhicheventuallyincreasetimeforaddinganobject
intoHashMap.
18.WhatswrongusingHashMapinmultithreadedenvironment?Whenget()method
gotoinfiniteloop?
Anothergoodquestion.Hisanswerwasduringconcurrentaccessandresizing.
19.Whatdoyouunderstandbythreadsafety?Whyisitrequired?Andfinally,
howtoachievethreadsafetyinJavaApplications?
JavaMemoryModeldefinesthelegalinteractionofthreadswiththememoryinareal
computersystem.Inaway,itdescribeswhatbehaviorsarelegalinmultithreadedcode.It
determineswhenaThreadcanreliablyseewritestovariablesmadebyotherthreads.It

determineswhenaThreadcanreliablyseewritestovariablesmadebyotherthreads.It
definessemanticsforvolatile,final&synchronized,thatmakesguaranteeofvisibilityof
memoryoperationsacrosstheThreads.
Let'sfirstdiscussaboutMemoryBarrierwhicharethebaseforourfurtherdiscussions.There
aretwotypeofmemorybarrierinstructionsinJMMreadbarriersandwritebarrier.
Areadbarrierinvalidatesthelocalmemory(cache,registers,etc)andthenreadsthecontents
fromthemainmemory,sothatchangesmadebyotherthreadsbecomesvisibletothecurrent
Thread.
Awritebarrierflushesoutthecontentsoftheprocessor'slocalmemorytothemainmemory,
sothatchangesmadebythecurrentThreadbecomesvisibletotheotherthreads.
JMMsemanticsforsynchronized
Whenathreadacquiresmonitorofanobject,byenteringintoasynchronizedblockofcode,
itperformsareadbarrier(invalidatesthelocalmemoryandreadsfromtheheapinstead).
Similarlyexitingfromasynchronizedblockaspartofreleasingtheassociatedmonitor,it
performsawritebarrier(flusheschangestothemainmemory)
ThusmodificationstoasharedstateusingsynchronizedblockbyoneThread,isguaranteed
tobevisibletosubsequentsynchronizedreadsbyotherthreads.Thisguaranteeisprovided
byJMMinpresenceofsynchronizedcodeblock.
JMMsemanticsforVolatilefields
Read&writetovolatilevariableshavesamememorysemanticsasthatofacquiringand
releasingamonitorusingsynchronizedcodeblock.Sothevisibilityofvolatilefieldis
guaranteedbytheJMM.MoreoverafterwardsJava1.5,volatilereadsandwritesarenot
reorderablewithanyothermemoryoperations(volatileandnonvolatileboth).Thuswhen
ThreadAwritestoavolatilevariableV,andafterwardsThreadBreadsfromvariableV,any
variablevaluesthatwerevisibletoAatthetimeVwaswrittenareguaranteednowtobe
visibletoB.
Let'strytounderstandthesameusingthefollowingcode
Datadata=null
volatilebooleanflag=false
ThreadA

data=newData()
flag=true<writingtovolatilewillflushdataaswellasflagtomainmemory
ThreadB

if(flag==true){<as=""barrier=""data.=""flag=""font=""for=""from=""perform=""
read=""reading=""volatile=""well=""will="">
usedata<!dataisguaranteedtovisibleeventhoughitisnotdeclaredvolatile
becauseoftheJMMsemanticsofvolatileflag.
}
20.WhatwillhappenifyoucallreturnstatementorSystem.exitontryorcatch
block?willfinallyblockexecute?
ThisisaverypopulartrickyJavaquestionanditstrickybecausemanyprogrammer

ThisisaverypopulartrickyJavaquestionanditstrickybecausemanyprogrammer
thinkthatfinallyblockalwaysexecuted.Thisquestionchallengethatconceptby
puttingreturnstatementintryorcatchblockorcallingSystem.exitfromtryorcatch
block.AnswerofthistrickyquestioninJavaisthatfinallyblockwillexecuteevenif
youputreturnstatementintryblockorcatchblockbutfinallyblockwon'trunifyou
callSystem.exitformtryorcatch.
19.CanyouoverrideprivateorstaticmethodinJava?
AnotherpopularJavatrickyquestion,AsIsaidmethodoverridingisagoodtopicto
asktrickquestionsinJava.Anyway,youcannotoverrideprivateorstaticmethodin
Java,ifyoucreatesimilarmethodwithsamereturntypeandsamemethod
argumentsthat'scalledmethodhiding.
20.WhatwillhappenifweputakeyobjectinaHashMapwhichisalready
there?
ThistrickyJavaquestionsispartofHowHashMapworksinJava,whichisalsoa
populartopictocreateconfusingandtrickyquestioninJava.wellifyouputthesame
keyagainthanitwillreplacetheoldmappingbecauseHashMapdoesn'tallow
duplicatekeys.
21.IfamethodthrowsNullPointerExceptioninsuperclass,canweoverrideit
withamethodwhichthrowsRuntimeException?
OnemoretrickyJavaquestionsfromoverloadingandoverridingconcept.Answeris
youcanverywellthrowsuperclassofRuntimeExceptioninoverriddenmethodbut
youcannotdosameifitscheckedException.
22.WhatistheissuewithfollowingimplementationofcompareTo()methodin
Java
publicintcompareTo(Objecto){
Employeeemp=(Employee)emp
returnthis.ido.id
}
23.HowdoyouensurethatNthreadcanaccessNresourceswithoutdeadlock
Ifyouarenotwellversedinwritingmultithreadingcodethenthisisrealtricky
questionforyou.ThisJavaquestioncanbetrickyevenforexperiencedandsenior
programmer,whoarenotreallyexposedtodeadlockandraceconditions.Keypoint
hereisorder,ifyouacquireresourcesinaparticularorderandreleaseresourcesin
reverseorderyoucanpreventdeadlock.
24.WhatisdifferencebetweenCyclicBarrierandCountDownLatchinJava
RelativelynewerJavatrickyquestion,onlybeenintroducedformJava5.Main
differencebetweenbothofthemisthatyoucanreuseCyclicBarrierevenifBarrieris
brokenbutyoucannotreuseCountDownLatchinJava.SeeCyclicBarriervs
CountDownLatchinJavaformoredifferences.
25.Canyouaccessnonstaticvariableinstaticcontext?
AnothertrickyJavaquestionfromJavafundamentals.Noyoucannotaccessstatic

AnothertrickyJavaquestionfromJavafundamentals.Noyoucannotaccessstatic
variableinnonstaticcontextinJava.Readwhyyoucannotaccessnonstatic
variablefromstaticmethodtolearnmoreaboutthistrickyJavaquestions.

Das könnte Ihnen auch gefallen