You are on page 1of 48

6/16/2015

28thJune2014

JavaInterviewQuestions

JavaInterviewQuestions

[http://2.bp.blogspot.com/7Z1VZHYyxeg/U670Z2WkT3I/AAAAAAAAB2I/Ykz6ANsQwiQ/s1600/interview11.jpg]

JavainterviewQuestions

1.WhatisJVM?
TheJavainterpreteralongwiththeruntimeenvironmentrequiredtoruntheJavaapplicationincalledasJava
virtualmachine(JVM)
2.WhatisthemostimportantfeatureofJava?
Javaisaplatformindependentlanguage.
3.Whatdoyoumeanbyplatformindependence?
Platformindependencemeansthatwecanwriteandcompilethejavacodeinoneplatform(egWindows)and
canexecutetheclassinanyothersupportedplatformeg(Linux,Solaris,etc).
4.WhatisthedifferencebetweenaJDKandaJVM?
JDKisJavaDevelopmentKitwhichisfordevelopmentpurposeanditincludesexecutionenvironmentalso.But
JVMispurelyaruntimeenvironmentandhenceyouwillnotbeabletocompileyoursourcefilesusingaJVM.
5.Whatisthebaseclassofallclasses?
java.lang.Object
6.WhataretheaccessmodifiersinJava?
Thereare3accessmodifiers.Public,protectedandprivate,andthedefaultoneifnoidentifierisspecifiedis
calledfriendly,butprogrammercannotspecifythefriendlyidentifierexplicitly.
7.Whatisarepackages?
Apackageisacollectionofrelatedclassesandinterfacesprovidingaccessprotectionandnamespace
management.

http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

1/48

6/16/2015

JavaInterviewQuestions

8.WhatismeantbyInheritanceandwhatareitsadvantages?
Inheritanceistheprocessofinheritingallthefeaturesfromaclass.Theadvantagesofinheritanceare
reusabilityofcodeandaccessibilityofvariablesandmethodsofthesuperclassbysubclasses.
9.Whatisthedifferencebetweensuperclassandsubclass?
Asuperclassisaclassthatisinheritedwhereassubclassisaclassthatdoestheinheriting.
10.Whatisanabstractclass?
Anabstractclassisaclassdesignedwithimplementationgapsforsubclassestofillinandisdeliberately
incomplete.
11.Whatarethestatesassociatedinthethread?
Threadcontainsready,running,waitinganddeadstates.
12.Whatissynchronization?
Synchronizationisthemechanismthatensuresthatonlyonethreadisaccessedtheresourcesatatime.
13.Whatisdeadlock?
Whentwothreadsarewaitingeachotherandcantprecedetheprogramissaidtobedeadlock.
14.Whatisanapplet?
Appletisadynamicandinteractiveprogramthatrunsinsideawebpagedisplayedbyajavacapablebrowser
15.Whatisthelifecycleofanapplet?
init()methodCanbecalledwhenanappletisfirstloaded
start()methodCanbecalledeachtimeanappletisstarted.
paint()methodCanbecalledwhentheappletisminimizedormaximized.
stop()methodCanbeusedwhenthebrowsermovesofftheappletspage.
destroy()methodCanbecalledwhenthebrowserisfinishedwiththeapplet.
16.Howdoyousetsecurityinapplets?
usingsetSecurityManager()method
17.WhatisalayoutmanagerandwhataredifferenttypesoflayoutmanagersavailableinjavaAWT?
Alayoutmanagerisanobjectthatisusedtoorganizecomponentsinacontainer.Thedifferentlayoutsare
availableareFlowLayout,BorderLayout,CardLayout,GridLayoutandGridBagLayout
18.WhatisJDBC?
JDBCisasetofJavaAPIforexecutingSQLstatements.ThisAPIconsistsofasetofclassesandinterfaces
toenableprogramstowritepureJavaDatabaseapplications.
19.Whataredriversavailable?
a)JDBCODBCBridgedriverb)NativeAPIPartlyJavadriver
c)JDBCNetPureJavadriverd)NativeProtocolPureJavadriver
20.Whatisstoredprocedure?
StoredprocedureisagroupofSQLstatementsthatformsalogicalunitandperformsaparticulartask.Stored
Proceduresareusedtoencapsulateasetofoperationsorqueriestoexecuteondatabase.Storedprocedures
canbecompiledandexecutedwithdifferentparametersandresultsandmayhaveanycombinationof
input/outputparameters.
21.WhatistheJavaAPI?
TheJavaAPIisalargecollectionofreadymadesoftwarecomponentsthatprovidemanyusefulcapabilities,
suchasgraphicaluserinterface(GUI)widgets.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

2/48

6/16/2015

JavaInterviewQuestions

22.WhytherearenoglobalvariablesinJava?
Globalvariablesaregloballyaccessible.Javadoesnotsupportgloballyaccessiblevariablesduetofollowing
reasons:
1)Theglobalvariablesbreaksthereferentialtransparency
2)Globalvariablescreatescollisionsinnamespace.
23.WhatareEncapsulation,InheritanceandPolymorphism?
Encapsulationisthemechanismthatbindstogethercodeanddataitmanipulatesandkeepsbothsafefrom
outsideinterferenceandmisuse.Inheritanceistheprocessbywhichoneobjectacquiresthepropertiesof
anotherobject.Polymorphismisthefeaturethatallowsoneinterfacetobeusedforgeneralclassactions.
24.WhatistheuseofbinandlibinJDK?
Bincontainsalltoolssuchasjavac,appletviewer,awttool,etc.,whereaslibcontainsAPIandallpackages.
25.Whatismethodoverloadingandmethodoverriding?
Methodoverloading:Whenamethodinaclasshavingthesamemethodnamewithdifferentargumentsissaid
tobemethodoverloading.Methodoverriding:Whenamethodinaclasshavingthesamemethodnamewith
sameargumentsissaidtobemethodoverriding.
26.Whatisthedifferencebetweenthis()andsuper()?
this()canbeusedtoinvokeaconstructorofthesameclasswhereassuper()canbeusedtoinvokeasuper
classconstructor.
27.WhatisDomainNamingService(DNS)?
Itisverydifficulttorememberasetofnumbers(IPaddress)toconnecttotheInternet.TheDomainNaming
Service(DNS)isusedtoovercomethisproblem.ItmapsoneparticularIPaddresstoastringofcharacters.For
example,www.mascom.comimpliescomisthedomainnamereservedforUScommercialsites,moscomis
thenameofthecompanyandwwwisthenameofthespecificcomputer,whichismascomsserver.
28.WhatisURL?
URLstandsforUniformResourceLocatoranditpointstoresourcefilesontheInternet.URLhasfour
components:http://www[http://www/].address.com:80/index.html,wherehttpprotocolname,addressIP
addressorhostname,80portnumberandindex.htmlfilepath.
29.WhatisRMIandstepsinvolvedindevelopinganRMIobject?
RemoteMethodInvocation(RMI)allowsjavaobjectthatexecutesononemachineandtoinvokethemethodof
aJavaobjecttoexecuteonanothermachine.ThestepsinvolvedindevelopinganRMIobjectare:a)Definethe
interfacesb)Implementingtheseinterfacesc)Compiletheinterfacesandtheirimplementationswiththejava
compilerd)CompiletheserverimplementationwithRMIcompilere)RuntheRMIregistryf)Runtheapplication.
30.WhatisRMIarchitecture?
RMIarchitectureconsistsoffourlayersandeachlayerperformsspecificfunctions:a)Applicationlayer
containstheactualobjectdefinition.b)Proxylayerconsistsofstubandskeleton.c)RemoteReferencelayer
getsthestreamofbytesfromthetransportlayerandsendsittotheproxylayer.d)Transportationlayer
responsibleforhandlingtheactualmachinetomachinecommunication.
31.WhatisaJavaBean?
AJavaBeanisasoftwarecomponentthathasbeendesignedtobereusableinavarietyofdifferent
environments.
32.Whatarecheckedexceptions?
CheckedexceptionarethosewhichtheJavacompilerforcesyoutocatch.e.g.IOExceptionarechecked
Exceptions.

http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

3/48

6/16/2015

JavaInterviewQuestions

33.Whatareruntimeexceptions?
Runtimeexceptionsarethoseexceptionsthatarethrownatruntimebecauseofeitherwronginputdataor
becauseofwrongbusinesslogicetc.Thesearenotcheckedbythecompileratcompiletime.
34.Whatisthedifferencebetweenerrorandanexception?
Anerrorisanirrecoverableconditionoccurringatruntime.SuchasOutOfMemoryerror.TheseJVMerrorsand
youcannotrepairthematruntime.Whileexceptionsareconditionsthatoccurbecauseofbadinputetc.e.g.
FileNotFoundExceptionwillbethrownifthespecifiedfiledoesnotexist.OraNullPointerExceptionwilltake
placeifyoutryusinganullreference.Inmostofthecasesitispossibletorecoverfromanexception(probably
bygivinguserafeedbackforenteringpropervaluesetc.).
35.Whatisthepurposeoffinalization?
Thepurposeoffinalizationistogiveanunreachableobjecttheopportunitytoperformanycleanupprocessing
beforetheobjectisgarbagecollected.Forexample,closingaopenedfile,closingaopeneddatabase
Connection.
36.Whatisthedifferencebetweenyieldingandsleeping?
Whenataskinvokesitsyield()method,itreturnstothereadystate.Whenataskinvokesitssleep()method,it
returnstothewaitingstate.
37.Whatisthedifferencebetweenpreemptiveschedulingandtimeslicing?
Underpreemptivescheduling,thehighestprioritytaskexecutesuntilitentersthewaitingordeadstatesora
higherprioritytaskcomesintoexistence.Undertimeslicing,ataskexecutesforapredefinedsliceoftimeand
thenreentersthepoolofreadytasks.Theschedulerthendetermineswhichtaskshouldexecutenext,basedon
priorityandotherfactors.
38.Whatismutableobjectandimmutableobject?
IfaobjectvalueischangeablethenwecancallitasMutableobject.(Ex.,StringBuffer,)Ifyouarenot
allowedtochangethevalueofanobject,itisimmutableobject.(Ex.,String,Integer,Float,)
39.WhatisthepurposeofVoidclass?
TheVoidclassisanuninstantiableplaceholderclasstoholdareferencetotheClassobjectrepresentingthe
primitiveJavatypevoid.
40.WhatisJITanditsuse?
Really,justaveryfastcompilerInthisincarnation,prettymuchaonepasscompilernooffline
computations.Soyoucantlookatthewholemethod,ranktheexpressionsaccordingtowhichonesarereused
themost,andthengeneratecode.Intheoryterms,itsanonlineproblem.
41.Whatisnestedclass?
Ifallthemethodsofainnerclassisstaticthenitisanestedclass.
42.WhatisHashMapandMap?
MapisInterfaceandHashmapisclassthatimplementsthat.
43.Whataredifferenttypesofaccessmodifiers?
public:Anythingdeclaredaspubliccanbeaccessedfromanywhere.private:Anythingdeclaredasprivate
cantbeseenoutsideofitsclass.protected:Anythingdeclaredasprotectedcanbeaccessedbyclassesinthe
samepackageandsubclassesintheotherpackages.defaultmodifier:Canbeaccessedonlytoclassesinthe
samepackage.
44.WhatisthedifferencebetweenReader/WriterandInputStream/OutputStream?
TheReader/WriterclassischaracterorientedandtheInputStream/OutputStreamclassisbyteoriented.
45.Whatisservlet?
Servletsaremodulesthatextendrequest/responseorientedservers,suchasjavaenabledwebservers.For
example,aservletmightberesponsiblefortakingdatainanHTMLorderentryformandapplyingthebusiness
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

4/48

6/16/2015

JavaInterviewQuestions

logicusedtoupdateacompanysorderdatabase.
46.WhatisConstructor?
Aconstructorisaspecialmethodwhosetaskistoinitializetheobjectofitsclass.
Itisspecialbecauseitsnameisthesameastheclassname.
Theydonothavereturntypes,notevenvoidandthereforetheycannotreturnvalues.
Theycannotbeinherited,thoughaderivedclasscancallthebaseclassconstructor.
Constructorisinvokedwheneveranobjectofitsassociatedclassiscreated.
47.WhatisanIterator?
TheIteratorinterfaceisusedtostepthroughtheelementsofaCollection.
IteratorsletyouprocesseachelementofaCollection.
IteratorsareagenericwaytogothroughalltheelementsofaCollectionnomatterhowitisorganized.
IteratorisanInterfaceimplementedadifferentwayforeveryCollection.
48.WhatistheListinterface?
TheListinterfaceprovidessupportfororderedcollectionsofobjects.
Listsmaycontainduplicateelements.
49.Whatismemoryleak?
Amemoryleakiswhereanunreferencedobjectthatwillneverbeusedagainstillhangsaroundinmemoryand
doesntgetgarbagecollected.
50.Whatisthedifferencebetweentheprefixandpostfixformsofthe++operator?
Theprefixformperformstheincrementoperationandreturnsthevalueoftheincrementoperation.Thepostfix
formreturnsthecurrentvaluealloftheexpressionandthenperformstheincrementoperationonthatvalue.
51.Whatisthedifferencebetweenaconstructorandamethod?
Aconstructorisamemberfunctionofaclassthatisusedtocreateobjectsofthatclass.Ithasthesamename
astheclassitself,hasnoreturntype,andisinvokedusingthenewoperator.
Amethodisanordinarymemberfunctionofaclass.Ithasitsownname,areturntype(whichmaybevoid),and
isinvokedusingthedotoperator.
52.WhatwillhappentotheExceptionobjectafterexceptionhandling?
Exceptionobjectwillbegarbagecollected.
53.Differencebetweenstaticanddynamicclassloading.
Staticclassloading:Theprocessofloadingaclassusingnewoperatoriscalledstaticclassloading.Dynamic
classloading:Theprocessofloadingaclassatruntimeiscalleddynamicclassloading.
DynamicclassloadingcanbedonebyusingClass.forName(.).newInstance().
54.ExplaintheCommonuseofEJB
TheEJBscanbeusedtoincorporatebusinesslogicinawebcentricapplication.
TheEJBscanbeusedtointegratebusinessprocessesinBusinesstobusiness(B2B)ecommerce
applications.InEnterpriseApplicationIntegrationapplications,EJBscanbeusedtohouseprocessingand
mappingbetweendifferentapplications.
55.WhatisJSP?
JSPisatechnologythatreturnsdynamiccontenttotheWebclientusingHTML,XMLandJAVAelements.JSP
pagelookslikeaHTMLpagebutisaservlet.ItcontainsPresentationlogicandbusinesslogicofaweb
application.
56.Whatisthepurposeofapachetomcat?
ApacheserverisastandaloneserverthatisusedtotestservletsandcreateJSPpages.Itisfreeandopen
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

5/48

6/16/2015

JavaInterviewQuestions

sourcethatisintegratedintheApachewebserver.Itisfast,reliableservertoconfiguretheapplicationsbutitis
hardtoinstall.Itisaservletcontainerthatincludestoolstoconfigureandmanagetheservertorunthe
applications.ItcanalsobeconfiguredbyeditingXMLconfigurationfiles.
57.Wherepragmaisused?
Pragmaisusedinsidetheservletsintheheaderwithacertainvalue.Thevalueisofnocachethattellsthata
servletsisactingasaproxyandithastoforwardrequest.Pragmadirectivesallowthecompilertousemachine
andoperatingsystemfeatureswhilekeepingtheoverallfunctionalitywiththeJavalanguage.Thesearedifferent
fordifferentcompilers.
58.Brieflyexplaindaemonthread.
Daemonthreadisalowprioritythreadwhichrunsinthebackgroundperformsgarbagecollectionoperationfor
thejavaruntimesystem.
59.Whatisanativemethod?
AnativemethodisamethodthatisimplementedinalanguageotherthanJava.
60.Explaindifferentwayofusingthread?
AJavathreadcouldbeimplementedbyusingRunnableinterfaceorbyextendingtheThreadclass.The
Runnableismoreadvantageous,whenyouaregoingformultipleinheritance.
61.WhatarethetwomajorcomponentsofJDBC?
Oneimplementationinterfacefordatabasemanufacturers,theotherimplementationinterfaceforapplicationand
appletwriters.
62.WhatkindofthreadistheGarbagecollectorthread?
Itisadaemonthread.
63.Whatarethedifferentwaystohandleexceptions?
Therearetwowaystohandleexceptions,
1.Bywrappingthedesiredcodeinatryblockfollowedbyacatchblocktocatchtheexceptions.and
2.Listthedesiredexceptionsinthethrowsclauseofthemethodandletthecallerofthemethodhandlethose
exceptions.
64.Howmanyobjectsarecreatedinthefollowingpieceofcode?
MyClassc1,c2,c3
c1=newMyClass()
c3=newMyClass()
Answer:Only2objectsarecreated,c1andc3.Thereferencec2isonlydeclaredandnotinitialized.
65.WhatisUNICODE?
Unicodeisusedforinternalrepresentationofcharactersandstringsandituses16bitstorepresenteachother
*************************************==============================********************************************

Top 371 Java FAQs Useful for Freshers and Experienced


Q1.WhatisthedifferencebetweenanAbstractclassandInterface?
1. Abstract classes may have some executable methods and methods left
unimplemented.Interfacescontainnoimplementationcode.
2. Anclasscanimplementanynumberofinterfaces,butsubclassatmostoneabstract
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

6/48

6/16/2015

JavaInterviewQuestions

class.
3. Anabstractclasscanhavenonabstractmethods.Allmethodsofaninterfaceare
abstract.
4.Anabstractclasscanhaveinstancevariables.Aninterfacecannot.
5.Anabstractclasscandefineconstructor.Aninterfacecannot.
6.Anabstractclasscanhaveanyvisibility:public,protected,privateornone(package).
Aninterface'svisibilitymustbepublicornone(package).
7. An abstract class inherits from Object and includes methods such as clone() and
equals().
Q2.Whatarecheckedanduncheckedexceptions?
Javadefinestwokindsofexceptions:
Checkedexceptions:ExceptionsthatinheritfromtheExceptionclassare
checkedexceptions.Clientcodehastohandlethecheckedexceptionsthrownby
theAPI,eitherinacatchclauseorbyforwardingitoutwardwiththethrowsclause.
ExamplesSQLException,IOxception.
Uncheckedexceptions:RuntimeExceptionalsoextendsfromException.However,allof
theexceptionsthatinheritfromRuntimeExceptiongetspecialtreatment.Thereisno
requirementfortheclientcodetodealwiththem,andhencetheyarecalledunchecked
exceptions.ExampleUncheckedexceptionsareNullPointerException,OutOfMemoryError,
DivideByZeroExceptiontypically,programmingerrors.
Q3.Whatisauserdefinedexception?
Userdefinedexceptionsmaybeimplementedby
definingaclasstorespondtotheexceptionand
embeddingathrowstatementinthetryblockwheretheexceptioncanoccurordeclaring
thatthemethodthrowstheexception(toanothermethodwhereitishandled).
ThedevelopercandefineanewexceptionbyderivingitfromtheExceptionclassas
follows:publicclassMyExceptionextendsException{/*classdefinitionofconstructors
(butNOTtheexceptionhandlingcode)goesherepublicMyException(){
super()
}
public MyException( String errorMessage ) { super(
errorMessage)
}

[https://www.blogger.com/null]

}
Thethrowstatementisusedtosignaltheoccuranceoftheexceptionwithinatry
block.Often,
exceptionsareinstantiatedinthesamestatementinwhichtheyarethrownusingthe
syntax.
thrownewMyException("Ithrewmyownexception.")
Tohandletheexceptionwithinthemethodwhereitisthrown,acatchstatementthat
handles
MyException,mustfollowthetryblock.Ifthedeveloperdoesnotwanttohandlethe
exceptioninthemethoditself,themethodmustpasstheexceptionusingthesyntax:public
myMethodName()throwsMyException
Q4.WhatisthedifferencebetweenC++&Java?
WellasBjarneStroustrupsays"..despitethesyntacticsimilarities,C++andJavaare
very
differentlanguages.Inmanyways,JavaseemsclosertoSmalltalkthantoC++..".Here
arefewIdiscovered:
Javaismultithreaded
Javahasnopointers
Javahasautomaticmemorymanagement(garbagecollection)
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

7/48

6/16/2015

JavaInterviewQuestions

Javaisplatformindependent(Stroustrupmaydifferbysaying"Javaisaplatform"
Javahasbuiltinsupportforcommentdocumentation
Javahasnooperatoroverloading
Javadoesntprovidemultipleinheritance
TherearenodestructorsinJava
Q5.WhatarestatementsinJAVA?
Statementsareequivalenttosentencesinnaturallanguages.Astatementformsacomplete
unitofexecution.Thefollowingtypesofexpressionscanbemadeintoastatementby
terminatingtheexpressionwithasemicolon
Assignmentexpressions
Anyuseof++or
Methodcalls
Objectcreationexpressions
Thesekindsofstatementsarecalledexpressionstatements.Inadditiontothesekindsof
expressionstatements,therearetwootherkindsofstatements.Adeclaration
statement
declaresavariable.Acontrolflowstatementregulatestheorderinwhichstatementsget
executed.Theforloopandtheifstatementarebothexamplesofcontrolflowstatements.
Q6.WhatisJARfile?
JavaARchivefilesareabigglobofJavaclasses,images,audio,etc.,
compressedtomakeonesimple,smallerfiletoeaseAppletdownloading.Normallywhena
browserencountersanapplet,itgoesanddownloadsallthefiles,images,audio,usedby
theAppletseparately.Thiscanleadtoslowerdownloads.
Q7.WhatisJNI?
JNIisanacronymofJavaNativeInterface.UsingJNIwecancallfunctionswhichare
writteninotherlanguagesfromJava.Followingareitsadvantagesanddisadvantages.
Advantages:
Youwanttouseyourexistinglibrarywhichwaspreviouslywritteninotherlanguage.
YouwanttocallWindowsAPIfunction.
Forthesakeofexecutionspeed.
YouwanttocallAPIfunctionofsomeserverproductwhichisincorc++fromjava
client.
Disadvantages:
Youcantsaywriteoncerunanywhere.
Difficulttodebugruntimeerrorinnativecode.
Potentialsecurityrisk.
YoucantcallitfromApplet.
Q8.Whatisserialization?
Quitesimply,objectserializationprovidesaprogramtheabilitytoreadorwriteawhole
object
toandfromarawbytestream.ItallowsJavaobjectsandprimitivestobeencodedintoa
bytestreamsuitableforstreamingtosometypeofnetworkortoafilesystem,ormore
generally,toatransmissionmediumorstoragefacility.Aseralizableobjectmustimplement
theSerilizable
interface.WeuseObjectOutputStreamtowritethisobjecttoastreamand
ObjectInputStreamtoreaditfromthestream.
Q9.Whytherearesomenullinterfaceinjava?Whatdoesitmean?Giveme
somenullinterfacesinJAVA?
Nullinterfacesactasmarkers..theyjusttellthecompilerthattheobjectsofthisclassneed
tobetreateddifferently..somemarkerinterfacesare:Serializable,Remote,Cloneable.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

8/48

6/16/2015

JavaInterviewQuestions

Q10.Issynchronizedamodifier?Identifier?Whatisit??
It'samodifier.Synchronizedmethodsaremethodsthatareusedtocontrolaccessto
anobject.Athreadonlyexecutesasynchronizedmethodafterithasacquiredthelock
forthemethod'sobjectorclass.Synchronizedstatementsaresimilartosynchronized
methods.Asynchronized
statementcanonlybeexecutedafterathreadhasacquiredthelockfortheobjector
classreferencedinthesynchronizedstatement.
Q11.Whatissingletonclass?whereisitused?
Singletonisadesignpatternmeanttoprovideoneandonlyoneinstanceofanobject.
Other
objectscangetareferencetothisinstancethroughastaticmethod(classconstructoris
kept
private).Whydoweneedone?Sometimesitisnecessary,andoftensufficient,tocreatea
singleinstanceofagivenclass.Thishasadvantagesinmemorymanagement,andfor
Java,ingarbagecollection.Moreover,restrictingthenumberofinstancesmaybe
necessaryordesirablefor
technologicalorbusinessreasonsforexample,wemayonlywantasingleinstance
ofapoolofdatabaseconnections.
Q12.Whatisacompilationunit?
Thesmallestunitofsourcecodethatcanbecompiled,i.e.a.javafile.
Q13.Isstringsawrapperclass?
Stringisaclass,butnotawrapperclass.Wrapperclasseslike(Integer)existforeach
primitivetype.Theycanbeusedtoconvertaprimitivedatavalueintoanobject,andvice
versa.
Q14.Whyjavadoesnothavemultipleinheritances?
TheJavadesignteamstrovetomakeJava:
Simple,objectoriented,andfamiliar
Robustandsecure
Architectureneutralandportable
Highperformance
Interpreted,threaded,anddynamic
ThereasonsforomittingmultipleinheritancefromtheJavalanguagemostlystem
fromthe
"simple,objectoriented,andfamiliar"goal.Asasimplelanguage,Java'screatorswanted
a
languagethatmostdeveloperscouldgraspwithoutextensivetraining.Tothatend,they
workedtomakethelanguageassimilartoC++aspossible(familiar)withoutcarryingover
C++'sunnecessarycomplexity(simple).
Inthedesigners'opinion,multipleinheritancecausesmoreproblemsandconfusionthanit
solves.Sotheycutmultipleinheritancefromthelanguage(justastheycutoperator
overloading).Thedesigners'extensiveC++experiencetaughtthemthatmultiple
inheritancejustwasn'tworththeheadache.
Q15.Whyjavaisnota100%oops?
ManypeoplesaythisbecauseJavausesprimitivetypessuchasint,char,double.Butthen
alltherestareobjects.Confusingquestion.
Q16.Whatisaresourcebundle?
Initssimplestform,aresourcebundleisrepresentedbyatextfilecontainingkeysanda
textvalueforeachkey.
*CoreJava
*Servlets&JSP
*Struts
*EJB
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

9/48

6/16/2015

JavaInterviewQuestions

*J2ME
Q17.Whatistransientvariable?
Transientvariablecan'tbeserialize.Forexampleifavariableisdeclaredastransientina
SerializableclassandtheclassiswrittentoanObjectStream,thevalueofthevariablecan't
bewrittentothestreaminsteadwhentheclassisretrievedfromtheObjectStreamthevalue
ofthevariablebecomesnull.
Q18.WhatisCollectionAPI?
TheCollectionAPIisasetofclassesandinterfacesthatsupportoperationoncollectionsof
objects. These classes and interfaces are more flexible, more powerful, and more
regularthanthevectors,arrays,andhashtablesifeffectivelyreplaces.
Exampleofclasses:HashSet,HashMap,ArrayList,LinkedList,TreeSetandTreeMap.
Exampleofinterfaces:Collection,Set,ListandMap.
Q19.IsIteratoraClassorInterface?Whatisitsuse?
IteratorisaninterfacewhichisusedtostepthroughtheelementsofaCollection.
Q20.Whatissimilarities/differencebetweenanAbstractclassandInterface?
Differencesareasfollows:
Interfacesprovideaformofmultipleinheritance.Aclasscanextendonlyoneother
class.
Interfacesarelimitedtopublicmethodsandconstantswithnoimplementation.
Abstractclassescanhaveapartialimplementation,protectedparts,staticmethods,etc.
A Class may implement several interfaces. But in case of abstract class, a class may
extendonlyoneabstractclass.
Interfacesareslowasitrequiresextraindirectiontotofindcorrespondingmethodin
intheactualclass.Abstractclassesarefast.Similarities:
NeitherAbstractclassesorInterfacecanbeinstantiated.
Q21.Whatisatransientvariable?
Atransientvariableisavariablethatmaynotbeserialized.
Q22.WhichcontainersuseaborderLayoutastheirdefaultlayout?
Thewindow,FrameandDialogclassesuseaborderlayoutastheirdefaultlayout.
Q23.WhydothreadsblockonI/O?
Threadsblockoni/o(thatisentersthewaitingstate)sothatotherthreadsmay
executewhilethei/oOperationisperformed.
Q24.HowareObserverandObservableused?
ObjectsthatsubclasstheObservableclassmaintainalistofobservers.Whenan
Observable
object is updated it invokes the update () method of each of its observers to notify the
observersthatithaschangedstate.TheObserverinterfaceisimplementedbyobjectsthat
observeObservableobjects.
Q25.Whatissynchronizationandwhyisitimportant?
Withrespecttomultithreading,synchronizationisthecapabilitytocontroltheaccessof
multiplethreadstosharedresources.Withoutsynchronization,itispossibleforonethread
tomodifyasharedobjectwhileanotherthreadisintheprocessofusingorupdatingthat
object'svalue.Thisoftenleadstosignificanterrors.
Q26.Canalockbeacquiredonaclass?
Yes,alockcanbeacquiredonaclass.Thislockisacquiredontheclass'sClassobject.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

10/48

6/16/2015

JavaInterviewQuestions

Q27.What'snewwiththestop(),suspend()and
resume()methodsinJDK1.2?
Thestop(),suspend()andresume()methodshavebeendeprecatedinJDK1.2.
Q28.Isnullakeyword?
Thenullvalueisnotakeyword.
Q29.Whatisthepreferredsizeofacomponent?
Thepreferredsizeofacomponentistheminimumcomponentsizethatwillallowthe
componenttodisplaynormally.
Q30.Whatmethodisusedtospecifyacontainer'slayout?
ThesetLayout()methodisusedtospecifyacontainer'slayout.
Q31.WhichcontainersuseaFlowLayoutastheirdefaultlayout?
ThePanelandAppletclassesusetheFlowLayoutastheirdefaultlayout.
Q32.Whatstatedoesathreadenterwhenitterminatesitsprocessing?
Whenathreadterminatesitsprocessing,itentersthedeadstate.
Q33.WhatistheCollectionsAPI?
TheCollectionsAPIisasetofclassesandinterfacesthatsupportoperationson
collectionsofobjects.
Q34.Whichcharactersmaybeusedasthesecondcharacterofanidentifier,
butnotasthefirstcharacterofanidentifier?
Thedigits0through9maynotbeusedasthefirstcharacterofanidentifierbutthey
maybeusedafterthefirstcharacterofanidentifier.
Q35.WhatistheListinterface?
TheListinterfaceprovidessupportfororderedcollectionsofobjects.
Q36.HowdoesJavahandleintegeroverflowsandunderflows?
Itusesthoseloworderbytesoftheresultthatcanfitintothesizeofthetypeallowedby
theoperation.
Q37.WhatistheVectorclass?
TheVectorclassprovidesthecapabilitytoimplementagrowablearrayofobjects
Q38.Whatmodifiersmaybeusedwithaninnerclassthatisamemberofan
outerclass?
A(nonlocal)innerclassmaybedeclaredaspublic,protected,private,static,final,or
abstract.
Q39.WhatisanIteratorinterface?
TheIteratorinterfaceisusedtostepthroughtheelementsofaCollection.
Q40.Whatisthedifferencebetweenthe>>and>>>operators?
The>>operatorcarriesthesignbitwhenshiftingright.The>>>zerofillsbitsthathave
beenshiftedout.
Q41.WhichmethodoftheComponentclassisusedtosetthepositionand
sizeofacomponent?
setBounds()
Q42.HowmanybitsareusedtorepresentUnicode,ASCII,UTF16,andUTF8
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

11/48

6/16/2015

JavaInterviewQuestions

characters?
Unicoderequires16bitsandASCIIrequire7bits.AlthoughtheASCIIcharactersetuses
only7bits,itisusuallyrepresentedas8bits.UTF8representscharactersusing8,16,
and18bitpatterns.UTF16uses16bitandlargerbitpatterns.
Q43.Whatisthedifferencebetweenyieldingandsleeping?
Whenataskinvokesitsyield()method,itreturnstothereadystate.Whenatask
invokesitssleep()method,itreturnstothewaitingstate.
Q44.Whichjava.utilclassesandinterfacessupport
eventhandling?
TheEventObjectclassandtheEventListenerinterfacesupporteventprocessing.
Q45.Issizeofakeyword?
Thesizeofoperatorisnotakeyword.
Q46.Whatarewrappedclasses?
Wrappedclassesareclassesthatallowprimitivetypestobeaccessedasobjects.
Q47.Doesgarbagecollectionguaranteethataprogramwillnotrunoutof
memory?
Garbage collection does not guarantee that a program will not run out of memory. It is
possibleforprogramstouseupmemoryresourcesfasterthantheyaregarbagecollected.
Itisalso
possibleforprogramstocreateobjectsthatarenotsubjecttogarbagecollection
Q48.Whatrestrictionsareplacedonthelocationofapackagestatementwithin
asourcecodefile?
Apackagestatementmustappearasthefirstlineinasourcecodefile(excludingblank
linesandcomments).
Q49.Cananobject'sfinalize()methodbeinvokedwhileitisreachable?
Anobject'sfinalize()methodcannotbeinvokedbythegarbagecollectorwhiletheobject
isstillreachable.However,anobject'sfinalize()methodmaybeinvokedbyotherobjects.
Q50.WhatistheimmediatesuperclassoftheAppletclass?
Panel
Q51.Whatisthedifferencebetweenpreemptiveschedulingandtimeslicing?
Underpreemptivescheduling,thehighestprioritytaskexecutesuntilitentersthewaiting
ordeadstatesorahigherprioritytaskcomesintoexistence.Undertimeslicing,atask
executesforapredefinedsliceoftimeandthenreentersthepoolofreadytasks.The
schedulerthendetermineswhichtaskshouldexecutenext,basedonpriorityandother
factors.
Q52NamethreeComponentsubclassesthatsupportpainting.
TheCanvas,Frame,Panel,andAppletclassessupportpainting.
Q53.WhatvaluedoesreadLine()returnwhenithasreachedtheendofafile?
ThereadLine()methodreturnsnullwhenithasreachedtheendofafile.
Q54.WhatistheimmediatesuperclassoftheDialogclass?
Window
Q55.Whatisclipping?
Clippingistheprocessofconfiningpaintoperationstoalimitedareaorshape.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

12/48

6/16/2015

JavaInterviewQuestions

Q56.Whatisanativemethod?
AnativemethodisamethodthatisimplementedinalanguageotherthanJava.
Q57.Canaforstatementloopindefinitely?
Yes,forstatementcanloopindefinitely.Forexample,considerthefollowing:for(
Q58.Whatareorderofprecedenceandassociativity,andhowaretheyused?
Orderofprecedencedeterminestheorderinwhichoperatorsareevaluatedin
expressions.
Associatitydetermineswhetheranexpressionisevaluatedlefttorightorrighttoleft
Q59.WhenathreadblocksonI/O,whatstatedoesitenter?
AthreadentersthewaitingstatewhenitblocksonI/O.
Q60.TowhatvalueisavariableoftheStringtypeautomaticallyinitialized?
ThedefaultvalueofaStringtypeisnull.
Q61.Whatisthecatchordeclareruleformethoddeclarations?
Ifacheckedexceptionmaybethrownwithinthebodyofamethod,themethodmusteither
catchtheexceptionordeclareitinitsthrowsclause.
Q62.WhatisthedifferencebetweenaMenuItemand
aCheckboxMenuItem?
TheCheckboxMenuItemclassextendstheMenuItemclasstosupportamenuitemthat
maybecheckedorunchecked.
Q63.Whatisatask'spriorityandhowisitusedinscheduling?
Atask'spriorityisanintegervaluethatidentifiestherelativeorderinwhichitshouldbe
executedwithrespecttoothertasks.Theschedulerattemptstoschedulehigherpriority
tasksbeforelowerprioritytasks.
Q64.WhatclassisthetopoftheAWTeventhierarchy?
Thejava.awt.AWTEventclassisthehighestlevelclassintheAWTeventclasshierarchy.
Q65.Whenathreadiscreatedandstarted,whatisitsinitialstate?
Athreadisinthereadystateafterithasbeencreatedandstarted.
Q66.Canananonymousclassbedeclaredasimplementinganinterfaceand
extendingaclass?
Ananonymousclassmayimplementaninterfaceorextendasuperclass,butmaynotbe
declaredtodoboth.
Q67.Whatistherangeoftheshorttype?
Therangeoftheshorttypeis(2^15)to2^151.
Q68.Whatistherangeofthechartype?
Therangeofthechartypeis0to2^161.
Q69.InwhichpackagearemostoftheAWTeventsthatsupporttheevent
delegationmodeldefined?
MostoftheAWTrelatedeventsoftheeventdelegationmodelaredefinedinthe
java.awt.eventpackage.TheAWTEventclassisdefinedinthejava.awtpackage.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

13/48

6/16/2015

JavaInterviewQuestions

Q70.WhatistheimmediatesuperclassofMenu?
MenuItem
Q71.Whatisthepurposeoffinalization?
Thepurposeoffinalizationistogiveanunreachableobjecttheopportunityto
performanycleanupprocessingbeforetheobjectisgarbagecollected.
Q72.Whichclassistheimmediatesuperclassof
theMenuComponentclass.
Object
Q73.Whatinvokesathread'srun()method?
Afterathreadisstarted,viaitsstart()methodorthatoftheThreadclass,theJVM
invokesthethread'srun()methodwhenthethreadis
initiallyexecuted.
Q74.WhatisthedifferencebetweentheBoolean&operatorandthe&&operator?
IfanexpressioninvolvingtheBoolean&operatorisevaluated,bothoperandsare
evaluated.Thenthe&operatorisappliedtotheoperand.Whenanexpression
involvingthe&&
operatorisevaluated,thefirstoperandisevaluated.Ifthefirstoperandreturnsavalueof
true
thenthesecondoperandisevaluated.The&&operatoristhenappliedtothefirstand
second
operands.Ifthefirstoperandevaluatestofalse,theevaluationofthesecondoperand
isskipped.
Q75.NamethreesubclassesoftheComponentclass.
Box.Filler,Button,Canvas,Checkbox,Choice,Container,Label,List,Scrollbar,or
TextComponent.
Q76.WhatistheGregorianCalendarclass?
TheGregorianCalendarprovidessupportfortraditionalWesterncalendars.
Q77.WhichContainermethodisusedtocauseacontainertobelaidoutand
redisplayed?
validate()
Q78.WhatisthepurposeoftheRuntimeclass?
ThepurposeoftheRuntimeclassistoprovideaccesstotheJavaruntimesystem.
Q79.Howmanytimesmayanobject'sfinalize()methodbeinvokedbythe
garbagecollector?
Anobject'sfinalize()methodmayonlybeinvokedoncebythegarbagecollector.
Q80.Whatisthepurposeofthefinallyclauseofatrycatchfinallystatement?
Thefinallyclauseisusedtoprovidethecapabilitytoexecutecodenomatterwhether
ornotanexceptionisthrownorcaught.
Q81.Whatistheargumenttypeofaprogram'smain()method?
Aprogram'smain()methodtakesanargumentoftheString[]type.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

14/48

6/16/2015

JavaInterviewQuestions

Q82.WhichJavaoperatorisrightassociative?
The=operatorisrightassociative.

Q83.WhatistheLocaleclass?
TheLocaleclassisusedtotailorprogramoutputtotheconventionsofaparticular
geographic,political,orculturalregion.
Q84.Canadoublevaluebecasttoabyte?
Yes,adoublevaluecanbecasttoabyte.
Q85.Whatisthedifferencebetweenabreakstatementandacontinue
statement?
Abreakstatementresultsintheterminationofthestatementtowhichitapplies(switch,for,
do, or while). A continue statement is used to end the current loop iteration and return
controltotheloopstatement.
Q86.Whatmustaclassdotoimplementaninterface?
Itmustprovideallofthemethodsintheinterfaceandidentifytheinterfaceinits
implementsclause.
Q87.Whatmethodisinvokedtocauseanobjecttobeginexecuting
asaseparatethread?
Thestart()methodoftheThreadclassisinvokedtocauseanobjecttobeginexecuting
asaseparatethread.
Q88.NametwosubclassesoftheTextComponentclass.
TextFieldandTextArea
Q89.Whatistheadvantageoftheeventdelegationmodelovertheearlier
eventinheritancemodel?
Theeventdelegationmodelhastwoadvantagesovertheeventinheritance
model.First,it
enableseventhandlingtobehandledbyobjectsotherthantheonesthatgeneratethe
events(ortheircontainers).Thisallowsacleanseparationbetweenacomponent'sdesign
anditsuse.Theotheradvantageoftheeventdelegationmodelisthatitperformsmuch
betterinapplicationswheremanyeventsaregenerated.Thisperformanceimprovementis
duetothefactthatthe
eventdelegationmodeldoesnothavetorepeatedlyprocessunhandledevents,asisthe
caseoftheeventinheritancemodel.
Q90.WhichcontainersmayhaveaMenuBar?
Frame
Q91.Howarecommasusedintheintializationanditerationpartsofafor
statement?
Commasareusedtoseparatemultiplestatementswithintheinitialization
anditerationpartsofaforstatement.
Q92.Whatisthepurposeofthewait(),notify(),andnotifyAll()methods?
Thewait(),notify(),andnotifyAll()methodsareusedtoprovideanefficientwayfor
threadstowaitforasharedresource.Whenathreadexecutesanobject'swait()
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

15/48

6/16/2015

JavaInterviewQuestions

method,itentersthe
waitingstate.Itonlyentersthereadystateafteranotherthreadinvokestheobject's
notify()ornotifyAll()methods..
Q93.Whatisanabstractmethod?
Anabstractmethodisamethodwhoseimplementationisdeferredtoasubclass.
Q94.HowareJavasourcecodefilesnamed?
AJavasourcecodefiletakesthenameofapublicclassorinterfacethatisdefinedwithin
the
file.Asourcecodefilemaycontainatmostonepublicclassorinterface.Ifapublicclass
or
interfaceisdefinedwithinasourcecodefile,thenthesourcecodefilemusttakethe
nameofthepublicclassorinterface.Ifnopublicclassorinterfaceisdefinedwithina
sourcecodefile,then
thefilemusttakeonanamethatisdifferentthanitsclassesandinterfaces.
Sourcecodefilesusethe.javaextension.
Q95.WhatistherelationshipbetweentheCanvasclassandtheGraphicsclass?
ACanvasobjectprovidesaccesstoaGraphicsobjectviaitspaint()method.
Q96.Whatarethehighlevelthreadstates?
Thehighlevelthreadstatesareready,running,waiting,anddead.
Q97.Whatvaluedoesread()returnwhenithasreachedtheendofafile?
Theread()methodreturns1whenithasreachedtheendofafile.
Q98.CanaByteobjectbecasttoadoublevalue?
No,anobjectcannotbecasttoaprimitivevalue.
Q99.Whatisthedifferencebetweenastaticandanonstaticinnerclass?
Anonstaticinnerclassmayhaveobjectinstancesthatareassociatedwithinstancesofthe
class'souterclass.Astaticinnerclassdoesnothaveanyobjectinstances.
Q100.WhatisthedifferencebetweentheStringandStringBufferclasses?
Stringobjectsareconstants.StringBufferobjectsarenot.
Q101.Ifavariableisdeclaredasprivate,wheremaythevariablebeaccessed?
Aprivatevariablemayonlybeaccessedwithintheclassinwhichitisdeclared.
Q102.Whatisanobject'slockandwhichobject'shavelocks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized
accesstotheobject.Athreadmayexecuteasynchronizedmethodofanobjectonlyafterit
hasacquired
theobject'slock.Allobjectsandclasseshavelocks.Aclass'slockisacquiredonthe
class'sClassobject.
Q103.WhatistheDictionaryclass?
TheDictionaryclassprovidesthecapabilitytostorekeyvaluepairs.
Q104.HowaretheelementsofaBorderLayoutorganized?
TheelementsofaBorderLayoutareorganizedattheborders(North,South,East,
andWest)andthecenterofacontainer.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

16/48

6/16/2015

JavaInterviewQuestions

Q105.Whatisthe%operator?
Itisreferredtoasthemoduloorremainderoperator.Itreturnstheremainderof
dividingthefirstoperandbythesecondoperand.
Q106.Whencananobjectreferencebecasttoan
interfacereference?
Anobjectreferencebecasttoaninterfacereferencewhentheobjectimplementsthe
referencedinterface.
Q107.WhatisthedifferencebetweenaWindowandaFrame?
TheFrameclassextendsWindowtodefineamainapplicationwindowthatcanhavea
menubar.
Q108.Whichclassisextendedbyallotherclasses?
TheObjectclassisextendedbyallotherclasses.
Q109.Cananobjectbegarbagecollectedwhileitisstillreachable?
Areachableobjectcannotbegarbagecollected.Onlyunreachableobjectsmaybegarbage
collected..
Q110.Istheternaryoperatorwrittenx:y?zorx?y:z?
Itiswrittenx?y:z.
Q111.WhatisthedifferencebetweentheFontandFontMetricsclasses?
TheFontMetricsclassisusedtodefineimplementationspecificproperties,suchasascent
anddescent,ofaFontobject.
Q112.Howisroundingperformedunderintegerdivision?
Thefractionalpartoftheresultistruncated.Thisisknownasroundingtowardzero.
Q113.Whathappenswhenathreadcannotacquirealockonanobject?
Ifathreadattemptstoexecuteasynchronizedmethodorsynchronizedstatementandis
unable to acquire an object's lock, it enters the waiting state until the lock becomes
available.
Q114.WhatisthedifferencebetweentheReader/Writerclasshierarchyandthe
InputStream/OutputStreamclasshierarchy?
TheReader/Writerclasshierarchyischaracteroriented,andtheInputStream/
OutputStreamclasshierarchyisbyteoriented.
Q115.Whatclassesofexceptionsmaybecaughtbyacatchclause?
AcatchclausecancatchanyexceptionthatmaybeassignedtotheThrowable
type.ThisincludestheErrorandExceptiontypes.
Q116.Ifaclassisdeclaredwithoutanyaccessmodifiers,wheremaytheclassbe
accessed?
Aclassthatisdeclaredwithoutanyaccessmodifiersissaidtohavepackageaccess.This
meansthattheclasscanonlybeaccessedbyotherclassesandinterfacesthatare
definedwithinthesamepackage.
Q117.WhatistheSimpleTimeZoneclass?
TheSimpleTimeZoneclassprovidessupportforaGregoriancalendar.
Q118.WhatistheMapinterface?
TheMapinterfacereplacestheJDK1.1Dictionaryclassandisusedassociatekeys
withvalues.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

17/48

6/16/2015

JavaInterviewQuestions

Q119.Doesaclassinherittheconstructorsofitssuperclass?
Aclassdoesnotinheritconstructorsfromanyofitssuperclasses.
Q120.Forwhichstatementsdoesitmakesensetousealabel?
Theonlystatementsforwhichitmakessensetousealabelarethosestatementsthat
canencloseabreakorcontinuestatement.
Q121.WhatisthepurposeoftheSystemclass?
ThepurposeoftheSystemclassistoprovideaccesstosystemresources.
Q122.WhichTextComponentmethodisusedtoset
aTextComponenttothereadonlystate?setEditable()
Q123.HowaretheelementsofaCardLayoutorganized?
TheelementsofaCardLayoutarestacked,oneontopoftheother,likeadeckofcards.
Q124.Is&&=avalidJavaoperator?
No,itisnot.
Q125.NametheeightprimitiveJavatypes?
Theeightprimitivetypesarebyte,char,short,int,long,float,double,andboolean.
Q126.Whichclassshouldyouusetoobtaindesigninformationaboutanobject?
TheClassclassisusedtoobtaininformationaboutanobject'sdesign.
Q127.Whatistherelationshipbetweenclippingandrepainting?
WhenawindowisrepaintedbytheAWTpaintingthread,itsetstheclippingregions
totheareaofthewindowthatrequiresrepainting.
Q128.Is"abc"aprimitivevalue?
TheStringliteral"abc"isnotaprimitivevalue.ItisaStringobject.
Q129.Whatistherelationshipbetweenaneventlistenerinterfaceandanevent
adapterclass?
Aneventlistenerinterfacedefinesthemethodsthatmustbeimplementedbyanevent
handlerforaparticularkindofevent.Aneventadapterprovidesadefaultimplementation
ofaneventlistenerinterface.
Q130.Whatrestrictionsareplacedonthevaluesofeachcaseofaswitch
statement?
Duringcompilation,thevaluesofeachcaseofaswitchstatementmustevaluatetoa
valuethatcanbepromotedtoanintvalue.
Q131.Whatmodifiersmaybeusedwithaninterfacedeclaration?
Aninterfacemaybedeclaredaspublicorabstract.
Q132.Isaclassasubclassofitself?
Aclassisasubclassofitself.
Q133.Whatisthehighestleveleventclassoftheevent
delegationmodel?
Thejava.util.EventObjectclassisthehighestlevelclassintheeventdelegationclass
hierarchy.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

18/48

6/16/2015

JavaInterviewQuestions

Q134.Whateventresultsfromtheclickingofabutton?
TheActionEventeventisgeneratedastheresultoftheclickingofabutton.
Q135.HowcanaGUIcomponenthandleitsownevents?
Acomponentcanhandleitsowneventsbyimplementingtherequiredeventlistener
interfaceandaddingitselfasitsowneventlistener.
Q136.Whatisthedifferencebetweenawhilestatementandadostatement?
A while statement checks at the beginning of a loop to see whether the next loop
iteration should occur. A do statement checks at the end of a loop to see whether the
nextiterationofaloop
shouldoccur.Thedostatementwillalwaysexecutethebodyofaloopatleastonce.
Q137.HowaretheelementsofaGridBagLayoutorganized?
TheelementsofaGridBagLayoutareorganizedaccordingtoagrid.However,the
elementsareofdifferentsizesandmayoccupymorethanoneroworcolumnofthegrid.
Inaddition,therowsandcolumnsmayhavedifferentsizes.
Q138.WhatadvantagedoJava'slayoutmanagersprovideovertraditional
windowingsystems?
Java uses layout managers to lay out components in a consistent manner across all
windowing platforms. Since Java's layout managers aren't tied to absolute sizing and
positioning, they are able to accomodate platformspecific differences among windowing
systems.
Q139.WhatistheCollectioninterface?
TheCollectioninterfaceprovidessupportfortheimplementationofamathematicalbag
anunorderedcollectionofobjectsthatmaycontainduplicates.
Q140.Whatmodifierscanbeusedwithalocalinnerclass?
Alocalinnerclassmaybefinalorabstract.
Q141.Whatisthedifferencebetweenstaticandnonstaticvariables?
Astaticvariableisassociatedwiththeclassasawholeratherthanwithspecific
instancesofaclass.Nonstaticvariablestakeonuniquevalues
witheachobjectinstance.
Q142.Whatisthedifferencebetweenthepaint()andrepaint()methods?
Thepaint()methodsupportspaintingviaaGraphicsobject.Therepaint()methodisused
tocausepaint()tobeinvokedbytheAWTpaintingthread.
Q143.WhatisthepurposeoftheFileclass?
TheFileclassisusedtocreateobjectsthatprovideaccesstothefilesanddirectoriesofa
localfilesystem.
Q144.Cananexceptionberethrown?
Yes,anexceptioncanberethrown.
Q145.WhichMathmethodisusedtocalculatetheabsolutevalueofanumber?
Theabs()methodisusedtocalculateabsolutevalues.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

19/48

6/16/2015

JavaInterviewQuestions

Q146.HowdoesmultithreadingtakeplaceonacomputerwithasingleCPU?
Theoperatingsystem'staskschedulerallocatesexecutiontimetomultipletasks.
Byquickly
switchingbetweenexecutingtasks,itcreatestheimpressionthattasksexecute
sequentially.
Q147.Whendoesthecompilersupplyadefaultconstructorforaclass?
Thecompilersuppliesadefaultconstructorforaclassifnootherconstructors
areprovided.
Q148.Whenisthefinallyclauseofatrycatchfinallystatementexecuted?
Thefinallyclauseofthetrycatchfinallystatementisalwaysexecutedunlessthethread
of
executionterminatesoranexceptionoccurswithintheexecutionofthefinallyclause.
Q149.WhichclassistheimmediatesuperclassoftheContainerclass?
Component
Q150.Ifamethodisdeclaredasprotected,wheremaythemethodbeaccessed?
Aprotectedmethodmayonlybeaccessedbyclassesorinterfacesofthesamepackage
orbysubclassesoftheclassinwhichitisdeclared.
Q151.HowcantheCheckboxclassbeusedtocreatearadiobutton?
ByassociatingCheckboxobjectswithaCheckboxGroup.
Q152.WhichnonUnicodelettercharactersmaybeusedasthefirstcharacterof
anidentifier?
ThenonUnicodelettercharacters$and_mayappearasthefirstcharacterofan
identifier
Q153.Whatrestrictionsareplacedonmethodoverloading?
Twomethodsmaynothavethesamenameandargumentlistbutdifferentreturn
types.
Q154.Whathappenswhenyouinvokeathread'sinterruptmethodwhileitissleeping
orwaiting?
Whenatask'sinterrupt()methodisexecuted,thetaskentersthereadystate.Thenext
timethetaskenterstherunningstate,anInterruptedExceptionisthrown.
Q155.Whatiscasting?
Therearetwotypesofcasting,castingbetweenprimitivenumerictypesandcasting
between
objectreferences.Castingbetweennumerictypesisusedtoconvertlargervalues,suchas
doublevalues,tosmallervalues,suchasbytevalues.Castingbetweenobjectreferences
isusedtorefertoanobjectbyacompatibleclass,interface,orarraytypereference.
Q156.Whatisthereturntypeofaprogram'smain()method?
Aprogram'smain()methodhasavoidreturntype.
Q157.NamefourContainerclasses.
Window,Frame,Dialog,FileDialog,Panel,Applet,orScrollPane
Q158.WhatisthedifferencebetweenaChoiceandaList?
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

20/48

6/16/2015

JavaInterviewQuestions

AChoiceisdisplayedinacompactformthatrequiresyoutopullitdowntoseethelistof
availablechoices.OnlyoneitemmaybeselectedfromaChoice.AListmaybe
displayedin
suchawaythatseveralListitemsarevisible.AListsupportstheselectionofoneormore
Listitems.
Q159.WhatclassofexceptionsaregeneratedbytheJavaruntimesystem?
TheJavaruntimesystemgeneratesRuntimeExceptionandErrorexceptions.
Q160.Whatclassallowsyoutoreadobjectsdirectlyfromastream?
TheObjectInputStreamclasssupportsthereadingofobjectsfrominputstreams.
Q161.Whatisthedifferencebetweenafieldvariableandalocalvariable?
Afieldvariableisavariablethatisdeclaredasamemberofaclass.Alocalvariableis
avariablethatisdeclaredlocaltoamethod.
Q162.Underwhatconditionsisanobject'sfinalize()methodinvokedbythe
garbagecollector?
Thegarbagecollectorinvokesanobject'sfinalize()methodwhenitdetectsthatthe
objecthasbecomeunreachable.
Q163.Howarethis()andsuper()usedwithconstructors?
this()isusedtoinvokeaconstructorofthesameclass.super()isusedtoinvokea
superclassconstructor.
Q164.Whatistherelationshipbetweenamethod'sthrowsclauseandthe
exceptionsthatcanbethrownduringthemethod'sexecution?
Amethod'sthrowsclausemustdeclareanycheckedexceptionsthatarenotcaught
withinthebodyofthemethod.
Q165.WhatisthedifferencebetweentheJDK1.02eventmodelandtheevent
delegationmodelintroducedwithJDK1.1?
TheJDK1.02eventmodelusesaneventinheritanceorbubblingapproach.In
thismodel,
componentsarerequiredtohandletheirownevents.Iftheydonothandlea
particularevent,the
eventisinheritedby(orbubbledupto)thecomponent'scontainer.Thecontainerthen
either
handlestheeventoritisbubbleduptoitscontainerandsoon,untilthehighestlevel
containerhasbeentried..Intheeventdelegationmodel,specificobjectsaredesignated
aseventhandlersforGUIcomponents.Theseobjectsimplementeventlistener
interfaces.Theeventdelegationmodelismoreefficientthantheeventinheritancemodel
becauseiteliminatestheprocessingrequiredtosupportthebubblingofunhandled
events.
Q166.HowisitpossiblefortwoStringobjectswithidenticalvaluesnottobeequal
underthe==operator?
The==operatorcomparestwoobjectstodetermineiftheyarethesameobjectinmemory.
Itis
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

21/48

6/16/2015

JavaInterviewQuestions

possiblefortwoStringobjectstohavethesamevalue,butlocatedindifferentareas
ofmemory.
Q167.WhyarethemethodsoftheMathclassstatic?
Sotheycanbeinvokedasiftheyareamathematicalcodelibrary.
Q168.WhatCheckboxmethodallowsyoutotellifaCheckboxischecked?
getState()
Q169.Whatstateisathreadinwhenitisexecuting?Anexecuting
threadisintherunningstate.
Q170.Whatarethelegaloperandsoftheinstanceofoperator?
Theleftoperandisanobjectreferenceornullvalueandtherightoperandisaclass,
interface,orarraytype.
Q171.HowaretheelementsofaGridLayoutorganized?
TheelementsofaGridBadlayoutareofequalsizeandarelaidoutusingthesquaresofa
grid.
Q172.WhatanI/Ofilter?
AnI/Ofilterisanobjectthatreadsfromonestreamandwritestoanother,usually
alteringthedatainsomewayasitispassedfromonestreamtoanother.
Q173.Ifanobjectisgarbagecollected,canitbecomereachableagain?
Onceanobjectisgarbagecollected,itceasestoexist.Itcannolongerbecome
reachableagain.
Q174.WhatistheSetinterface?
TheSetinterfaceprovidesmethodsforaccessingtheelementsofafinitemathematical
set.Setsdonotallowduplicateelements.
Q175.Whatclassesofexceptionsmaybethrownbya
throwstatement?
AthrowstatementmaythrowanyexpressionthatmaybeassignedtotheThrowabletype.
Q176.WhatareEandPI?
EisthebaseofthenaturallogarithmandPIismathematicalvaluepi.
Q177.Aretrueandfalsekeywords?
Thevaluestrueandfalsearenotkeywords.
Q178.Whatisavoidreturntype?
Avoidreturntypeindicatesthatamethoddoesnotreturnavalue.
Q179.WhatisthepurposeoftheenableEvents()method?
TheenableEvents()methodisusedtoenableaneventforaparticularobject.Normally,
aneventisenabledwhenalistenerisaddedtoanobjectforaparticularevent.The
enableEvents()methodisusedbyobjectsthathandleeventsbyoverridingtheir
eventdispatchmethods.
Q180.WhatisthedifferencebetweentheFile
andRandomAccessFileclasses?
TheFileclassencapsulatesthefilesanddirectoriesofthelocalfilesystem.The
RandomAccessFileclassprovidesthemethodsneededtodirectlyaccessdatacontained
inanypartofafile.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

22/48

6/16/2015

JavaInterviewQuestions

Q181.WhathappenswhenyouaddadoublevaluetoaString?
TheresultisaStringobject.
Q182.Whatisyourplatform'sdefaultcharacterencoding?
IfyouarerunningJavaonEnglishWindowsplatforms,itisprobablyCp1252.Ifyouare
runningJavaonEnglishSolarisplatforms,itismostlikely8859_1..
Q183.Whichpackageisalwaysimportedbydefault?
Thejava.langpackageisalwaysimportedbydefault.
Q184.Whatinterfacemustanobjectimplementbeforeitcanbewrittentoa
streamasanobject?
AnobjectmustimplementtheSerializableorExternalizableinterfacebeforeitcanbe
writtentoastreamasanobject.
Q185.Howarethisandsuperused?
thisisusedtorefertothecurrentobjectinstance.superisusedtorefertothevariables
andmethodsofthesuperclassofthecurrentobjectinstance.
Q186.Whatisthepurposeofgarbagecollection?
Thepurposeofgarbagecollectionistoidentifyanddiscardobjectsthatarenolonger
neededbyaprogramsothattheirresourcesmaybereclaimedandreused.
Q187.Whatisacompilationunit?
AcompilationunitisaJavasourcecodefile.

Q188.WhatinterfaceisextendedbyAWTeventlisteners?
AllAWTeventlistenersextendthejava.util.EventListenerinterface.
Q189.Whatrestrictionsareplacedonmethodoverriding?
Overriddenmethodsmusthavethesamename,argumentlist,andreturntype.
Theoverridingmethodmaynotlimittheaccessofthemethoditoverrides.
The overriding method may not throw any exceptions that may not be thrownby the
overriddenmethod.
Q190.Howcanadeadthreadberestarted?
Adeadthreadcannotberestarted.
Q191.Whathappensifanexceptionisnotcaught?
AnuncaughtexceptionresultsintheuncaughtException()methodofthethread's
ThreadGroupbeinginvoked,whicheventuallyresultsintheterminationoftheprogramin
whichitisthrown.
Q192.Whatisalayoutmanager?
Alayoutmanagerisanobjectthatisusedtoorganizecomponentsinacontainer.
Q193.Whicharithmeticoperationscanresultinthethrowingofan
ArithmeticException?
Integer/and%canresultinthethrowingofanArithmeticException.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

23/48

6/16/2015

JavaInterviewQuestions

Q194.Whatarethreewaysinwhichathreadcanenterthewaitingstate?
Athreadcanenterthewaitingstatebyinvokingitssleep()method,byblockingonI/O,
by
unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait()
method.Itcanalsoenterthewaitingstatebyinvokingits(deprecated)suspend()method.
Q195.Cananabstractclassbefinal?
Anabstractclassmaynotbedeclaredasfinal.
Q196.WhatistheResourceBundleclass?
TheResourceBundleclassisusedtostorelocalespecificresourcesthatcanbeloaded
bya
programtotailortheprogram'sappearancetotheparticularlocaleinwhichitisbeing
run.
Q197.Whathappensifatrycatchfinallystatementdoesnothaveacatchclauseto
handleanexceptionthatis
thrownwithinthebodyofthetrystatement?
Theexceptionpropagatesuptothenexthigherleveltrycatchstatement(ifany)orresults
intheprogram'stermination.
Q198.Whatisnumericpromotion?
Numericpromotionistheconversionofasmallernumerictypetoalargernumerictype,so
thatintegerandfloatingpointoperationsmaytakeplace.Innumericalpromotion,byte,
char,andshortvaluesareconvertedtointvalues.Theintvaluesarealsoconvertedtolong
values,ifnecessary.Thelongandfloatvaluesareconvertedtodoublevalues,asrequired.
Q199.WhatisthedifferencebetweenaScrollbarandaScrollPane?
AScrollbarisaComponent,butnotaContainer.AScrollPaneisaContainer.A
ScrollPanehandlesitsowneventsandperformsitsownscrolling.
Q200.Whatisthedifferencebetweenapublicanda
nonpublicclass?
Apublicclassmaybeaccessedoutsideofitspackage.Anonpublicclassmaynotbe
accessedoutsideofitspackage.
Q201.Towhatvalueisavariableoftheboolean
typeautomaticallyinitialized?
Thedefaultvalueofthebooleantypeisfalse.
Q202.Cantrystatementsbenested?
Trystatementsmaybetested.
Q203.Whatisthedifferencebetweentheprefixandpostfixformsofthe++operator?
Theprefixformperformstheincrementoperationandreturnsthevalueoftheincrement
operation.Thepostfixformreturnsthecurrentvaluealloftheexpressionandthen
performstheincrementoperationonthatvalue.
Q204.Whatisthepurposeofastatementblock?
Astatementblockisusedtoorganizeasequenceofstatementsasasingle
statementgroup.
Q205.WhatisaJavapackageandhowisitused?
AJavapackageisanamingcontextforclassesandinterfaces.Apackageisusedto
createa
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

24/48

6/16/2015

JavaInterviewQuestions

separatenamespaceforgroupsofclassesandinterfaces.Packagesarealsousedto
organize
relatedclassesandinterfacesintoasingleAPIunitandtocontrolaccessibilityto
theseclassesandinterfaces.
Q206.Whatmodifiersmaybeusedwithatoplevelclass?
Atoplevelclassmaybepublic,abstract,orfinal.
Q207.WhataretheObjectandClassclassesusedfor?
TheObjectclassisthehighestlevelclassintheJavaclasshierarchy.TheClassclassis
usedtorepresenttheclassesandinterfacesthatareloadedbyaJavaprogram..
Q208.Howdoesatrystatementdeterminewhichcatchclauseshouldbeusedto
handleanexception?
Whenanexceptionisthrownwithinthebodyofatrystatement,thecatchclausesof
thetry
statementareexaminedintheorderinwhichtheyappear.Thefirstcatchclausethatis
capableofhandlingtheexceptionisexecuted.Theremainingcatchclausesareignored.
Q209.Cananunreachableobjectbecomereachableagain?
Anunreachableobjectmaybecomereachableagain.Thiscanhappenwhentheobject's
finalize()methodisinvokedandtheobjectperformsanoperationwhichcausesitto
becomeaccessibletoreachableobjects.
Q210.Whenisanobjectsubjecttogarbagecollection?
Anobjectissubjecttogarbagecollectionwhenitbecomesunreachabletotheprogramin
whichitisused.
Q211.Whatmethodmustbeimplementedbyallthreads?
Alltasksmustimplementtherun()method,whethertheyareasubclassofThreador
implementtheRunnableinterface.
Q212.Whatmethodsareusedtogetandsetthetextlabeldisplayed
byaButtonobject?
getLabel()andsetLabel()
Q213.WhichComponentsubclassisusedfordrawingandpainting?
Canvas
Q214.Whataresynchronizedmethodsand
synchronizedstatements?
Synchronizedmethodsaremethodsthatareusedtocontrolaccesstoanobject.Athread
onlyexecutesasynchronizedmethodafterithasacquiredthelockforthemethod's
objectorclass.Synchronizedstatementsaresimilartosynchronizedmethods.A
synchronizedstatementcanonlybeexecutedafterathreadhasacquiredthelockforthe
objectorclassreferencedinthesynchronizedstatement.
Q215.Whatarethetwobasicwaysinwhichclassesthatcanberunasthreads
maybedefined?
AthreadclassmaybedeclaredasasubclassofThread,oritmayimplementthe
Runnableinterface.
Q216.WhataretheproblemsfacedbyJavaprogrammerswhodon'tuselayout
managers?
Withoutlayoutmanagers,JavaprogrammersarefacedwithdetermininghowtheirGUI
willbedisplayedacrossmultiplewindowingsystemsandfindingacommonsizingand
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

25/48

6/16/2015

JavaInterviewQuestions

positioningthatwillworkwithintheconstraintsimposedbyeachwindowingsystem.
Q217.Whatisthedifferencebetweenanifstatementandaswitchstatement?
Theifstatementisusedtoselectamongtwoalternatives.Itusesaboolean
expressiontodecide
whichalternativeshouldbeexecuted.Theswitchstatementisusedtoselectamong
multiple
alternatives.Itusesanintexpressiontodeterminewhichalternativeshouldbe
executed.
Q218.WhathappenswhenyouaddadoublevaluetoaString?
TheresultisaStringobject.
Q219.WhatistheListinterface?
TheListinterfaceprovidessupportfororderedcollectionsofobjects
Q220.WhatisanException?
Ans.Anunwanted,unexpectedeventthatdisturbsnormalflowoftheprogramis
calledException.Example:FileNotFondException.
Q221.WhatisthepurposeofExceptionHandling?
Ans.ThemainpurposeofExceptionHandlingisforgracefulterminationoftheprogram.
Q222.WhatisthemeaningofExceptionHandling?
Ans.ExceptionHandlingdoesntmeanrepairinganException,wehavetodefine
alternativewaytocontinuerestofthecodenormally.
Example:Ifourprogrammingrequirementistoreadthedatafromthefilelocatingat
LondonbutatRuntimeifLondonfileisnotavailablethenwehavetouselocalfile
alternativelytocontinuerestofprogramnormally.ThisisnothingbutExceptionHandling.
Q223.ExplainDefaultExceptionHandlingMechanisminjava?
Ans.Ifanexceptionraised,themethodinwhichitsraisedisresponsibleforthecreation
ofExceptionsobjectbyincludingthefollowinginformation:
NameoftheExceptionDescriptionof
theExceptionStackTrace
AftercreatingExceptionobjectthemethodhandoverittotheJVM.JVMchecksfor
ExceptionHandlingcodeinthatmethod.
IfthemethoddoesntcontainanyExceptionhandlingcodethenJVMterminatesthe
methodabnormallyandremovesthecorrespondingentryfromthestack.JVMidentifythe
callermethodandchecksforExceptionHandlingcodeinthatmethod.Ifthecallerdoesnt
containanyexceptionhandlingcodethenJVMterminatesthatmethodabnormallyand
removesthecorrespondingentryfromthestack.
Thisprocesswillbecontinueuntilmain()method.
Ifthemain()methodalsodoesntcontainexceptionhandlingcodetheJVMterminatesthat
main()methodandremovesthecorrespondingentryfromthestack.Justbefore
terminatingtheprogramabnormallyJVMhandoverstheresponsibilityof
exceptionhandlingtotheDefaultExceptionHandlerwhichisthecomponentof
JVM.
DefaultExceptionHandlerjustprintexceptioninformationtotheconsolinthefollowing
format
NameofException:Description
StackTrace(LocationoftheException)
Q224.Whatisthepurposeoftry?
AnsWeshouldmaintainallriskycodeinsidethetryblock.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

26/48

6/16/2015

JavaInterviewQuestions

Q225.Whatisthepurposeofcatchblock?
Ans.WehavetomaintainallExceptionHandlingcodeinsidethecatchblock.
Q226.Istrywithmultiplecatchblockispossible?
Ans.Thewayofhandlinganexceptionisvariedfromexceptiontoexceptioncompulsory
wehavetowriteaseparatecatchblockforeveryexception.Hencetrywillmultiplecatch
blockispossibleanditisrecommendedtouse.
Example:
try{//Riskycode
}
catch(IOExceptione)
{
//HndlingcodeforIOException
}
catch(ArithmeticExceptione){//handling
codeforAE
}
catch(NullPointerExcetpione)
{
//handlingcodeforNPE
}
catch(Exceptione)
{
//defaultexceptionhandlingcode
}
Q227.Iftrywithmultiplecatchblockpresentisorderofcatchblocksimportant
inwhichorderwehavetotake?
Ans.Iftrywithmultiplecatchblockpresentthentheorderofcatchblockisveryimportantit
shouldbefromchildtoparentbutnotfromparenttochild.
Q228.WhatarevariousmethodstoprintExceptioninformation?anddifferentiate
them.
Ans.
Throwableclassdefinesthefollowingmethodtoprintexceptionorerrorinformation.
1.printStackTrace():Thismethodprintexceptioninformationinthefollowingformat.
NameoftheException:DescriptionStackTrace
2.toString():Thismethodprintexceptioninformationinthefollowingformat.
NameoftheException:Description
3.getMessage():Thismethodprintsonlydescriptionoftheexception.
Description
Q229.Ifanexceptionrisedinsidecatchblockthenwhatwillhappen?
Ans.Ifanexceptionraisedinsidecatchblockanditisnotpartofanytryblockthenitis
alwaysabnormaltermination.
Q230.Isitpossibletotaketry,catchinsidetryblock?
Ans.Yes,Itispossibletotaketry,catchinsidetryblock.Thatisnestingoftrycatchis
possible.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

27/48

6/16/2015

JavaInterviewQuestions

Q231.Isitpossibletotaketry,catchinsidecatchblock?
Ans.Yes,Itispossibletotaketry,catchinsidecatchblock.
Q232.Isitpossibletotaketrywithoutcatch?
Ans.Yes,itispossibletotaketrywithoutcatchbutcompulsoryfinallyblockshouldbe
available.
Q233.Whatisthepurposeoffinallyblock?
Ans.Themainpurposeoffinallyblockis,tomaintainthecleanupcode.Thisblockwill
executealways.
Q234.Isfinallyblockwillbeexecutealways?
Ans.Yesfinallyblockwillbeexecutedalwaysirrespectiveofwhetherexceptionraisedor
notraisedwhetherexceptionsarehandledornothandle.Thereisonesituationwherethe
finallyblockwontbeexecutediftheJVMisgoingtobeshutdown.
Q235.Inwhichsituationfinallyblockwillnotexecuted?
Ans.Thereisonesituationwherethefinallyblockwontbeexecutedifweareusing
system.exit(0)explicitlythenJVMitselfwillbeshutdownandthereisnochanceof
executingfinallyblock.
Q236.Ifreturnstatementpresentinsidetryisfinallyblockwillbeexecuted?
Ans.Yes,ifreturnstatementpresentinsidetry,thenalsofinallyblockwillbeexecuted.
finallyblockwilldominatereturnstatementalso.
Q237.Whatisthedifferencebetweenfinal,finallyandfinalize()?
Ans.final:finalisamodifierapplicableforvariables,methodsandclasses.final
variable
meansconstantandreassignmentisnotpossible.finalmethodmeansimplementation
is final in the child classes we cant override. final class means it wont participate in
inheritanceandchildclasscreationisnotpossible.
finally:Itisablockassociatedwithtrycatchtomaintaincleanupcode.Finallyblockwillbe
executedalwaysirrespectiveofwhetherexceptionisraisedornotraisedorwhetherthe
exceptionishandleornothandle.finalize():Itisamethod,Garbagecollectoralwayscalls
thismethodjustbeforedestroyinganyobjecttoperformcleanupactivities.
Q238.Isitpossibletowriteanystatementbetweentrycatchandfinally?
Ans.No,itisnotpossibletowriteanystatementbetweentrycatchandfinally.Ifwewill
trytowriteanystatementbetweenthemthenwewillgetcompiletimeerror.

Q239.Isitpossibletotaketwofinallyblocksforthesametry?
Ans.No,itisnotpossibletotaketwofinallyblocksforthesametry.Ifwetrytotakethenwe
willgetcompiletimeerror.
Q240.Issyntaxtryfinallycatchisvalid?
Ans.No,thissyntaxisnotvalid.Itshouldbeliketrycatchfinallythenonlycodewill
compile.
Q241.Whatisthepurposeofthrow?
Ans.SometimeswecancreateExceptionobjectexplicitlyandwecanhandoverthat
exceptionobjecttotheJVMexplicitlybythrowkeyword.Thepurposeofthrowkeyword
istohandoverourcreatedexceptionobjectexplicitlytothe
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

28/48

6/16/2015

JavaInterviewQuestions

JVM.
Example1:class
Test{
publicstaticvoidmain(String[]args){
System.out.println(10/0)
}
}
InthiscaseArithmeticExceptionobjectcreatedimplicitlyandhandovertotheJVM
automaticallybythemainmethod.
Example2:class
Test{
Publicstaticvoidmain(String[]args){
ThrownewArithmeticException(/byZero)}
}
InthiscasecreationofanexceptionobjectandhandovertotheJVMexplicitlybythe
programmer.
Q242.IsitpossibletothrowanError?
Ans.Yes,ItispossibletothrowanyThrowabletypeincludingError.
Q243.Isitpossibletothrowanyjavaobject?
Ans.No,wecanusethrowkeywordonlyforthrowableobjectsotherwisewewillget
compiletimeerrorsayingincompatibletype.
*CoreJava
*Servlets&JSP
*Struts
*EJB
*J2ME
Q244.Afterthrowisitallowtotakeanystatementdirectly?
Ans.Afterthrowstatementwearenotallowtoplaceanystatementdirectlyviolation
leadstocompiletimeerrorsayingUnreachableStatement.
Q245.Whatisthepurposeofthrows?
Ans.Themainpurposeofthrowskeywordistodelegatetheresponsibilitiesofexception
handlingtothecaller.Itrequiresinthecaseofcheckedexception.
Q246.Whatisthedifferencebetweenthrowandthrows?
Ans.SometimeswecancreateExceptionobjectexplicitlyandwecanhandoverthat
exceptionobjecttotheJVMexplicitlybythrowkeyword.Themainpurposeofthrow
keywordisto
handoverourcreatedexceptionobjectexplicitlytotheJVM.Themainpurposeof
throws
keywordistodelegatetheresponsibilitiesofexceptionhandlingtothecaller.Itrequires
inthecaseofcheckedexception.
Q47.Whatisthedifferencebetweenthrowandthrown?
Ans.Thereisnoterminologyofthrowninjava.
Q248.Isitpossibletousethrowskeywordforanyjavaclass?
Ans.No,wecanusethrowskeywordonlyforThrowableclasses.Otherwisewewillget
compiletimeerrorsayingIncompatibletypes.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

29/48

6/16/2015

JavaInterviewQuestions

Q249.Ifwearetakingcatchblockforanexceptionbutthereisnochanceofrising
thatexceptionintrythenwhatwillhappen?
Ans. If there is no chance of raising an exception in try then we are not allow to write
catch
blockforthatexceptionviolationleadstocompiletimeerror.Butthisruleisapplicableonly
forfullycheckedexception.
Q250.ExplainExceptionHandlingkeyword?
Ans.ExceptionHandlingkeyword:Try:TomaintainRiskycode.Catch:Tomaintain
ExceptionHandlingcode.Finally:Tomaintainthecleanupcode.
Throw: To handover our created exception object to the JVM explicitly. Throws: To
delegatetheresponsibilitiesofExceptionHandlingtothecaller.
Q251.WhichclassactasrootforentirejavaExceptionhierarchy?
Ans.ThrowableclassactasrootforentirejavaExceptionhierarchy.
Q252.WhatisthedifferencebetweenErrorandException?
Ans.Throwableclasscontaintwochildclasses.
Exception:Thesearemostlycausedbyourprogramandarerecoverable.
Error: These are not caused by our program, mostly caused by lake of system
resources.Thesearenonrecoverable.
Q253. What is difference between checked exception and unchecked
exception?
Ans. The exceptions which are checked by the compiler for smooth execution of
the program at Runtime is called checked exception. Example: IOException,
InterruptedException.The
exceptions which are not checked by the compiler are called unchecked exception.
Example:ArithmeticException,RuntimeException.
Q254.Whatisdifferencebetweenpartiallycheckedandfullychecked
Exception?
Ans.Acheckedexceptionissaidtobefullycheckedifandonlyifallthechildclasses
alsocheckedotherwiseitiscalledpartiallycheckedexception.
Example:
IOException: fully checked exception Exception:
partially checked exception Throwable: partially
checked exception RuntimeException: unchecked
exception
Q255.WhatisacustomizedException?
Ans.Sometimesbasedonourprogrammingrequirementwehavetocreateourown
exceptionsuchtypeofexceptionarecalledcustomizeException.
Example:TooYoungException
TooOldException
InsufficientFundException
Q256.ExplaintheprocessofcreatingthecustomizedException.
Ans.CreatingcustomizedException:
ClassTooYoungExceptionextendsRuntimeException{
TooYoungExcetpion(Stringdesc){
Super(desc)
}
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

30/48

6/16/2015

JavaInterviewQuestions

}
ClassTooOldExceptionextendsRuntimeException{
TooOldException(Stringdesc){
super(desc)
}
}
ClasscustExcepiton{
Publicstaticvoidmain(String[]args){intage=Integer.parseInt(args[0])if(age>60)
{
ThrownewTooYoungException(Pleasewaitsomemoretime,definitelyyouwillgetbest
match)
}
elseif(age<18){
ThrownewTooOldException(Yourageisalreadycrossedofmarriage,nochanceto
gettingmarriage)
}
else{
System.out.println(Congratulation!Youwillgetmatchdetailssoonbyyour
email)
}
}
Q257.Explaincontrolflowintry,catch,finally.
Ans.try{Statement1
Statement2
Statement3
}
catch(Xe){Statement4
}Finally{Statement5}
Statement6Case1:
IfthereisnoExceptionthenoutputisStatement1
Statement2
Statement3
Statement5
Statement6Normal
terminationCase2:
Ifanexceptionraisedatstatement2andcorrespondingcatchblockhasmatchedthen
outputisStatement1
Statement4
Statement5
Statement5Normal
terminationCase3:
Anexceptionraisedatstatement2andcorrespondingcatchhasnotmatchedthen
outputisStatement1
Statement5Abnormal
terminationCase4:

Anexceptionoccursatstatement4italwaysAbnormalterminationbutbeforethatfinally
blockwillbeexecutedandoutputis
Statement1
Statement2
Statement5Abnormal
terminationCase5:
Ifanexceptionraisedatstatement5orstatement6,itisalwaysabnormaltermination.
Q258.Canyougivethemostcommonoccurredexceptioninyourpreviousproject.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

31/48

6/16/2015

JavaInterviewQuestions

Ans.NullPointerException,ArrayIndexOutofBoundException,
StackOverFlowError,
ClassCastException,NoClassDefFoundError,ExceptionInitilizerError,
IllegalArgumentException,NumberFormatException,IllegalStateException,
AssertionError.
Q259.WhatisMultitasking?
Ans.Executingseveraltasksimultaneouslyiscalledmultitasking.
Q260.WhatisthedifferencebetweenprocessbasedandThreadbased
Multitasking?
Ans.Processbasedmultitasking:Executingseveraltasksimultaneouslywhereeachtask
isa
separate independent process such type of multitasking is called process based
Multitasking.
Example:While typing a program in the editor we can listen MP3 audio songs. At the
sametimewe download a file from the net. all these task are executing simultaneously
andeachtaskis
aseparateindependentprogram.henceitisprocessbasedmultitasking.Itisbestsuitable
atoperatingsystemlevel.Threadbasedmultitasking:Executingseveraltask
simultaneouslywhereeachtaskisaseparateindependentpartofthesameprogramis
calledThreadbasedmultitasking.andeveryindependentpartiscalledathread.Thistype
ofmultitaskingisbestsuitableatprogrammaticlevel.
Q261.WhatisMultithreadingandexplainitsapplicationareas?
Ans.Executingseveralthreadsimultaneouslywhereeachthreadisaseparate
independentpartofthesameprogramiscalledmultithreading.Javalanguageprovides
inbuiltsupportfor
multithreadingbydefiningareachlibrary,classesandinterfaceslikeThread,
ThreadGroup,
Runnableetc.Themainimportantapplicationareaofmultithreadingarevideogames
implementation,animationdevelopment,multimediagraphicsetc.
Q262.WhatisadvantageofMultithreadin
Ans.Themainadvantageofmultithreadingisreducesresponsetimeandimproves
performanceofthesystem.
Q263.WhencomparedwithC++whatistheadvantageinjavawithrespectto
Multithreading?
Ans.Javalanguageprovidesinbuiltsupportformultithreadingbydefiningareachlibrary,
classesandinterfaceslikeThread,ThreadGroup,Runnableetc.Butinc++thereisno
inbuiltsupportformultithreading.
Q264.InhowmanywayswecandefineaThread?Amongextending
ThreadandimplementingRunnablewhichisrecommended?
Ans.WecandefineaThreadinthefollowingtwoways:
1.byextendingThreadclassor
2.byimplementingRunnableinterface.
AmongthetwowaysofdefiningathreadimplementingRunnablemechanismis
always
recommended.InthefirstapproachasourThreadclassalreadyextendingThreadthere
isnochanceofextendinganyother.Hence,wemissingthekeybenefitof
oops(inheritanceproperties).
Q265.Whatisthedifferencebetweent.start()andt.run()method?
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

32/48

6/16/2015

JavaInterviewQuestions

Ans.Inthecaseoft.start()method,anewthreadwillbecreatedwhichisresponsiblefor
the
executionofrun()method.
Butinthecaseoft.run()methodnonewthreadwillbecreatedmainthreadexecutes
run()methodjustlikeanormalmethodcall.
Q266.ExplainaboutThreadScheduler?
Ans.Ifmultiplethreadsarewaitingforgettingthechanceforexecutingthenwhichthread
willgetchancefirstdecidedbyThreadScheduler.ItisthepartofJVManditsbehavioris
vendordependentandwecantexpectexactoutput.Wheneverthesituationcomesto
multithreadingtheguaranteebehaviorisveryverylow.
Q267.Ifwearenotoverridingrun()methodwhatwillhappened?
Ans.Ifwearenotoverridingrun()methodthenThreadclassrun()methodwillexecuted
whichhasemptyimplementationandhencewewillnotgetanyoutput.
Q268.Isoverloadingofrun()methodispossible?
Ans.Yes,wecanoverloadrun()methodbutThreadclassstart()methodalwaysinvokesno
argumentrun()methodonly.Theotherrun()methodwehavetocallexplicitlythen
onlywillbeexecuted.
Q269.Isitpossibletooverridestart()method?
Ans.Yesitispossible.Butnotrecommended.
Q270.Ifweareoverridingstart()methodthenwhatwillhappen?
Ans.Itweareoverridingstart()methodthenourownstart()methodwillbeexecutedjust
likeanormalmethodcall.InthiscasenonewThreadwillbecreated.
Q271.ExplainlifecycleofaThread?
Ans.OncewecreateaThreadobjectthentheThreadissaidtobeinNew/Bornstateonce
wecallt.start()methodnowtheThreadwillbeenteredintoready/Runnablestatethatis
Threadisreadytoexecute.IfThreadSchedulerallocatesCPUnowtheThreadwillentered
intotheRunningstateandstartexecutionofrun()method.Aftercompletingrun()method
theThreadenteredintoDeadState.
Q272.WhatistheimportanceofThreadclassstart()method?
Ans.Start()methodpresentinThreadclassperformingalllowleveljoiningformalities
forthenewlycreatedthreadlikeregisteringthreadwithThreadScheduleretcandthen
start()method
invoking run() method.As the start() method is doing all low level mandatory
activities,
Programmer has to concentrate only on run() method to define the job. Hence, start()
method is a big assistant to the programmer.Without executing Thread class start()
methodthereisnochanceofstartinganewThread.
Q273.AfterstartingaThreadifwetryingtorestartthesamethreadonceagain
whatwillhappen?
Ans. After starting a Thread restarting of the same Thread once again is not allowed
violationleadstoRuntimeExceptionsayingIllegalThreadStateException.
Q274.ExplainThreadclassconstructors?
Ans.ThereareeightconstructorsareavailableinThreadclass:
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

33/48

6/16/2015

JavaInterviewQuestions

1.Threadt=newThread()
2.Threadt=newThread(Runnabler)
3.Threadt=newThread(Stringname)
4.Threadt=newThread(Runnabler,Stringname)5.Threadt=new
Thread(ThreadGroupg,Stringname)6.Threadt=new
Thread(ThreadGroupg,Runnabler)
7.Threadt=newThread(ThreadGroupg,Runnabler,Stringname)8.Threadt=new
Thread(ThreadGroupg,Runnabler,Stringname,longstacksize)
Q275.HowtogetandsetnameofaThread?
Ans.ForeveryThreadinjavathereisaname.TosetandgetthenameofaThreadwecan
usethefollowingmethods.Allmethodsarefinal.1.PublicfinalvoidsetName(Stringname)
TosetthenameofaThread2.PublicfinalStringgetName()TogetthenameofaThread.
Q276.WhatistherangeofThreadpriorityinjava?
Ans.ThevalidrangeofaThreadpriorityis110.(1isleastpriorityand10ishighest
priority)
Q277.WhousesThreadpriority?
Ans.ThreadSchedulerusesprioritieswhileallocatingCPU.TheThreadwhichishaving
highestprioritywillgetchancefirstforexecution.
Q278.WhatisthedefaultpriorityoftheThread?
Ans.Thedefaultpriorityonlyforthemainthreadis5butforallremainingthreadsdefault
prioritywillbeinheritingfromparenttochild.Whateverpriorityparentthreadhasthe
samewillbeinheritedtothechildthread.
Q279.OncewecreatedanewThreadwhataboutitspriority?
Ans.Whateverpriorityparentthreadhasthesamewillbeinheritedtothenewchildthread.
Q280.HowtogetandsetpriorityofaThread?
Ans.TogetandsetpriorityofaThread,Threadclassdefinesthefollowingtwo
methods:
1. Public final int
getPriority()
2.PublicfinalvoidsetPriority(intpriority)
Q281.IfwearetryingtosetpriorityofaThreadas100whatwillhappen?
Ans.IfwearetryingtosetpriorityofaThreadas100thenwewillnotgetanycompile
timeerrorbutattheruntimewewillgetRuntimeexceptionIllegalArgumentException.
BecausethevalidrangeoftheThreadpriorityis(110)only.
Q282.Iftwothreadshavingsameprioritythenwhichthreadwillgetchancefirstfor
execution?
Ans.Iftwothreadshavingsameprioritythenwhichthreadwillgetthechancefirstfor
executiondecidedbyThreadScheduler.Itisthepartof
JVManditsbehaviorisvendordependentandwecantexpectexactoutput.
Q283.Iftwothreadshavingdifferentprioritythenwhichthreadwillgetchancefirst
forexecution?
Ans.IftwothreadshavingdifferentprioritythentheThreadwhichishavinghighest
prioritywillgetchancefirstforexecution.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

34/48

6/16/2015

JavaInterviewQuestions

Q284.Howwecanpreventathreadfromexecution?
Ans.WecanpreventaThreadfromexecutinbyusingthefollowingmethods:
1.Yield()
2.Join()
3.Sleep()
Q285.Whatisyield()method?Explainitspurpose?
Ans.yield()methodcausesthecurrentexecutingthreadtopauseexecutionandgive
thechanceforwaitingthreadaresamepriority.Ifthereisnowaitingthreadorallthe
remainingwaitingthreadhavelowprioritythenthesamethreadwillgetchanceonce
againforexecution.The
Threadwhichisyieldedwhenitwillgetchanceonceagainforexecutiondependsupon
mercyofThreadscheduler.Publicstaticnativevoidyield()
Q286.Whatispurposeofjoin()method?
Ans.IfaThreadwantstowaituntilsomeotherThreadcompletionthenweshouldgofor
join()method.
Example:ifaThreadt1executet2.join()thent1willenteredintowaitingstateuntil
t2Threadcompletion.
Q287.Isjoin()methodisoverloaded?
Ans.Yesjoin()methodisoverloadedmethod.Publicfinalvoid
join()throwsInterruptedException
Byusingthismethodthreadwillwaituptoanotherthreadcompletion.Publicfinalvoid
join(longms)throwsInterruptedException
Byusingthismethodthreadwillwailuptosometimewhatwearepassingasaargumentin
millisecond
Public final void join(long ms, int ns)throws InterruptedException By using this
method thread will wait up to sometime what we are passing as a argument in
millisecondandnanosecond.
Q288.Whatisthepurposeofsleep()method?
Ans.IfaThreaddontwanttoperformanyoperationforaparticularamountoftimethenwe
shouldgoforsleep()method.Wheneverweare
usingsleep()methodcompulsoryweshould
handleInterruptedExceptioneitherbyusingtrycatchorbyusingthrowskeyword
otherwisewewillgetcompiletimeerror.
Q289.Whatissynchronizedkeyword?Explainitsadvantagesanddisadvantages.
Ans.Synchronizedkeywordisapplicableformethodandblocksonly.Wecantusefor
variablesandclasses.
IfamethoddeclaredasasynchronizedthenatatimeonlyoneThreadisallowto
executethatmethodonthegivenobject.
Themainadvantagesofsynchronizedkeywordare,wecanpreventdatainconsistency
problemsandwecanprovideThreadsafty.
Butthemainlimitationofsynchronizedkeywordisitincreaseswaitingtimeof
Threadsandeffectperformanceofthesystem.Henceifthereisnospecificrequirementit
isnotrecommendedtousesynchronizedkeyword.
Q290.Wherewecanusesynchronizedkeyword?
Ans.SynchronizationconceptisapplicablewhenevermultipleThreadsareoperatingonthe
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

35/48

6/16/2015

JavaInterviewQuestions

sameobjectsimultaneously.ButwhenevermultipleThreadsareoperatingondifferent
objectsthenthereisnoimpactofsynchronization.
Q291.Whatisobjectlock?Explainwhenitisrequired?
Ans.Everyobjectinjavahasauniquelockwheneverweareusingsynchronization
conceptthenonlylockconceptwillcomingtothepicture.IfaThreadwantstoexecutea
synchronizedmethodfirstithastogetthelockoftheobject.OnceaThreadgotthelock
thenitisallowtoexecuteanysynchronizedmethodonthatobject.Aftercompleting
synchronizedmethodexecutionThreadreleasesthelockautomatically.Whilea
ThreadexecutingsynchronizedmethodonthegivenobjecttheremainingThreadsarenot
allowtoexecuteanysynchronizedmethodonthatobjectsimultaneously.Butremaining
Threadsareallowtoexecuteanynonsynchronizedmethodsimultaneously.(Lockconcept
isimplementedbasedonobjectbutnotbasedonmethod.)
Q292.Whatistheclasslevellock?Explainitspurpose.
Ans.EveryclassinjavahasauniquelockifaThreadwantstoexecutestatic
synchronized
methodthatThreadhastogetclasslevellockonceaThreadgotclasslevellockthenonly
itisallowtoexecutestaticsynchronizedmethod.WhileaThreadexecutinganystatic
synchronizedmethodthenremainingThreadsarenotallowtoexecuteanystatic
synchronizedmethodofthesameclasssimultaneously.ButtheremainingThreadsare
allowtoexecutethefollowingmethodsimultaneously:
1.Anystaticnonsynchronizedmethod.
2.Synchronizedinstancemethods
3.Nonsynchronizedinstancemethod.
Thereisnorelationshipbetweenobjectlockandclasslevellock,bothareindependent.
Q293.Whileathreadexecutinganysynchronizedmethodonthegivenobjectisit
possibletoexecuteremainingsynchronizedmethodofthesameobject
simultaneouslybyanyotherthread?
Ans.No,itisnopossible.
Q294.Whatisthedifferencebetweensynchronizedmethodandstatic
synchronizedmethod?
Ans.IfaThreadwantstoexecuteasynchronizedmethodfirstithastogetthelockof
the
object.OnceaThreadgotthelockthenitisallowtoexecuteanysynchronized
methodonthat
object.IfaThreadwantstoexecutestaticsynchronizedmethodthatThreadhastoget
classlevellockonceaThreadgotclasslevellockthenonlyitisallowtoexecutestatic
synchronizedmethod.
Q295.Whatistheadvantageofsynchronizedblockoversynchronized
method?
Ans.Ifveryfewlinesofthecoderequiredsynchronizationthendeclaringentiremethodas
thesynchronizedisnotrecommended.Wehavetodeclarethosefewlinesofthecode
inside
synchronizedblock.ThisapproachreduceswaitingtimeoftheThreadandimproves
performanceofthesystem.
Q296.Whatissynchronizedstatement?
Ans.TheStatementwhichisinsidethesynchronizedarea(synchronizedmethodor
synchronizedblock)iscalledsynchronizedstatement.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

36/48

6/16/2015

JavaInterviewQuestions

Q297.Howwecandeclaresynchronizedblocktogetclasslevellock?
Ans.Togettheclasslevellockwecandeclaresynchronizedblockasfollows:
synchronized(Display.class)
{
}
Q298.Howtwothreadwillcommunicatewitheachother?
Ans.TwoThreadswillcommunicatewitheachotherbyusingwait(),notify(),
notifyAll()methods.
Q299.wait(),notify(),notifyAll()methodcanavailableinwhich
class?
Ans.ThesemethodsaredefinedinObjectclass.
Q300.Whywait(),notify(),notifyAll()methoddefinesinobjectclassinsteadof
Threadclass?
Ans.ThesemethodsaredefinedinObjectclassbutnotinThreadbecauseThreadsare
callingthismethodonthesharedobject.
Q301.Ifawaitingthreadgotnotificationthenitwillenteredintowhichstate?
Ans.Itwillenteredintoanotherwaitingstatetogetlock.
Q302.Inwhichmethodthreadscanreleasethelock?
Ans. Once a Thread calls wait() method it immediately releases the lock of that object
andthenenteredintowaitingstatesimilarlyaftercallingnotify()methodThreadreleases
thelockbutmaynotimmediately.
Exceptthesethreemethods(wait(),notify(),notifyAll())methodThreadneverreleasesthe
lockanywhereelse.
Q303.Explainwait(),notify(),notifyAll()methoduses.
Ans.TwoThreadswillcommunicatewitheachotherbyusingwait(),notify()or
notifyAll()methods.
ThesemethodsaredefinedinObjectclassbutnotinThreadbecauseThreadsare
callingthismethod.
Q304.Whatisthedifferencebetweennotify()andnotifyAll()?
Ans. To give notification to the single waiting Thread. We use notify() method and to
givenotificationtoallwaitingthreadweusenotifyAll()method.
Q305.OnceaThreadgotthenotificationthenwhichwaitingthreadwillget
chance?
Ans.ItisdependsontheThreadScheduler.
Q306.Howathreadcaninterruptanotherthread?
Ans.AThreadcaninterruptanotherThreadbyusinginterrupt()method.
Q307.WhichkeywordcausesDeadLocksituation?
Ans.SynchronizedkeywordisthethingtocausesofDeadLock.Ifwearenotusing
properlysynchronizedkeywordtheprogramwillenteredintoDeadLocksituation.
Q308.Howwecanstopathreadexplacitly?
Ans.Threadclassdefinesstop()methodbyusingthismethodwecanstopaThread.But
itisdeprecated.Andhencenotrecommendedtouse.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

37/48

6/16/2015

JavaInterviewQuestions

Q309.Explainaboutsuspend()andresume()method?
Ans.AThreadcansuspendanotherThreadbyusingsuspend()method.AThreadcan
resumeasuspendedThreadbyusingresume()method.
Q310.WhatisStarvation()?AndExplainthedifferencebetweenDeadlockand
Starvation?
Ans.AlongwaitingThreadissaidtobeinstarvation(becauseofleastpriority)butafter
certaintimedefiantlyitwillgetthechanceforexecution.ButinthecaseofDeadlock
twoThreadswillwaitforeachotherforever.Itwillnevergetthechanceforexecution.
Q311.Whatisracecondition?
Ans. Multiple Threads are accessing simultaneously and causing data inconsistency
problemiscalledracecondition,wecanresolvethisbyusingsynchronizedkeyword.
Q312.WhatisDaemonThread?Andgiveanexample?
Ans.TheThreadswhicharerunninginthebackgroundarecalledDaemonThread.
Example:Garbagecollector.
Q313.WhatisthepurposeofaDaemonThread?
Ans.ThemainpurposeofDaemonThreadsistoprovidesupportfornondaemon
Threads.
Q314.HowwecancheckDaemonnatureofaThread?
Ans.WecancheckDaemonnatureofaThreadbyusingisDaemon()method.
Q315.IsitpossibletochangeaDaemonnatureofaThread?
Ans.Yes,wecanchangeDaemonnatureofaThreadbyusingsetDaemon()
method.
Q316.IsmainthreadisDaemonornondaemon?
Ans.Bydefaultmainthreadisalwaysnondaemonnature.
Q317.Oncewecreatedanewthreadisitdaemonornondaemon.
Ans.OncewecreatedanewThread,TheDaemonnaturewillbeinheritingfromparentto
child.IftheparentisDaemonthechildisalsoDaemonandiftheparentisnondaemonthen
childisalsonondaemon
[https://www.blogger.com/null]

Q318.AfterstartingathreadisitpossibletochangeDaemonnature?
Ans.WecanchangetheDaemonnaturebeforestartingtheThreadonly.OnceThread
startedwearenotallowtochangeDaemonnatureotherwisewewillget
RuntimeExceptionsyingIllegalThreadStateException.
Q319.WhentheDaemonthreadwillbeterminated?
Ans.OncelastnondaemonThreadterminatesautomaticallyeveryDaemon
Threadwillbeterminated.
Q320.WhatisgreenThread?
Ans.AgreenthreadreferstoamodeofoperationfortheJavaVirtualMachine(JVM)in
whichallcodeisexecutedinasingleoperatingsystemthread.IftheJavaprogramhas
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

38/48

6/16/2015

JavaInterviewQuestions

anyconcurrent
threads,theJVMmanagesmultithreadinginternallyratherthanusingotheroperating
systemthreads.
ThereisasignificantprocessingoverheadfortheJVMtokeeptrackofthreadstatesand
swap between them, so green thread mode has been deprecated and removed from
morerecentJavaimplementations.
Q321.ExplainaboutThreadgroup?
Ans.EveryJavathreadisamemberofathreadgroup.Threadgroupsprovidea
mechanismfor
collectingmultiplethreadsintoasingleobjectandmanipulatingthosethreadsallat
once,rather
thanindividually.Forexample,youcanstartorsuspendallthethreadswithinagroup
witha
singlemethodcall.Javathreadgroupsareimplementedbythe
ThreadGroupapiclassinthejava.langpackage.
Q322.WhatistheThreadLocal?
Ans.It'sawayforeachthreadinmultithreadedcodetokeepitsowncopyofan
instance
variable.Generally,instancevariablearesharedbetweenallthreadsthatuseanobject
ThreadLocalisawayforeachthreadtokeepitsowncopyofsuchavariable.Thepurpose
mightbethateachthreadkeepsdifferentdatainthatvariable,orthatthedeveloperwants
toavoidtheoverheadofsynchronizingaccesstoit.
Q323.Whatisinnerclassandwhenweshouldgoforinnerclasses?
Sometimeswecandeclareaclassinsideanotherclasssuchtypeofclassesare
calledinnerclasses
Example
ClassCar{

//morecodehereClass
Engine{//morecodehere}
}
WithoutexistingCarobjectthereisnochanceofexistingEngineobject,henceEngine
classhasdeclaredinsideCarclass.
Q324.Howmanytypesofinnerclassesarepresent?
Therearefourtypesofinnerclassesarepresent
oNormalorregularinnerclassoMethodlocalinnerclassoAnonymousinnerclasso
Staticnestedclass
Q325.Whatismethodlocalinnerclass?
Sometimeswecandeclareaclassinsideamethodsuchtypeofclassesarecalled
methodlocal
innerclasses
Themainpurposeofmethodlocalinnerclassesistodefinemethodspecificfunctionality
Thescopeofmethodlocalinnerclassesisthescopeofthemethodwhereitisdeclared.
Thisisthemostlyrarelyusedtypeofinnerclasses.
Exampleclass
Test{
publicvoidm1(){class
Inner{
publicvoidsum(intI,intj){
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

39/48

6/16/2015

JavaInterviewQuestions

System.out.println(i+J)}//sum
}//inner
Inneri=newInner()
i.sum(10,20)//morecodehere
I.sum(100,303)//morecode
herei.sum(102,84)}//m1()
Publicstaticvoidmain(){New
Test().m1()
}
}

Q326.Whatisanonymousinnerclass?
Sometimeswecandeclareainnerclasswithoutnamesuchtypeofinnerclassesare
called
Anonymousinnerclasses
Anonymousinnerclassescanbedividedinto3categoriesAnonymous
innerclassthatextendsaclass
Anonymousinnerclassthatimplementsaninterface
AnonymousinnerclassthatdefinesinsideamethodargumentANONYMOUS
INNERCLASSTHATEXTENDSACLASSExampleClasspopcorn{
Publicvoidtaste(){System.out.println(itis
salty)
}
//morecodehere
}
ClassTest{
Publicstaticvoidmain(String[]args)
{
Popcornp=newPopcorn()
{//herewearecreatingchildclassforpopcornPublicvoid
taste(){
System.out.println(itissweet)
}
}//heresemicolonindicateswercreatingchildclassobjectwithparent//classreference
herechildclassdosentcontainname
p.taste()//itissweetPopcornp=new
Popcorn()p1.taste()//itissalty}
}
ANONYMOUSINNERCLASSTHATIMPLEMENTSANINTERFACEexampleclass
Test{
Publicstaticvoidmain(String[]args){Runnable
r=newRunnable(){
Publicvoidrun(){for(int
i=0i<10i++){
System.out.printin(childthread)
}
}
}
Threadt=newThread(r)t.start()
for(inti=0i<10i++){System.out.printin(main
thread)}
}
}
DontbecomefoolthatherewearecreatingobjectofinterfaceRunnable.Here
weareactually
creatinganobjectofclassthatisimplementedRunnableinterface.
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

40/48

6/16/2015

JavaInterviewQuestions

Q327.Whatisstaticnestedcalss?whythetermnestedinsteadofinnerinstatic
nestedclass?
Sometimeswecandeclareinnerclasswithstaticmodifiersuchtypeofinnerclassare
calledstatic
nestedclasses.thetermnestedinsteadofstaticbecausewithoutexistingouterclass
objectinner
classobjectcanexist.Example
Classouter{
StaticclassNested{
Publicstaticvoidmain(String[]args){
System.out.println(nestedclassmain())}
}
Publicstaticvoidmain(String[]args){
System.out.println(outerclassmain())}
}
JavaOuterO/P
Outerclassmain()JavaOuter$NestedO/P
Nestedclassmain()
Q328.Insideinnerclassisitpossibletodeclaremain()?
Noitisnotpossibletodeclaremain()insideinnerclassbutinstaticnestedclassitis
possiblefor
Examplereferabovecode
Q329.WhatarelimitationsofobjectArrays?
ThemainlimitationsofObjectarraysare
*Thesearefixedinsizeieoncewecreatedanarrayobjectthereisnochanceofincreasing
ordecreasingsizebasedonourrequirement.HenceIfwedontknowsizeinadvance,
arraysarenotrecommendedtouse
*Arrayscanholdonlyhomogeneouselements.
*Thereisnounderlyingdatastructureforarraysandhencenoreadymademethod
supportforarrays.Henceforeveryrequirementprogrammerhastocodeexplicitly
Toovercometheseproblemscollectionsarerecommendedtouse.
Q330.WhatisCollectionAPI?
Itdefinessetofclassesandinterfaceswhichcanbeusedforrepresentingagroupof
objectsassingleentity
Q331.WhatisCollectionframework?
Itdefinessetofclassesandinterfaceswhichcanbeusedforrepresentinga
groupofobjectsassingleentity
Q332.WhatisdifferencebetweenCollectionsandCollection?
Collectionisaninterfacewhichcanbeusedforrepresentingagroupofindividualobjects
assingleentityanditactsasrootinterfaceofcollectionframework.
CollectionsisanutilityclasstodefineseveralutilitymethodsforCollection
implementedclassobjects.
Q333.ExplainaboutCollectioninterface?
*Thisinterfacecanbeusedtorepresentagroupofobjectsasasingleentity.*Itactsas
rootinterfaceforentirecollectionframework.
* Itdefinesthemostcommonlyusedmethodswhichcanbeapplicableforanycollection
implementedclassobject
Q339.ExplainaboutListinterface?
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

41/48

6/16/2015

JavaInterviewQuestions

List interface is a child interface of Collection interface. This can be used to represent
groupofindividualobjectsinasasingleentitywhere
*Duplicatesareallowed
*Insertionorderispreserved
Q334.ExplainaboutSetinterface?
SetisachildinterfaceofCollectioninterface.itcanbeusedtorepresentagroupof
individualobjectsasasingleentitywhere
*Duplicateobjectsarenotallowed.
*Insertionorderisnotpreserved
Q335.ExplainaboutSortedSetinterface?
itischildinterfaceofSetinterface.itcanbeusedtorepresentagroupofindividualobjects
intoasingleentitywhere
Alltheobjectsarearrangedinsomesortingorder(Canbenaturalsortingorderor
customizede).
Duplicatesarenotallowed.
Q336.ExplainaboutNavigableSet?
ItischildinterfaceofSortedSetandprovidesseveralutilitymethodsfornavigation
purposes
Itdoesntallowsduplicates
InsertionorderispreservedItis
introducedin1.6version
Q337.ExplainaboutQueueinterface?
Ifwewanttorepresentagroupofindividualobjectspriortoprocessing,thenweshould
goforQueueinterface.ItischildinterfaceofCollectioninterface.
Ithasintroducedin1.5version.
Q338.ExplainaboutMapinterface?
RememberitisnotachildInterfaceofCollectionInterfaceandhenceMapandCollection
Interfacesdoesnthaveanyrelationship.
ItcanbeusedforrepresentingagroupofObjectsaskey,valuepairs.Bothkeysand
valuesshouldbeobjects
Keyscantbeduplicatedbutvaluescanbeduplicated.ithasintroducedin1.2version
Q339.ExplainaboutSortedMap?
Ifwewanttorepresentagroupofobjectsaskeyvaluepairswherealltheentriesare
arrangedaccordingsomesortingorderofkeysthenweshouldgoforSortedMap.Itis
childinterfaceofMap.
Ithasintroducedin1.2version
Q340.ExplainaboutNavigableMap?
ItischildinterfaceofSortedMapanddefinesseveralmethodfornavigation
purposeItisintroducedin1.6version
Q341.ExplainaboutArrayListclass?
ArrayListisaCollectionwhichcanbeusedtorepresentagroupofobjectsasasingle
entity.
itisaimplementedclassforListinterface
Introducedin1.2version
Theunderlyingdatastructureisresizableorgrowablearray.Insertionorderis
preserved
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

42/48

6/16/2015

JavaInterviewQuestions

DuplicatesareallowedHeterogeneousobjects
areallowednullinsertionispossible
ThisclassimplementsRandomAccess,Serializable,CloneableinterfacesBestchoicefor
retrievalpurposeandworstifourfrequentoperationisinsertionordeletioninthemiddle
Q342.WhatisRandomAccessInterface?
IfacollectionclassimplementsRandomAccessinterfacethenwecanaccessanyof
itselementwiththesamespeed.
RandomAccessinterfaceismarkerinterfaceanditdosentcontainsanymethods.
ArrayListandvectorclassesimplementsthisinterface.
Q343.ExplainaboutLinkedListclass?
LinkedListisaCollectionimplementedclasswhichcanbeusedforrepresentinga
groupofobjectsasasingleentity.
LinkedLististheimplemetationclassforListinterfaceIntroducedin1.2
version
UnderlyingdataStructureisDoubleLinkedListAllowsduplicatesInsertionorder
ispreserved
Allowsheterogeneousobjectsnull
insertionispossible
LinkedListclassimplementsSeriallizableandCloneableinterfacebutnotRandomAccess
interface
Bestchoiceiffrequentoperationisinsertionordeletionanobjectsinmiddlebutworst
choiceiffrequentoperationisretrieval.
Q344.ExplainaboutVectorclass?
Vectorisalegacycollectionclasswhichcanbeusedtorepresentagroupofobjects.
Introducedin1.0version.itislegacyclass
Theunderlyingdatastructureisresizableorgrowablearray.Insertionorderis
preserved
DuplicatesareallowedHeterogeneousobjects
areallowed
ItisaimplementedclassforListinterfacenullinsertionispossibleVectorclassimplements
RandomAccess,Serializable,CloneableinterfacesBestChoiceiffrequentoperationis
retrievalandworstchoiceiffrequentoperationisinsertionordeletioninthemiddle.
AllmethodspresentinVectorclassaresynchronizedhenceVectorclassobjectisthread
safe.
Q345.HowwecangetsynchronizedversionofArrayList?
CollectionsclasscontainssynchronizedList()methodforthisPublicstatic
ListsynchronizedList(Listl)
EX
ArrayListl=newArrayList()
Listl2=Collections.synchronizedList(l)
SimilarlywecangetsynchronizedversionsofSetandMapobjectsbythefollowing
methods.PublicstaticListsynchronizedSet(Sets)
PublicstaticListsynchronizedMap(Mapm)
Q346.WhatisdifferencebetweensizeandcapacityofaCollectionObject?
sizemeansnumberofobjectspresentwhereascapacitymeansnoofobjectsitcan
accommodate.

http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

43/48

6/16/2015

JavaInterviewQuestions

Q347.WhatarelegacyclassesandinterfacespresentinCollections
framework?
EnumerationInterfaceDictonary
Abstractclass
Hashtable
Properties
Vector

Concreteclass
Concreteclass
ConcreteclassStackConcreteclass

Q348.WhatarelimitationsofEnumeration?
WhileiteratingtheelementswearenotallowedtoperformremovaloperationItis
applicableonlyforlegacyclassesanditisnotauniversalcursor.Itcanretrievethe
elementsonlyinforwarddirection.
Q349.WhatisdifferencebetweenenumandEnumeration?
Anenumcanbeusedtodefineagroupofnamedconstants.Ithasintroducedin
1.5versionEx
ClassBeer{
KO,KF,RC,FO
}
EnumerationiscursortoretrieveObjectsonebyonefromCollectionobjects.
Q350.WhatisdifferencebetweenIteratorandListIterator?oListIteratoristhe
childinterfaceoftheIterator
oIteratoristhesingledirectioncursorwhereasListIteratorisbidirectionalcursor.o
WhileiteratingtheelementsbyIteratorwecanperformonlyreadandremove
operations.ButbyusingListIteratorwecanperformread,removal,replace
andadditionofnewobjectsalso.
oIteratorisapplicableforeveryCollectonimplementedclassobjectbutListIteratoris
applicableonlyforListimplementedclassobjects.
oIteratorcanbegetbyusingiterator()ofCollectioninterfacewhereasListIterator
canbegetbyusinglistIterator()methodofListinterfaceo
bothareintroducedin1.2version
Q351.WhatisrelationbetweenListIteratorandIterator?
ListIteratorischildinterfaceofIterator
Q352.ExplainaboutHashSetclass?
TheunderlyingdatastructureisHashtablenullvaluesareacceptedduplicatesare
notallowed
insertionorderisbasedonhashcodeoftheobjecthenceinsertionorderisnotpreserved
bestsuitableiffrequentoperationissearchoperationsHashSetclassimplements
SerializableandCloneableitisimplementationclassforSetinterface
heterogeneousobjectsarealloweditis
introducedin1.2version

Q353.IfwearetryingtoinsertduplicatevaluesinSetwhatwillhappen?
IfwearetryingtoinsertduplicateobjectstotheHashSet,wewontgetanycompiletime
orruntimeerrorsjusttheadd(Objecto)returnsfalseanditdoesntaddthatobject.
Q354.WhatisLinkedHashSet?
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

44/48

6/16/2015

JavaInterviewQuestions

ItisthechildclassofHashSet.ThemaindifferencebetweenHashSetandLinkedHashSet
is: In the case of HashSet insertion order is not preserved , but in the case of
LinkedHashSetinsertionwillbepreserved.
Q355.Whataremajorenhancementsin1.4versionofcollectionframework?
LinkedHashSet
LinkedHashMap
IdentityHashMap
Q356.ExplainaboutTreeSet?
ItisCollectionobjectwhichcanbeusedtorepresentagroupofobjectsaccordingto
somesortingorder.
TheunderlyingdatastructureisBalancedtreeDuplicatesarenotallowedAllobjectsare
storedaccordingtosomesortingorderhenceinsertionorderisnotpreserved
Heterogeneousobjectsarenotallowedviolationleadsto
ClassCastException
For an Empty TreeSet as firs element null value can be inserted but after inserting that
firstvalueifwearetryingtoinsertanyotherobjectsthenwewillgetNullPointerException
ForannonemptyTreeSetifwearetryingtoinsernullvalueatruntimeuwillget
NullPointerException
Q357.WhatisComparableinterface?
Thisinterfacecanbeusedfordefiningnaturalsortingorderoftheobjects.Itis
presentinjava.langpackage
ItcontainsamethodpublicintcompareTo(Objectobj1)
Q358.WhatisComparatorinterface?
Thisinterfacecanbeusedforimplementingcustomizedsortingorder.Itispresentin
java.utilpackage
Itcontainstwomethods
opublicintcompare(Object,Object)opublicbooleanequals(Object)

Q359.WhatisEntryinterface?
ItisinnerinterfaceofMap.
IntheMapeachkeyvaluepairisconsideredasEntryobject.interfaceMap{
//more code here interface
Entry{ObjectgetKey()
ObjectgetValue()
ObjectsetValue(Objectnew)
}
}
Q360.ExplainaboutHashMap?
ItisaMapObjectwhichcanbeusedusedtorepresentagroupofobjectsaskeyvalue
pairs.
TheunderlyingdatastructureisHashtable
Duplicaeskeysarenotallowedduplicatevaluesareallowed
Insertionorderisnotpreservedbecauseinsertionisbasedonhashcodeofkeys.
Heterogeneousobjectsareallowedforbothkeysandvaluesnullkeyisallowedonly
once
nullvaluesareallowedmultipletimesIntroduced
in1.2version
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

45/48

6/16/2015

JavaInterviewQuestions

Q361.ExplainaboutLinkedHashMap?
ItischildclassofHashMap.ItisexactlysameasHashMapexceptthefollowing
difference.InthecaseofHashMaptheinsertionorderisnotpreservedbutinthecaseof
LinkedHashMapinsertionorderispreserved.Introducedin1.4version
Q362.WhatisIdentityHashMap?
ItisexactlysameasHashMapexceptthefollowingdifference.
IntheHashMapJVMusesequals()methodtoidentifyduplicatekeysbutinthecaseof
IdentityHashMapJVMuses==operatorforthis.
Q363.WhatisdifferencebetweenHashMapand
IdentityHashMap?
ReferQ377fortheanswer.
Q364.WhatisWeakHashMap?
ItisexactlysameasHashMapexceptthefollowingdifference.
IncaseofHashMapanObjectisnoteligibleforgarbagecollectionifitisassociatedwith
HashMapeventhoughitdosenthaveanyexternaldominatesgarbagecollector.
ButincaseofWeakHashMap,ifanObjectisnothavinganyexternalreferencesthenitis
alwayseligibleforgarabagecollectoioneventhoughitisassociatedwithweakHashMap.
iegarbagecollectordominatesWeakHashMap
Q365.WhatisdifferencebetweenHashMapandWeakHashMap?
ReferQ379fortheanswer.
Q366.WhatisTreeMap?
TreeMapcanbeusedtostoreagroupofobjectsaskeyvaluepairswhereallthe
entriesarearrangedaccordingtosomesortingorderofkeys.
TheunderlyingdatastructureisREDBLACKTree
Duplicateskeysarenotallowedbutvaluescanbeduplicated.Insertionorder
isnotpreservedbecauseinsertionisbasedonsomesortingorder
IfwearedependingonNaturalsortingorderthenkeysshouldbe
homogeneous(violationleadstoClassCastException)butvaluesneednothomogeneous
Incaseofcustomizedsortingorderwecaninsertheterogeneouskeysandvalues
ForemptyTreeMapasfirstentrywithnullvaluesareallowedbutafterinsertingthatentryif
wearetryingtoinsertanyotherentrywewillgetNullPointerExceptionFornonempty
TreeMapifwearetryingtoinsertnullkeyswewillget
NullPointerException
Therearenorestrictionsfornullvalues.
Q367.WhatisHashtable?
HashtableisalegacyMapandcanbeusedtostoreobjectsaskeyvaluepairs.
TheunderlyingdatastuructureisHashtabe
Duplicateskeysarenotallowedbutduplicatevaluesareallowednull
insertionisnotpossibleforbothkeysandvalues
allmethodsaresynchronizedinsertionorderisnotpreservedbecauseitisbasedon
hashcodeofkeysheterogeneousObjectsareallowedforbothkeysandvaluesintroduced
in1.0versionitislegacyclass
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

46/48

6/16/2015

JavaInterviewQuestions

Q368.WhatisPriorityQueue?
Itrepresentsadatastructuretoholdgroupofindividualobjectspriortoprocessing
basedonsomepriority.itcanbenaturalsortingorderanditcanbecustomizedsorting
orderdescribedbyComparator.
ItistheimplementationclassofQueueinterface.
Insertionorderisnotpreservedbecausehereinsertionisdonebasedonsome

sortingorder
Duplicatesarenotallowed
nullinsertionisnotpossibleevenasfirstelementalso
IfwearedependingonnaturalsortingorderObjectsshouldbehomogeneous
violationleadstoClassCastException
IfwearedependingoncustomizedsortingorderObjectscanbeheterogeneous
also.
Q369.WhatisArraysclass?
Itisutilityclassforarrays.
Itdefinesseveralutilitymethodsforarrayslikesortinganarrayorsearchingan
elementinarray
presentinjava.utilpackage
Q370.Weareplanningtodoanindexedsearchinalistofobjects.Whichofthetwo
Javacollectionsshouldyouuse:ArrayListorLinkedList?
ArrayList
Q371.WhyArrayListisfasterthanVector?
AllmethodspresentintheVectoraresynchronizedandhenceanymethodcanbe
executedbyonlyonethreadatatime.Itslowsdowntheexecution.
ButinArrayList,nomethodissynchronizedandhencemultiplethreadareallowedexecute
simultaneouslywhichspeeduptheexecution.

Posted28thJune2014bymanojbokku
http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

47/48

6/16/2015

JavaInterviewQuestions

0 Addacomment

Enteryourcomment...

Commentas:

Publish

raja(Google)

Preview

http://javatooj2ee.blogspot.in/2014/06/javainterviewquestions1.html

Signout

Notifyme

48/48

You might also like