uestion:WhatdoesthefollowingJavaprogramprint?
publicclassTest{
publicstaticvoidmain(String[]args){
[Link]([Link](Double.MIN_VALUE,0.0d));
}
}
Answer:ThisquestionsistrickybecauseunliketheInteger,whereMIN_VALUEisnegative,both
theMAX_VALUEandMIN_VALUEoftheDoubleclassarepositivenumbers.
TheDouble.MIN_VALUEis2^(1074),adoubleconstantwhosemagnitudeistheleastamong
[Link],thisprogramwillprint0.0
becauseDouble.MIN_VALUEisgreaterthan0.IhaveaskedthisquestiontoJavadeveloperhaving
experienceupto3to5yearsandsurprisinglyalmost70%candidategotitwrong.
Question:[Link]()ontryor
catchblock?Willfinallyblockexecute?
ThisisaverypopulartrickyJavaquestionandit'strickybecausemanyprogrammersthinkthat
nomatterwhat,[Link]
[Link]
[Link]
youputareturnstatementinthetryblockorcatchblockbutfinallyblockwon'trunifyou
[Link].
Question:CanyouoverrideaprivateorstaticmethodinJava?
AnotherpopularJavatrickyquestion,AsIsaidmethodoverridingisagoodtopictoasktrick
[Link],youcannotoverrideaprivateorstaticmethodinJava,ifyoucreate
asimilarmethodwithsamereturntypeandsamemethodargumentsinchildclassthenitwill
hidethesuperclassmethod,[Link],youcannotoverridea
privatemethodinsubclassbecauseit'snotaccessiblethere,whatyoudoiscreateanother
[Link]
Javaormoredetails.
Question:Whatdotheexpression1.0/0.0willreturn?willitthrowException?any
compiletimeerror?
Answer:[Link]
doubleprimitivetypeandDoubleclass,whiledoingfloatingpointarithmetictheydon'tpay
[Link],NaN,and0.0andotherrulesthatgovernthe
[Link]
[Link],notethatthecomparisonx
==[Link],[Link],one
[Link](x)[Link]
SQL,thisisveryclosetoNULLthere.
DoesJavasupportmultipleinheritances?
ThisisthetrickiestquestioninJavaifC++cansupportdirectmultipleinheritancethanwhynot
[Link]
lookslike,becauseJavadoessupportmultipleinheritancesofTypebyallowinganinterfaceto
extendotherinterfaces,whatJavadoesn'[Link]
distinctionalsogetsblurbecauseofdefaultmethodofJava8,whichnowprovidesJava,multiple
[Link]
thistrickyJavaquestion.
WhatwillhappenifweputakeyobjectinaHashMapwhichisalreadythere?
ThistrickyJavaquestionispartofanotherfrequentlyaskedquestion,HowHashMapworksin
[Link]
ofthisquestionisifyouputthesamekeyagainthenitwillreplacetheoldmappingbecause
HashMapdoesn'[Link]
[Link]
object,[Link]
comparewiththisnewkeyusingequals()method,ifthatreturntruethenvalueobjectinthat
[Link]
questionsfromHashMap.
Question:WhatdoesthefollowingJavaprogramprint?
publicclassTest{
publicstaticvoidmain(String[]args)throwsException{
char[]chars=newchar[]{'\u0097'};
Stringstr=newString(chars);
byte[]bytes=[Link]();
[Link]([Link](bytes));
}
}
Answer:ThetrickinessofthisquestionliesoncharacterencodingandhowStringtobytearray
[Link],wearefirstcreatingaStringfromacharacterarray,whichjust
hasonecharacter'\u0097',afterthanwearegettingbytearrayfromthatStringandprintingthat
[Link]\u0097iswithinthe8bitrangeofbyteprimitivetype,itisreasonabletoguessthat
[Link]()callwillreturnabytearraythatcontainsoneelementwithavalueof
105((byte)0x97).However,that'snotwhattheprogramprintsandthat'swhythisquestionis
[Link],[Link]
aWindowsXPwiththeUSlocale,theaboveprogramprints[63],ifyourunthisprogramonLinux
orSolaris,youwillgetdifferentvalues.
Toanswerthisquestioncorrectly,youneedtoknowabouthowUnicodecharactersarerepresented
inJavacharvaluesandinJavastrings,andwhatrolecharacterencodingplays
[Link]().Insimpleword,toconvertastringtoabytearray,Javaiterate
throughallthecharactersthatthestringrepresentsandturneachoneintoanumberofbytesand
[Link]
[Link]'spossiblethatifsamecharacterencodingisnotusedduringboth
[Link]
[Link]()withoutspecifyingacharacterencodingscheme,theJVMusesthedefault
[Link]
[Link],itisUTF8andonWindowswithaUSlocale,thedefaultencoding
[Link]
[Link],Javawillalwaystranslate
Unicodecharactersnotrecognizedbytheencodingto63,whichrepresentsthecharacterU+003F
(thequestionmark,?)inallencodings.
IfamethodthrowsNullPointerExceptioninthesuperclass,canweoverrideitwitha
methodwhichthrowsRuntimeException?
[Link]
youcanverywellthrowsuperclassofRuntimeExceptioninoverriddenmethod,butyoucannot
[Link].
WhatistheissuewithfollowingimplementationofcompareTo()methodinJava
publicintcompareTo(Objecto){
Employeeemp=(Employee)emp;
[Link];
}
wheretheidisanintegernumber.
Well,threeisnothingwronginthisJavaquestionuntilyouguaranteethatidisalwayspositive.
ThisJavaquestionbecomestrickywhenyoucan'[Link]
trickypartis,Ifidbecomesnegativethansubtractionmayoverflowandproduceanincorrect
[Link]
trickyquestionforanexperiencedprogrammer.
HowdoyouensurethatNthreadcanaccessNresourceswithoutdeadlock
Ifyouarenotwellversedinwritingmultithreadingcodethenthisisarealtrickyquestionfor
[Link],who
[Link],ifyou
acquireresourcesinaparticularorderandreleaseresourcesinthereverseorderyoucan
[Link].
Question:ConsiderthefollowingJavacodesnippet,whichisinitializingtwovariables
andbotharenotvolatile,andtwothreadsT1andT2aremodifyingthesevaluesas
following,botharenotsynchronized
intx=0;
booleanbExit=false;
Thread1(notsynchronized)
x=1;
bExit=true;
Thread2(notsynchronized)
if(bExit==true)
[Link]("x="+x);
Nowtellus,isitpossibleforThread2toprintx=0?
Answer:It'simpossibleforalistoftrickyJavaquestionstonotcontainanythingfrommulti
[Link],It'spossiblethatthread
T2mayprintx=[Link]?[Link]
volatile,bExit=truemightcomebeforex=[Link],x=1mightnotbecome
visibleinThread2,soThread2willloadx=[Link],howdoyoufixit?WhenIaskedthisquestion
toacoupleofprogrammerstheyanswerdifferently,onesuggeststomakeboththreads
synchronizedonacommonmutex,[Link],
[Link]
makebExitasvolatile,thenThread2canonlyprintx=[Link]
cannotbereorderedtocomeafterbExit=truewhenbExitisvolatile.
WhatisdifferencebetweenCyclicBarrierandCountDownLatchinJava
RelativelynewerJavatrickyquestion,[Link]
betweenbothofthemisthatyoucanreuseCyclicBarrierevenifBarrierisbroken,butyou
[Link]
moredifferences.
WhatisthedifferencebetweenStringBufferandStringBuilderinJava?
ClassicJavaquestionswhichsomepeoplethinktrickyandsomeconsidervery
easy.StringBuilderinJavawasintroducedinJDK1.5andtheonlydifferencebetweenboth
ofthemisthatStringBuffermethods
[Link](),capacity()orappend()aresynchronizedwhilecorrespondingmethods
[Link],
[Link]'sconsidered
thebadpracticetouseStringBufferanymore,because,inalmost99%scenario,youperform
[Link]
differences.
Canyouaccessanonstaticvariableinthestaticcontext?
[Link],youcannotaccessanonstatic
[Link],[Link]
acommonproblembeginnerinJavafacewhentheytrytoaccessinstancevariableinsidethe
[Link],andinstancevariablesarenonstatic,youcannot
[Link]
staticmethodtolearnmoreaboutthistrickyJavaquestions.
Now,it'spracticetime,herearesomequestionsforyouguystoanswer,thesearecontributedby
readersofthisblog,bigthankstothem.
[Link]'tremainSingletoninJava?
[Link]?
[Link]()toreturnfalse,evenifcontentsoftwoObjectsaresame?
[Link]()shouldbeconsistenttoequals()methodinJava?
[Link]()andcompareTo()==0.
[Link]"hasbefore"applytovolatilework?
7.Whyis0.1*3!=0.3,
[Link](Integer)1==(Integer)1but(Integer)222!=(Integer)222andwhichcommand
argumentschangethis.
[Link]?
[Link]()andnotifyAll()call?
[Link]()[Link]()method?
[Link]?isitexampleofmethodoverloadingoroverriding?
publicStringgetDescription(Objectobj){
[Link];
}
publicStringgetDescription(Stringobj){
returnobj;
}
and
publicvoidgetDescription(Stringobj){
returnobj;
}