0% found this document useful (0 votes)
213 views6 pages

Tricky Java Interview Questions Explained

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)
213 views6 pages

Tricky Java Interview Questions Explained

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
  • Java Exception Handling Queries
  • Java Program Output Questions
  • Character Encoding and Unicode Challenges
  • Multithreading and Synchronization Problems
  • Java Conceptual Comparisons and Access Queries
  • Java Concept Short Answer Questions

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;
}

uestion: What does the following Java program print?
public class Test { 
    public static void main(String[] args) { 
     
double primitive type and Double class, while doing floating point arithmetic they don't pay
enough attention to Double.INFIN
Answer: The trickiness of this question lies on character encoding and how String to byte array
conversion works. In this pro
   return this.id ‐ o.id; 
}
where the id is an integer number.
Well, three is nothing wrong in this Java question until you 
visible in Thread 2, so Thread 2 will load x=0. Now, how do you fix it? When I asked this question
to a couple of programmers
1. When Singleton doesn't remain Singleton in Java?
2. is it possible to load a class by two ClassLoader?
3. is it possible f

You might also like