Sunteți pe pagina 1din 6

uestion:WhatdoesthefollowingJavaprogramprint?

publicclassTest{
publicstaticvoidmain(String[]args){
System.out.println(Math.min(Double.MIN_VALUE,0.0d));
}
}

Answer:ThisquestionsistrickybecauseunliketheInteger,whereMIN_VALUEisnegative,both
theMAX_VALUEandMIN_VALUEoftheDoubleclassarepositivenumbers.
TheDouble.MIN_VALUEis2^(1074),adoubleconstantwhosemagnitudeistheleastamong
alldoublevalues.Sounliketheobviousanswer,thisprogramwillprint0.0
becauseDouble.MIN_VALUEisgreaterthan0.IhaveaskedthisquestiontoJavadeveloperhaving
experienceupto3to5yearsandsurprisinglyalmost70%candidategotitwrong.

Question:WhatwillhappenifyouputreturnstatementorSystem.exit()ontryor
catchblock?Willfinallyblockexecute?
ThisisaverypopulartrickyJavaquestionandit'strickybecausemanyprogrammersthinkthat
nomatterwhat,butthefinallyblockwillalwaysexecute.Thisquestionchallengethatconcept
byputtingareturnstatementinthetryorcatchblockorcallingSystem.exitfromtryor
catchblock.AnswerofthistrickyquestioninJavaisthatfinallyblockwillexecuteevenif
youputareturnstatementinthetryblockorcatchblockbutfinallyblockwon'trunifyou
callSystem.exitformtryorcatch.

Question:CanyouoverrideaprivateorstaticmethodinJava?
AnotherpopularJavatrickyquestion,AsIsaidmethodoverridingisagoodtopictoasktrick
questionsinJava.Anyway,youcannotoverrideaprivateorstaticmethodinJava,ifyoucreate
asimilarmethodwithsamereturntypeandsamemethodargumentsinchildclassthenitwill
hidethesuperclassmethod,thisisknownasmethodhiding.Similarly,youcannotoverridea
privatemethodinsubclassbecauseit'snotaccessiblethere,whatyoudoiscreateanother
privatemethodwiththesamenameinthechildclass.SeeCanyouoverrideaprivatemethodin
Javaormoredetails.

Question:Whatdotheexpression1.0/0.0willreturn?willitthrowException?any
compiletimeerror?
Answer:ThisisanothertrickyquestionfromDoubleclass.ThoughJavadeveloperknowsaboutthe

doubleprimitivetypeandDoubleclass,whiledoingfloatingpointarithmetictheydon'tpay
enoughattentiontoDouble.INFINITY,NaN,and0.0andotherrulesthatgovernthe
arithmeticcalculationsinvolvingthem.Thesimpleanswertothisquestionisthatitwillnot
throwArithmeticExcpetionandreturnDouble.INFINITY.Also,notethatthecomparisonx
==Double.NaNalwaysevaluatestofalse,evenifxitselfisaNaN.TotestifxisaNaN,one
shouldusethemethodcallDouble.isNaN(x)tocheckifgivennumberisNaNornot.Ifyouknow
SQL,thisisveryclosetoNULLthere.

DoesJavasupportmultipleinheritances?
ThisisthetrickiestquestioninJavaifC++cansupportdirectmultipleinheritancethanwhynot
JavaistheargumentIntervieweroftengive.Answerofthisquestionismuchmoresubtlethenit
lookslike,becauseJavadoessupportmultipleinheritancesofTypebyallowinganinterfaceto
extendotherinterfaces,whatJavadoesn'tsupportismultipleinheritancesofimplementation.This
distinctionalsogetsblurbecauseofdefaultmethodofJava8,whichnowprovidesJava,multiple
inheritancesofbehavioraswell.SeeWhymultipleinheritanceisnotsupportedinJavatoanswer
thistrickyJavaquestion.

WhatwillhappenifweputakeyobjectinaHashMapwhichisalreadythere?
ThistrickyJavaquestionispartofanotherfrequentlyaskedquestion,HowHashMapworksin
Java.HashMapisalsoapopulartopictocreateconfusingandtrickyquestioninJava.Answer
ofthisquestionisifyouputthesamekeyagainthenitwillreplacetheoldmappingbecause
HashMapdoesn'tallowduplicatekeys.TheSamekeywillresultinthesamehashcodeandwill
endupatthesamepositioninthebucket.EachbucketcontainsalinkedlistofMap.Entry
object,whichcontainsbothKeyandValue.NowJavawilltakeKeyobjectformeachentryand
comparewiththisnewkeyusingequals()method,ifthatreturntruethenvalueobjectinthat
entrywillbereplacedbynewvalue.SeeHowHashMapworksinJavaformoretrickyJava
questionsfromHashMap.
Question:WhatdoesthefollowingJavaprogramprint?
publicclassTest{
publicstaticvoidmain(String[]args)throwsException{
char[]chars=newchar[]{'\u0097'};
Stringstr=newString(chars);
byte[]bytes=str.getBytes();
System.out.println(Arrays.toString(bytes));
}
}

Answer:ThetrickinessofthisquestionliesoncharacterencodingandhowStringtobytearray
conversionworks.Inthisprogram,wearefirstcreatingaStringfromacharacterarray,whichjust
hasonecharacter'\u0097',afterthanwearegettingbytearrayfromthatStringandprintingthat
byte.Since\u0097iswithinthe8bitrangeofbyteprimitivetype,itisreasonabletoguessthat
thestr.getBytes()callwillreturnabytearraythatcontainsoneelementwithavalueof
105((byte)0x97).However,that'snotwhattheprogramprintsandthat'swhythisquestionis
tricky.Asamatteroffact,theoutputoftheprogramisoperatingsystemandlocaledependent.On
aWindowsXPwiththeUSlocale,theaboveprogramprints[63],ifyourunthisprogramonLinux
orSolaris,youwillgetdifferentvalues.
Toanswerthisquestioncorrectly,youneedtoknowabouthowUnicodecharactersarerepresented
inJavacharvaluesandinJavastrings,andwhatrolecharacterencodingplays
inString.getBytes().Insimpleword,toconvertastringtoabytearray,Javaiterate
throughallthecharactersthatthestringrepresentsandturneachoneintoanumberofbytesand
finallyputthebytestogether.TherulethatmapseachUnicodecharacterintoabytearrayiscalled
acharacterencoding.SoIt'spossiblethatifsamecharacterencodingisnotusedduringboth
encodinganddecodingthenretrievedvaluemaynotbecorrect.Whenwe
callstr.getBytes()withoutspecifyingacharacterencodingscheme,theJVMusesthedefault
characterencodingoftheplatformtodothejob.Thedefaultencodingschemeisoperatingsystem
andlocaledependent.OnLinux,itisUTF8andonWindowswithaUSlocale,thedefaultencoding
isCp1252.ThisexplainstheoutputwegetfromrunningthisprogramonWindowsmachineswith
aUSlocale.Nomatterwhichcharacterencodingschemeisused,Javawillalwaystranslate
Unicodecharactersnotrecognizedbytheencodingto63,whichrepresentsthecharacterU+003F
(thequestionmark,?)inallencodings.

IfamethodthrowsNullPointerExceptioninthesuperclass,canweoverrideitwitha
methodwhichthrowsRuntimeException?
OnemoretrickyJavaquestionsfromtheoverloadingandoverridingconcept.Theansweris
youcanverywellthrowsuperclassofRuntimeExceptioninoverriddenmethod,butyoucannot
dosameifitscheckedException.SeeRulesofmethodoverridinginJavaformoredetails.

WhatistheissuewithfollowingimplementationofcompareTo()methodinJava
publicintcompareTo(Objecto){
Employeeemp=(Employee)emp;

returnthis.ido.id;
}

wheretheidisanintegernumber.
Well,threeisnothingwronginthisJavaquestionuntilyouguaranteethatidisalwayspositive.
ThisJavaquestionbecomestrickywhenyoucan'tguaranteethatidispositiveornegative.the
trickypartis,Ifidbecomesnegativethansubtractionmayoverflowandproduceanincorrect
result.SeeHowtooverridecompareTomethodinJavaforthecompleteanswerofthisJava
trickyquestionforanexperiencedprogrammer.

HowdoyouensurethatNthreadcanaccessNresourceswithoutdeadlock
Ifyouarenotwellversedinwritingmultithreadingcodethenthisisarealtrickyquestionfor
you.ThisJavaquestioncanbetrickyevenfortheexperiencedandseniorprogrammer,who
arenotreallyexposedtodeadlockandraceconditions.Thekeypointhereisordering,ifyou
acquireresourcesinaparticularorderandreleaseresourcesinthereverseorderyoucan
preventdeadlock.SeehowtoavoiddeadlockinJavaforasamplecodeexample.

Question:ConsiderthefollowingJavacodesnippet,whichisinitializingtwovariables
andbotharenotvolatile,andtwothreadsT1andT2aremodifyingthesevaluesas
following,botharenotsynchronized
intx=0;
booleanbExit=false;
Thread1(notsynchronized)
x=1;
bExit=true;
Thread2(notsynchronized)
if(bExit==true)
System.out.println("x="+x);

Nowtellus,isitpossibleforThread2toprintx=0?
Answer:It'simpossibleforalistoftrickyJavaquestionstonotcontainanythingfrommulti
threading.ThisisthesimplestoneIcanget.AnswerofthisquestionisYes,It'spossiblethatthread
T2mayprintx=0.Why?becausewithoutanyinstructiontocompilere.g.synchronizedor
volatile,bExit=truemightcomebeforex=1incompilerreordering.Also,x=1mightnotbecome

visibleinThread2,soThread2willloadx=0.Now,howdoyoufixit?WhenIaskedthisquestion
toacoupleofprogrammerstheyanswerdifferently,onesuggeststomakeboththreads
synchronizedonacommonmutex,anotheronesaidmakebothvariablevolatile.Botharecorrect,
asitwillpreventreorderingandguaranteevisibility.Butthebestanswerisyoujustneedto
makebExitasvolatile,thenThread2canonlyprintx=1.xdoesnotneedtobevolatilebecausex
cannotbereorderedtocomeafterbExit=truewhenbExitisvolatile.

WhatisdifferencebetweenCyclicBarrierandCountDownLatchinJava
RelativelynewerJavatrickyquestion,onlybeenintroducedformJava5.Themaindifference
betweenbothofthemisthatyoucanreuseCyclicBarrierevenifBarrierisbroken,butyou
cannotreuseCountDownLatchinJava.SeeCyclicBarriervsCountDownLatchinJavafor
moredifferences.

WhatisthedifferencebetweenStringBufferandStringBuilderinJava?
ClassicJavaquestionswhichsomepeoplethinktrickyandsomeconsidervery
easy.StringBuilderinJavawasintroducedinJDK1.5andtheonlydifferencebetweenboth
ofthemisthatStringBuffermethods
e.g.length(),capacity()orappend()aresynchronizedwhilecorrespondingmethods
inStringBuilderarenotsynchronized.Becauseofthisfundamentaldifference,
concatenationofStringusingStringBuilderisfasterthanStringBuffer.Actuallyit'sconsidered
thebadpracticetouseStringBufferanymore,because,inalmost99%scenario,youperform
stringconcatenationonthesamethread.SeeStringBuildervsStringBufferformore
differences.

Canyouaccessanonstaticvariableinthestaticcontext?
AnothertrickyJavaquestionfromJavafundamentals.No,youcannotaccessanonstatic
variablefromthestaticcontextinJava.Ifyoutry,itwillgivecompiletimeerror.Thisisactually
acommonproblembeginnerinJavafacewhentheytrytoaccessinstancevariableinsidethe
mainmethod.BecausemainisstaticinJava,andinstancevariablesarenonstatic,youcannot
accessinstancevariableinsidemain.Readwhyyoucannotaccessanonstaticvariablefrom
staticmethodtolearnmoreaboutthistrickyJavaquestions.
Now,it'spracticetime,herearesomequestionsforyouguystoanswer,thesearecontributedby
readersofthisblog,bigthankstothem.

1.WhenSingletondoesn'tremainSingletoninJava?
2.isitpossibletoloadaclassbytwoClassLoader?
3.isitpossibleforequals()toreturnfalse,evenifcontentsoftwoObjectsaresame?
4.WhycompareTo()shouldbeconsistenttoequals()methodinJava?
5.WhendoDoubleandBigDecimalgivedifferentanswersforequals()andcompareTo()==0.
6.Howdoes"hasbefore"applytovolatilework?
7.Whyis0.1*3!=0.3,
8.Whyis(Integer)1==(Integer)1but(Integer)222!=(Integer)222andwhichcommand
argumentschangethis.
9.WhathappenswhenexceptionisthrownbyaThread?
10.Differencebetweennotify()andnotifyAll()call?
11.DifferencebetweenSystem.exit()andSystem.halt()method?
12.DoesfollowingcodelegalinJava?isitexampleofmethodoverloadingoroverriding?
publicStringgetDescription(Objectobj){
returnobj.toString;
}
publicStringgetDescription(Stringobj){
returnobj;
}
and
publicvoidgetDescription(Stringobj){
returnobj;
}

S-ar putea să vă placă și