0% found this document useful (0 votes)
625 views

Top 10 Tricky Java Interview Questions and Answers - Java67

This document contains explanations and answers to several tricky Java programming questions. Some key points: - Double.MIN_VALUE is greater than 0, so a program printing Math.min(Double.MIN_VALUE, 0) will output 0. - A finally block will always execute even if the try or catch block contains a return statement or calls System.exit(). - In Java, methods can be hidden but not overridden if they are private or static. - Dividing 1.0 by 0.0 in Java will return Double.INFINITY rather than throwing an exception. - Java supports multiple inheritance of interfaces but not of implementation classes.

Uploaded by

Rohini Bauskar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
625 views

Top 10 Tricky Java Interview Questions and Answers - Java67

This document contains explanations and answers to several tricky Java programming questions. Some key points: - Double.MIN_VALUE is greater than 0, so a program printing Math.min(Double.MIN_VALUE, 0) will output 0. - A finally block will always execute even if the try or catch block contains a return statement or calls System.exit(). - In Java, methods can be hidden but not overridden if they are private or static. - Dividing 1.0 by 0.0 in Java will return Double.INFINITY rather than throwing an exception. - Java supports multiple inheritance of interfaces but not of implementation classes.

Uploaded by

Rohini Bauskar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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;
}

You might also like