java interview questions

48
28th June 2014 [http://2.bp.blogspot.com/7Z1VZHYyxeg/U670Z2WkT3I/AAAAAAAAB2I/Ykz6ANsQwiQ/s1600/interview11.jpg] 1.What is JVM? The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM) 2. What is the most important feature of Java? Java is a platform independent language. 3. What do you mean by platform independence? Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc). 4. What is the difference between a JDK and a JVM? JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM. 5. What is the base class of all classes? java.lang.Object 6. What are the access modifiers in Java? There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly. 7. What is are packages? A package is a collection of related classes and interfaces providing access protection and namespace management. Java Interview Questions Java interview Questions

Upload: rajareddy

Post on 14-Sep-2015

35 views

Category:

Documents


3 download

DESCRIPTION

Best book

TRANSCRIPT

  • 6/16/2015 JavaInterviewQuestions

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

    28thJune2014

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

    1.WhatisJVM?TheJavainterpreteralongwiththeruntimeenvironmentrequiredtoruntheJavaapplicationincalledasJavavirtualmachine(JVM)

    2.WhatisthemostimportantfeatureofJava?Javaisaplatformindependentlanguage.

    3.Whatdoyoumeanbyplatformindependence?Platformindependencemeansthatwecanwriteandcompilethejavacodeinoneplatform(egWindows)andcanexecutetheclassinanyothersupportedplatformeg(Linux,Solaris,etc).

    4.WhatisthedifferencebetweenaJDKandaJVM?JDKisJavaDevelopmentKitwhichisfordevelopmentpurposeanditincludesexecutionenvironmentalso.ButJVMispurelyaruntimeenvironmentandhenceyouwillnotbeabletocompileyoursourcefilesusingaJVM.

    5.Whatisthebaseclassofallclasses?java.lang.Object

    6.WhataretheaccessmodifiersinJava?Thereare3accessmodifiers.Public,protectedandprivate,andthedefaultoneifnoidentifierisspecifiediscalledfriendly,butprogrammercannotspecifythefriendlyidentifierexplicitly.

    7.Whatisarepackages?Apackageisacollectionofrelatedclassesandinterfacesprovidingaccessprotectionandnamespacemanagement.

    JavaInterviewQuestions

    JavainterviewQuestions

  • 6/16/2015 JavaInterviewQuestions

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

    8.WhatismeantbyInheritanceandwhatareitsadvantages?Inheritanceistheprocessofinheritingallthefeaturesfromaclass.Theadvantagesofinheritancearereusabilityofcodeandaccessibilityofvariablesandmethodsofthesuperclassbysubclasses.

    9.Whatisthedifferencebetweensuperclassandsubclass?Asuperclassisaclassthatisinheritedwhereassubclassisaclassthatdoestheinheriting.

    10.Whatisanabstractclass?Anabstractclassisaclassdesignedwithimplementationgapsforsubclassestofillinandisdeliberatelyincomplete.

    11.Whatarethestatesassociatedinthethread?Threadcontainsready,running,waitinganddeadstates.

    12.Whatissynchronization?Synchronizationisthemechanismthatensuresthatonlyonethreadisaccessedtheresourcesatatime.

    13.Whatisdeadlock?Whentwothreadsarewaitingeachotherandcantprecedetheprogramissaidtobedeadlock.

    14.Whatisanapplet?Appletisadynamicandinteractiveprogramthatrunsinsideawebpagedisplayedbyajavacapablebrowser

    15.Whatisthelifecycleofanapplet?init()methodCanbecalledwhenanappletisfirstloadedstart()methodCanbecalledeachtimeanappletisstarted.paint()methodCanbecalledwhentheappletisminimizedormaximized.stop()methodCanbeusedwhenthebrowsermovesofftheappletspage.destroy()methodCanbecalledwhenthebrowserisfinishedwiththeapplet.

    16.Howdoyousetsecurityinapplets?usingsetSecurityManager()method

    17.WhatisalayoutmanagerandwhataredifferenttypesoflayoutmanagersavailableinjavaAWT?Alayoutmanagerisanobjectthatisusedtoorganizecomponentsinacontainer.ThedifferentlayoutsareavailableareFlowLayout,BorderLayout,CardLayout,GridLayoutandGridBagLayout

    18.WhatisJDBC?JDBCisasetofJavaAPIforexecutingSQLstatements.ThisAPIconsistsofasetofclassesandinterfacestoenableprogramstowritepureJavaDatabaseapplications.

    19.Whataredriversavailable?a)JDBCODBCBridgedriverb)NativeAPIPartlyJavadriverc)JDBCNetPureJavadriverd)NativeProtocolPureJavadriver

    20.Whatisstoredprocedure?StoredprocedureisagroupofSQLstatementsthatformsalogicalunitandperformsaparticulartask.StoredProceduresareusedtoencapsulateasetofoperationsorqueriestoexecuteondatabase.Storedprocedurescanbecompiledandexecutedwithdifferentparametersandresultsandmayhaveanycombinationofinput/outputparameters.

    21.WhatistheJavaAPI?TheJavaAPIisalargecollectionofreadymadesoftwarecomponentsthatprovidemanyusefulcapabilities,suchasgraphicaluserinterface(GUI)widgets.

  • 6/16/2015 JavaInterviewQuestions

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

    22.WhytherearenoglobalvariablesinJava?Globalvariablesaregloballyaccessible.Javadoesnotsupportgloballyaccessiblevariablesduetofollowingreasons:1)Theglobalvariablesbreaksthereferentialtransparency2)Globalvariablescreatescollisionsinnamespace.

    23.WhatareEncapsulation,InheritanceandPolymorphism?Encapsulationisthemechanismthatbindstogethercodeanddataitmanipulatesandkeepsbothsafefromoutsideinterferenceandmisuse.Inheritanceistheprocessbywhichoneobjectacquiresthepropertiesofanotherobject.Polymorphismisthefeaturethatallowsoneinterfacetobeusedforgeneralclassactions.

    24.WhatistheuseofbinandlibinJDK?Bincontainsalltoolssuchasjavac,appletviewer,awttool,etc.,whereaslibcontainsAPIandallpackages.

    25.Whatismethodoverloadingandmethodoverriding?Methodoverloading:Whenamethodinaclasshavingthesamemethodnamewithdifferentargumentsissaidtobemethodoverloading.Methodoverriding:Whenamethodinaclasshavingthesamemethodnamewithsameargumentsissaidtobemethodoverriding.

    26.Whatisthedifferencebetweenthis()andsuper()?this()canbeusedtoinvokeaconstructorofthesameclasswhereassuper()canbeusedtoinvokeasuperclassconstructor.

    27.WhatisDomainNamingService(DNS)?Itisverydifficulttorememberasetofnumbers(IPaddress)toconnecttotheInternet.TheDomainNamingService(DNS)isusedtoovercomethisproblem.ItmapsoneparticularIPaddresstoastringofcharacters.Forexample,www.mascom.comimpliescomisthedomainnamereservedforUScommercialsites,moscomisthenameofthecompanyandwwwisthenameofthespecificcomputer,whichismascomsserver.

    28.WhatisURL?URLstandsforUniformResourceLocatoranditpointstoresourcefilesontheInternet.URLhasfourcomponents:http://www[http://www/].address.com:80/index.html,wherehttpprotocolname,addressIPaddressorhostname,80portnumberandindex.htmlfilepath.

    29.WhatisRMIandstepsinvolvedindevelopinganRMIobject?RemoteMethodInvocation(RMI)allowsjavaobjectthatexecutesononemachineandtoinvokethemethodofaJavaobjecttoexecuteonanothermachine.ThestepsinvolvedindevelopinganRMIobjectare:a)Definetheinterfacesb)Implementingtheseinterfacesc)Compiletheinterfacesandtheirimplementationswiththejavacompilerd)CompiletheserverimplementationwithRMIcompilere)RuntheRMIregistryf)Runtheapplication.

    30.WhatisRMIarchitecture?RMIarchitectureconsistsoffourlayersandeachlayerperformsspecificfunctions:a)Applicationlayercontainstheactualobjectdefinition.b)Proxylayerconsistsofstubandskeleton.c)RemoteReferencelayergetsthestreamofbytesfromthetransportlayerandsendsittotheproxylayer.d)Transportationlayerresponsibleforhandlingtheactualmachinetomachinecommunication.

    31.WhatisaJavaBean?AJavaBeanisasoftwarecomponentthathasbeendesignedtobereusableinavarietyofdifferentenvironments.32.Whatarecheckedexceptions?CheckedexceptionarethosewhichtheJavacompilerforcesyoutocatch.e.g.IOExceptionarecheckedExceptions.

  • 6/16/2015 JavaInterviewQuestions

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

    33.Whatareruntimeexceptions?Runtimeexceptionsarethoseexceptionsthatarethrownatruntimebecauseofeitherwronginputdataorbecauseofwrongbusinesslogicetc.Thesearenotcheckedbythecompileratcompiletime.

    34.Whatisthedifferencebetweenerrorandanexception?Anerrorisanirrecoverableconditionoccurringatruntime.SuchasOutOfMemoryerror.TheseJVMerrorsandyoucannotrepairthematruntime.Whileexceptionsareconditionsthatoccurbecauseofbadinputetc.e.g.FileNotFoundExceptionwillbethrownifthespecifiedfiledoesnotexist.OraNullPointerExceptionwilltakeplaceifyoutryusinganullreference.Inmostofthecasesitispossibletorecoverfromanexception(probablybygivinguserafeedbackforenteringpropervaluesetc.).

    35.Whatisthepurposeoffinalization?Thepurposeoffinalizationistogiveanunreachableobjecttheopportunitytoperformanycleanupprocessingbeforetheobjectisgarbagecollected.Forexample,closingaopenedfile,closingaopeneddatabaseConnection.

    36.Whatisthedifferencebetweenyieldingandsleeping?Whenataskinvokesitsyield()method,itreturnstothereadystate.Whenataskinvokesitssleep()method,itreturnstothewaitingstate.

    37.Whatisthedifferencebetweenpreemptiveschedulingandtimeslicing?Underpreemptivescheduling,thehighestprioritytaskexecutesuntilitentersthewaitingordeadstatesorahigherprioritytaskcomesintoexistence.Undertimeslicing,ataskexecutesforapredefinedsliceoftimeandthenreentersthepoolofreadytasks.Theschedulerthendetermineswhichtaskshouldexecutenext,basedonpriorityandotherfactors.

    38.Whatismutableobjectandimmutableobject?IfaobjectvalueischangeablethenwecancallitasMutableobject.(Ex.,StringBuffer,)Ifyouarenotallowedtochangethevalueofanobject,itisimmutableobject.(Ex.,String,Integer,Float,)39.WhatisthepurposeofVoidclass?TheVoidclassisanuninstantiableplaceholderclasstoholdareferencetotheClassobjectrepresentingtheprimitiveJavatypevoid.

    40.WhatisJITanditsuse?Really,justaveryfastcompilerInthisincarnation,prettymuchaonepasscompilernoofflinecomputations.Soyoucantlookatthewholemethod,ranktheexpressionsaccordingtowhichonesarereusedthemost,andthengeneratecode.Intheoryterms,itsanonlineproblem.

    41.Whatisnestedclass?Ifallthemethodsofainnerclassisstaticthenitisanestedclass.42.WhatisHashMapandMap?MapisInterfaceandHashmapisclassthatimplementsthat.43.Whataredifferenttypesofaccessmodifiers?public:Anythingdeclaredaspubliccanbeaccessedfromanywhere.private:Anythingdeclaredasprivatecantbeseenoutsideofitsclass.protected:Anythingdeclaredasprotectedcanbeaccessedbyclassesinthesamepackageandsubclassesintheotherpackages.defaultmodifier:Canbeaccessedonlytoclassesinthesamepackage.

    44.WhatisthedifferencebetweenReader/WriterandInputStream/OutputStream?TheReader/WriterclassischaracterorientedandtheInputStream/OutputStreamclassisbyteoriented.

    45.Whatisservlet?Servletsaremodulesthatextendrequest/responseorientedservers,suchasjavaenabledwebservers.Forexample,aservletmightberesponsiblefortakingdatainanHTMLorderentryformandapplyingthebusiness

  • 6/16/2015 JavaInterviewQuestions

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

    logicusedtoupdateacompanysorderdatabase.

    46.WhatisConstructor?Aconstructorisaspecialmethodwhosetaskistoinitializetheobjectofitsclass.Itisspecialbecauseitsnameisthesameastheclassname.Theydonothavereturntypes,notevenvoidandthereforetheycannotreturnvalues.Theycannotbeinherited,thoughaderivedclasscancallthebaseclassconstructor.Constructorisinvokedwheneveranobjectofitsassociatedclassiscreated.

    47.WhatisanIterator?TheIteratorinterfaceisusedtostepthroughtheelementsofaCollection.IteratorsletyouprocesseachelementofaCollection.IteratorsareagenericwaytogothroughalltheelementsofaCollectionnomatterhowitisorganized.IteratorisanInterfaceimplementedadifferentwayforeveryCollection.

    48.WhatistheListinterface?TheListinterfaceprovidessupportfororderedcollectionsofobjects.Listsmaycontainduplicateelements.

    49.Whatismemoryleak?Amemoryleakiswhereanunreferencedobjectthatwillneverbeusedagainstillhangsaroundinmemoryanddoesntgetgarbagecollected.

    50.Whatisthedifferencebetweentheprefixandpostfixformsofthe++operator?Theprefixformperformstheincrementoperationandreturnsthevalueoftheincrementoperation.Thepostfixformreturnsthecurrentvaluealloftheexpressionandthenperformstheincrementoperationonthatvalue.

    51.Whatisthedifferencebetweenaconstructorandamethod?Aconstructorisamemberfunctionofaclassthatisusedtocreateobjectsofthatclass.Ithasthesamenameastheclassitself,hasnoreturntype,andisinvokedusingthenewoperator.Amethodisanordinarymemberfunctionofaclass.Ithasitsownname,areturntype(whichmaybevoid),andisinvokedusingthedotoperator.

    52.WhatwillhappentotheExceptionobjectafterexceptionhandling?Exceptionobjectwillbegarbagecollected.

    53.Differencebetweenstaticanddynamicclassloading.Staticclassloading:Theprocessofloadingaclassusingnewoperatoriscalledstaticclassloading.Dynamicclassloading:Theprocessofloadingaclassatruntimeiscalleddynamicclassloading.DynamicclassloadingcanbedonebyusingClass.forName(.).newInstance().

    54.ExplaintheCommonuseofEJBTheEJBscanbeusedtoincorporatebusinesslogicinawebcentricapplication.TheEJBscanbeusedtointegratebusinessprocessesinBusinesstobusiness(B2B)ecommerceapplications.InEnterpriseApplicationIntegrationapplications,EJBscanbeusedtohouseprocessingandmappingbetweendifferentapplications.

    55.WhatisJSP?JSPisatechnologythatreturnsdynamiccontenttotheWebclientusingHTML,XMLandJAVAelements.JSPpagelookslikeaHTMLpagebutisaservlet.ItcontainsPresentationlogicandbusinesslogicofawebapplication.

    56.Whatisthepurposeofapachetomcat?ApacheserverisastandaloneserverthatisusedtotestservletsandcreateJSPpages.Itisfreeandopen

  • 6/16/2015 JavaInterviewQuestions

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

    sourcethatisintegratedintheApachewebserver.Itisfast,reliableservertoconfiguretheapplicationsbutitishardtoinstall.Itisaservletcontainerthatincludestoolstoconfigureandmanagetheservertoruntheapplications.ItcanalsobeconfiguredbyeditingXMLconfigurationfiles.

    57.Wherepragmaisused?Pragmaisusedinsidetheservletsintheheaderwithacertainvalue.Thevalueisofnocachethattellsthataservletsisactingasaproxyandithastoforwardrequest.PragmadirectivesallowthecompilertousemachineandoperatingsystemfeatureswhilekeepingtheoverallfunctionalitywiththeJavalanguage.Thesearedifferentfordifferentcompilers.

    58.Brieflyexplaindaemonthread.Daemonthreadisalowprioritythreadwhichrunsinthebackgroundperformsgarbagecollectionoperationforthejavaruntimesystem.

    59.Whatisanativemethod?AnativemethodisamethodthatisimplementedinalanguageotherthanJava.

    60.Explaindifferentwayofusingthread?AJavathreadcouldbeimplementedbyusingRunnableinterfaceorbyextendingtheThreadclass.TheRunnableismoreadvantageous,whenyouaregoingformultipleinheritance.

    61.WhatarethetwomajorcomponentsofJDBC?Oneimplementationinterfacefordatabasemanufacturers,theotherimplementationinterfaceforapplicationandappletwriters.

    62.WhatkindofthreadistheGarbagecollectorthread?Itisadaemonthread.

    63.Whatarethedifferentwaystohandleexceptions?Therearetwowaystohandleexceptions,1.Bywrappingthedesiredcodeinatryblockfollowedbyacatchblocktocatchtheexceptions.and2.Listthedesiredexceptionsinthethrowsclauseofthemethodandletthecallerofthemethodhandlethoseexceptions.

    64.Howmanyobjectsarecreatedinthefollowingpieceofcode?MyClassc1,c2,c3c1=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 leftunimplemented.Interfacescontainnoimplementationcode.2. Anclasscan implementanynumberof interfaces,butsubclassatmostoneabstract

  • 6/16/2015 JavaInterviewQuestions

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

    class.3. Anabstractclasscanhavenonabstractmethods.Allmethodsofaninterfaceareabstract.4.Anabstractclasscanhaveinstancevariables.Aninterfacecannot.5.Anabstractclasscandefineconstructor.Aninterfacecannot.6.Anabstractclasscanhaveanyvisibility:public,protected,privateornone(package).Aninterface'svisibilitymustbepublicornone(package).7. Anabstractclass inherits fromObjectand includesmethodssuchasclone()andequals().

    Q2.Whatarecheckedanduncheckedexceptions?Javadefinestwokindsofexceptions:Checkedexceptions:ExceptionsthatinheritfromtheExceptionclassarecheckedexceptions.ClientcodehastohandlethecheckedexceptionsthrownbytheAPI,either inacatchclauseorbyforwardingitoutwardwiththethrowsclause.ExamplesSQLException,IOxception.Uncheckedexceptions:RuntimeExceptionalsoextendsfromException.However,alloftheexceptionsthatinheritfromRuntimeExceptiongetspecialtreatment.Thereisnorequirementfortheclientcodetodealwiththem,andhencetheyarecalleduncheckedexceptions.ExampleUncheckedexceptionsareNullPointerException,OutOfMemoryError,DivideByZeroExceptiontypically,programmingerrors.

    Q3.Whatisauserdefinedexception?Userdefinedexceptionsmaybeimplementedbydefiningaclasstorespondtotheexceptionandembeddingathrowstatementinthetryblockwheretheexceptioncanoccurordeclaringthatthemethodthrowstheexception(toanothermethodwhereitishandled).ThedevelopercandefineanewexceptionbyderivingitfromtheExceptionclassasfollows:publicclassMyExceptionextendsException{/*classdefinitionofconstructors(butNOTtheexceptionhandlingcode)goesherepublicMyException(){super()}public MyException( String errorMessage ) { super(errorMessage)}

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

    }Thethrowstatementisusedtosignaltheoccuranceoftheexceptionwithinatryblock.Often,exceptionsareinstantiatedinthesamestatementinwhichtheyarethrownusingthesyntax.thrownewMyException("Ithrewmyownexception.")Tohandletheexceptionwithinthemethodwhereitisthrown,acatchstatementthathandlesMyException,mustfollowthetryblock.Ifthedeveloperdoesnotwanttohandletheexceptioninthemethoditself,themethodmustpasstheexceptionusingthesyntax:publicmyMethodName()throwsMyException

    Q4.WhatisthedifferencebetweenC++&Java?WellasBjarneStroustrupsays"..despitethesyntacticsimilarities,C++andJavaareverydifferentlanguages.Inmanyways,JavaseemsclosertoSmalltalkthantoC++..".HerearefewIdiscovered:JavaismultithreadedJavahasnopointersJavahasautomaticmemorymanagement(garbagecollection)

  • 6/16/2015 JavaInterviewQuestions

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

    Javaisplatformindependent(Stroustrupmaydifferbysaying"Javaisaplatform"JavahasbuiltinsupportforcommentdocumentationJavahasnooperatoroverloadingJavadoesntprovidemultipleinheritanceTherearenodestructorsinJava

    Q5.WhatarestatementsinJAVA?Statementsareequivalenttosentencesinnaturallanguages.Astatementformsacompleteunitofexecution.ThefollowingtypesofexpressionscanbemadeintoastatementbyterminatingtheexpressionwithasemicolonAssignmentexpressionsAnyuseof++orMethodcallsObjectcreationexpressionsThesekindsofstatementsarecalledexpressionstatements.Inadditiontothesekindsofexpressionstatements,therearetwootherkindsofstatements.Adeclarationstatementdeclaresavariable.Acontrolflowstatementregulatestheorderinwhichstatementsgetexecuted.Theforloopandtheifstatementarebothexamplesofcontrolflowstatements.

    Q6.WhatisJARfile?JavaARchivefilesareabigglobofJavaclasses,images,audio,etc.,

    compressedtomakeonesimple,smallerfiletoeaseAppletdownloading.Normallywhenabrowserencountersanapplet,itgoesanddownloadsallthefiles,images,audio,usedbytheAppletseparately.Thiscanleadtoslowerdownloads.

    Q7.WhatisJNI?JNIisanacronymofJavaNativeInterface.UsingJNIwecancallfunctionswhicharewritteninotherlanguagesfromJava.Followingareitsadvantagesanddisadvantages.Advantages:Youwanttouseyourexistinglibrarywhichwaspreviouslywritteninotherlanguage.YouwanttocallWindowsAPIfunction.Forthesakeofexecutionspeed.YouwanttocallAPIfunctionofsomeserverproductwhichisincorc++fromjavaclient.Disadvantages:Youcantsaywriteoncerunanywhere.Difficulttodebugruntimeerrorinnativecode.Potentialsecurityrisk.YoucantcallitfromApplet.

    Q8.Whatisserialization?Quitesimply,objectserializationprovidesaprogramtheabilitytoreadorwriteawholeobjecttoandfromarawbytestream.ItallowsJavaobjectsandprimitivestobeencodedintoabytestreamsuitableforstreamingtosometypeofnetworkortoafilesystem,ormoregenerally,toatransmissionmediumorstoragefacility.AseralizableobjectmustimplementtheSerilizableinterface.WeuseObjectOutputStreamtowritethisobjecttoastreamandObjectInputStreamtoreaditfromthestream.

    Q9.Whytherearesomenullinterfaceinjava?Whatdoesitmean?GivemesomenullinterfacesinJAVA?Nullinterfacesactasmarkers..theyjusttellthecompilerthattheobjectsofthisclassneedtobetreateddifferently..somemarkerinterfacesare:Serializable,Remote,Cloneable.

  • 6/16/2015 JavaInterviewQuestions

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

    Q10.Issynchronizedamodifier?Identifier?Whatisit??It'samodifier.Synchronizedmethodsaremethodsthatareusedtocontrolaccesstoanobject.Athreadonlyexecutesasynchronizedmethodafterithasacquiredthelockforthemethod'sobjectorclass.Synchronizedstatementsaresimilartosynchronizedmethods.Asynchronizedstatementcanonlybeexecutedafterathreadhasacquiredthelockfortheobjectorclassreferencedinthesynchronizedstatement.

    Q11.Whatissingletonclass?whereisitused?Singletonisadesignpatternmeanttoprovideoneandonlyoneinstanceofanobject.Otherobjectscangetareferencetothisinstancethroughastaticmethod(classconstructoriskeptprivate).Whydoweneedone?Sometimesitisnecessary,andoftensufficient,tocreateasingleinstanceofagivenclass.Thishasadvantagesinmemorymanagement,andforJava,ingarbagecollection.Moreover,restrictingthenumberofinstancesmaybenecessaryordesirablefortechnologicalorbusinessreasonsforexample,wemayonlywantasingleinstanceofapoolofdatabaseconnections.

    Q12.Whatisacompilationunit?Thesmallestunitofsourcecodethatcanbecompiled,i.e.a.javafile.

    Q13.Isstringsawrapperclass?Stringisaclass,butnotawrapperclass.Wrapperclasseslike(Integer)existforeachprimitivetype.Theycanbeusedtoconvertaprimitivedatavalueintoanobject,andviceversa.

    Q14.Whyjavadoesnothavemultipleinheritances?TheJavadesignteamstrovetomakeJava:Simple,objectoriented,andfamiliarRobustandsecureArchitectureneutralandportableHighperformanceInterpreted,threaded,anddynamicThereasonsforomittingmultipleinheritancefromtheJavalanguagemostlystemfromthe"simple,objectoriented,andfamiliar"goal.Asasimplelanguage,Java'screatorswantedalanguagethatmostdeveloperscouldgraspwithoutextensivetraining.Tothatend,theyworkedtomakethelanguageassimilartoC++aspossible(familiar)withoutcarryingoverC++'sunnecessarycomplexity(simple).Inthedesigners'opinion,multipleinheritancecausesmoreproblemsandconfusionthanitsolves.Sotheycutmultipleinheritancefromthelanguage(justastheycutoperatoroverloading).Thedesigners'extensiveC++experiencetaughtthemthatmultipleinheritancejustwasn'tworththeheadache.

    Q15.Whyjavaisnota100%oops?ManypeoplesaythisbecauseJavausesprimitivetypessuchasint,char,double.Butthenalltherestareobjects.Confusingquestion.

    Q16.Whatisaresourcebundle?

    Initssimplestform,aresourcebundleisrepresentedbyatextfilecontainingkeysandatextvalueforeachkey.*CoreJava*Servlets&JSP*Struts*EJB

  • 6/16/2015 JavaInterviewQuestions

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

    *J2ME

    Q17.Whatistransientvariable?Transientvariablecan'tbeserialize.ForexampleifavariableisdeclaredastransientinaSerializableclassandtheclassiswrittentoanObjectStream,thevalueofthevariablecan'tbewrittentothestreaminsteadwhentheclassisretrievedfromtheObjectStreamthevalueofthevariablebecomesnull.

    Q18.WhatisCollectionAPI?TheCollectionAPIisasetofclassesandinterfacesthatsupportoperationoncollectionsofobjects. These classes and interfaces are more flexible, more powerful, and moreregularthanthevectors,arrays,andhashtablesifeffectivelyreplaces.Exampleofclasses:HashSet,HashMap,ArrayList,LinkedList,TreeSetandTreeMap.Exampleofinterfaces:Collection,Set,ListandMap.

    Q19.IsIteratoraClassorInterface?Whatisitsuse?IteratorisaninterfacewhichisusedtostepthroughtheelementsofaCollection.

    Q20.Whatissimilarities/differencebetweenanAbstractclassandInterface?Differencesareasfollows:Interfacesprovideaformofmultipleinheritance.Aclasscanextendonlyoneotherclass.Interfacesarelimitedtopublicmethodsandconstantswithnoimplementation.Abstractclassescanhaveapartialimplementation,protectedparts,staticmethods,etc. AClassmay implement several interfaces.But in caseofabstract class,a classmayextendonlyoneabstractclass.Interfacesareslowasitrequiresextraindirectiontotofindcorrespondingmethodinintheactualclass.Abstractclassesarefast.Similarities:NeitherAbstractclassesorInterfacecanbeinstantiated.

    Q21.Whatisatransientvariable?Atransientvariableisavariablethatmaynotbeserialized.

    Q22.WhichcontainersuseaborderLayoutastheirdefaultlayout?

    Thewindow,FrameandDialogclassesuseaborderlayoutastheirdefaultlayout.

    Q23.WhydothreadsblockonI/O?Threadsblockoni/o(thatisentersthewaitingstate)sothatotherthreadsmayexecutewhilethei/oOperationisperformed.

    Q24.HowareObserverandObservableused?ObjectsthatsubclasstheObservableclassmaintainalistofobservers.WhenanObservableobject is updated it invokes the update () method of each of its observers to notify theobserversthatithaschangedstate.TheObserverinterfaceisimplementedbyobjectsthatobserveObservableobjects.

    Q25.Whatissynchronizationandwhyisitimportant?Withrespecttomultithreading,synchronizationisthecapabilitytocontroltheaccessofmultiplethreadstosharedresources.Withoutsynchronization,itispossibleforonethreadtomodifyasharedobjectwhileanotherthreadisintheprocessofusingorupdatingthatobject'svalue.Thisoftenleadstosignificanterrors.

    Q26.Canalockbeacquiredonaclass?Yes,alockcanbeacquiredonaclass.Thislockisacquiredontheclass'sClassobject.

  • 6/16/2015 JavaInterviewQuestions

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

    Q27.What'snewwiththestop(),suspend()andresume()methodsinJDK1.2?Thestop(),suspend()andresume()methodshavebeendeprecatedinJDK1.2.

    Q28.Isnullakeyword?Thenullvalueisnotakeyword.

    Q29.Whatisthepreferredsizeofacomponent?Thepreferredsizeofacomponentistheminimumcomponentsizethatwillallowthecomponenttodisplaynormally.

    Q30.Whatmethodisusedtospecifyacontainer'slayout?ThesetLayout()methodisusedtospecifyacontainer'slayout.

    Q31.WhichcontainersuseaFlowLayoutastheirdefaultlayout?ThePanelandAppletclassesusetheFlowLayoutastheirdefaultlayout.

    Q32.Whatstatedoesathreadenterwhenitterminatesitsprocessing?Whenathreadterminatesitsprocessing,itentersthedeadstate.

    Q33.WhatistheCollectionsAPI?TheCollectionsAPIisasetofclassesandinterfacesthatsupportoperationsoncollectionsofobjects.

    Q34.Whichcharactersmaybeusedasthesecondcharacterofanidentifier,butnotasthefirstcharacterofanidentifier?Thedigits0through9maynotbeusedasthefirstcharacterofanidentifierbuttheymaybeusedafterthefirstcharacterofanidentifier.

    Q35.WhatistheListinterface?TheListinterfaceprovidessupportfororderedcollectionsofobjects.

    Q36.HowdoesJavahandleintegeroverflowsandunderflows?Itusesthoseloworderbytesoftheresultthatcanfitintothesizeofthetypeallowedbytheoperation.

    Q37.WhatistheVectorclass?TheVectorclassprovidesthecapabilitytoimplementagrowablearrayofobjects

    Q38.Whatmodifiersmaybeusedwithaninnerclassthatisamemberofanouterclass?A(nonlocal)innerclassmaybedeclaredaspublic,protected,private,static,final,orabstract.

    Q39.WhatisanIteratorinterface?TheIteratorinterfaceisusedtostepthroughtheelementsofaCollection.

    Q40.Whatisthedifferencebetweenthe>>and>>>operators?The>>operatorcarriesthesignbitwhenshiftingright.The>>>zerofillsbitsthathavebeenshiftedout.

    Q41.WhichmethodoftheComponentclassisusedtosetthepositionandsizeofacomponent?setBounds()

    Q42.HowmanybitsareusedtorepresentUnicode,ASCII,UTF16,andUTF8

  • 6/16/2015 JavaInterviewQuestions

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

    characters?Unicoderequires16bitsandASCIIrequire7bits.AlthoughtheASCIIcharactersetusesonly7bits, it isusuallyrepresentedas8bits.UTF8representscharactersusing8,16,and18bitpatterns.UTF16uses16bitandlargerbitpatterns.

    Q43.Whatisthedifferencebetweenyieldingandsleeping?Whenataskinvokesitsyield()method,itreturnstothereadystate.Whenataskinvokesitssleep()method,itreturnstothewaitingstate.

    Q44.Whichjava.utilclassesandinterfacessupporteventhandling?TheEventObjectclassandtheEventListenerinterfacesupporteventprocessing.

    Q45.Issizeofakeyword?Thesizeofoperatorisnotakeyword.

    Q46.Whatarewrappedclasses?Wrappedclassesareclassesthatallowprimitivetypestobeaccessedasobjects.

    Q47.Doesgarbagecollectionguaranteethataprogramwillnotrunoutofmemory?Garbage collection doesnot guarantee that a programwill not runout ofmemory. It ispossibleforprogramstouseupmemoryresourcesfasterthantheyaregarbagecollected.Itisalsopossibleforprogramstocreateobjectsthatarenotsubjecttogarbagecollection

    Q48.Whatrestrictionsareplacedonthelocationofapackagestatementwithinasourcecodefile?Apackagestatementmustappearasthefirstlineinasourcecodefile(excludingblanklinesandcomments).

    Q49.Cananobject'sfinalize()methodbeinvokedwhileitisreachable?Anobject'sfinalize()methodcannotbeinvokedbythegarbagecollectorwhiletheobjectisstillreachable.However,anobject'sfinalize()methodmaybeinvokedbyotherobjects.

    Q50.WhatistheimmediatesuperclassoftheAppletclass?Panel

    Q51.Whatisthedifferencebetweenpreemptiveschedulingandtimeslicing?Underpreemptivescheduling,thehighestprioritytaskexecutesuntilitentersthewaitingordeadstatesorahigherprioritytaskcomesintoexistence.Undertimeslicing,ataskexecutesforapredefinedsliceoftimeandthenreentersthepoolofreadytasks.Theschedulerthendetermineswhichtaskshouldexecutenext,basedonpriorityandotherfactors.

    Q52NamethreeComponentsubclassesthatsupportpainting.TheCanvas,Frame,Panel,andAppletclassessupportpainting.

    Q53.WhatvaluedoesreadLine()returnwhenithasreachedtheendofafile?ThereadLine()methodreturnsnullwhenithasreachedtheendofafile.

    Q54.WhatistheimmediatesuperclassoftheDialogclass?Window

    Q55.Whatisclipping?Clippingistheprocessofconfiningpaintoperationstoalimitedareaorshape.

  • 6/16/2015 JavaInterviewQuestions

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

    Q56.Whatisanativemethod?AnativemethodisamethodthatisimplementedinalanguageotherthanJava.

    Q57.Canaforstatementloopindefinitely?Yes,forstatementcanloopindefinitely.Forexample,considerthefollowing:for(

    Q58.Whatareorderofprecedenceandassociativity,andhowaretheyused?Orderofprecedencedeterminestheorderinwhichoperatorsareevaluatedinexpressions.Associatitydetermineswhetheranexpressionisevaluatedlefttorightorrighttoleft

    Q59.WhenathreadblocksonI/O,whatstatedoesitenter?AthreadentersthewaitingstatewhenitblocksonI/O.

    Q60.TowhatvalueisavariableoftheStringtypeautomaticallyinitialized?ThedefaultvalueofaStringtypeisnull.

    Q61.Whatisthecatchordeclareruleformethoddeclarations?Ifacheckedexceptionmaybethrownwithinthebodyofamethod,themethodmusteithercatchtheexceptionordeclareitinitsthrowsclause.

    Q62.WhatisthedifferencebetweenaMenuItemandaCheckboxMenuItem?TheCheckboxMenuItemclassextendstheMenuItemclasstosupportamenuitemthatmaybecheckedorunchecked.

    Q63.Whatisatask'spriorityandhowisitusedinscheduling?Atask'spriorityisanintegervaluethatidentifiestherelativeorderinwhichitshouldbeexecutedwithrespecttoothertasks.Theschedulerattemptstoschedulehigherprioritytasksbeforelowerprioritytasks.

    Q64.WhatclassisthetopoftheAWTeventhierarchy?Thejava.awt.AWTEventclassisthehighestlevelclassintheAWTeventclasshierarchy.

    Q65.Whenathreadiscreatedandstarted,whatisitsinitialstate?Athreadisinthereadystateafterithasbeencreatedandstarted.

    Q66.Canananonymousclassbedeclaredasimplementinganinterfaceandextendingaclass?Ananonymousclassmayimplementaninterfaceorextendasuperclass,butmaynotbedeclaredtodoboth.

    Q67.Whatistherangeoftheshorttype?Therangeoftheshorttypeis(2^15)to2^151.

    Q68.Whatistherangeofthechartype?Therangeofthechartypeis0to2^161.

    Q69.InwhichpackagearemostoftheAWTeventsthatsupporttheeventdelegationmodeldefined?MostoftheAWTrelatedeventsoftheeventdelegationmodelaredefinedinthejava.awt.eventpackage.TheAWTEventclassisdefinedinthejava.awtpackage.

  • 6/16/2015 JavaInterviewQuestions

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

    Q70.WhatistheimmediatesuperclassofMenu?MenuItem

    Q71.Whatisthepurposeoffinalization?Thepurposeoffinalizationistogiveanunreachableobjecttheopportunitytoperformanycleanupprocessingbeforetheobjectisgarbagecollected.

    Q72.WhichclassistheimmediatesuperclassoftheMenuComponentclass.Object

    Q73.Whatinvokesathread'srun()method?Afterathreadisstarted,viaitsstart()methodorthatoftheThreadclass,theJVMinvokesthethread'srun()methodwhenthethreadis

    initiallyexecuted.

    Q74.WhatisthedifferencebetweentheBoolean&operatorandthe&&operator?IfanexpressioninvolvingtheBoolean&operatorisevaluated,bothoperandsareevaluated.Thenthe&operatorisappliedtotheoperand.Whenanexpressioninvolvingthe&&operatorisevaluated,thefirstoperandisevaluated.Ifthefirstoperandreturnsavalueoftruethenthesecondoperandisevaluated.The&&operatoristhenappliedtothefirstandsecondoperands.Ifthefirstoperandevaluatestofalse,theevaluationofthesecondoperandisskipped.

    Q75.NamethreesubclassesoftheComponentclass.Box.Filler,Button,Canvas,Checkbox,Choice,Container,Label,List,Scrollbar,orTextComponent.

    Q76.WhatistheGregorianCalendarclass?TheGregorianCalendarprovidessupportfortraditionalWesterncalendars.

    Q77.WhichContainermethodisusedtocauseacontainertobelaidoutandredisplayed?validate()

    Q78.WhatisthepurposeoftheRuntimeclass?ThepurposeoftheRuntimeclassistoprovideaccesstotheJavaruntimesystem.

    Q79.Howmanytimesmayanobject'sfinalize()methodbeinvokedbythegarbagecollector?Anobject'sfinalize()methodmayonlybeinvokedoncebythegarbagecollector.

    Q80.Whatisthepurposeofthefinallyclauseofatrycatchfinallystatement?Thefinallyclauseisusedtoprovidethecapabilitytoexecutecodenomatterwhetherornotanexceptionisthrownorcaught.

    Q81.Whatistheargumenttypeofaprogram'smain()method?Aprogram'smain()methodtakesanargumentoftheString[]type.

  • 6/16/2015 JavaInterviewQuestions

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

    Q82.WhichJavaoperatorisrightassociative?

    The=operatorisrightassociative.

    Q83.WhatistheLocaleclass?TheLocaleclassisusedtotailorprogramoutputtotheconventionsofaparticulargeographic,political,orculturalregion.

    Q84.Canadoublevaluebecasttoabyte?Yes,adoublevaluecanbecasttoabyte.

    Q85.Whatisthedifferencebetweenabreakstatementandacontinuestatement?Abreakstatementresultsintheterminationofthestatementtowhichitapplies(switch,for,do, or while). A continue statement is used to end the current loop iteration and returncontroltotheloopstatement.

    Q86.Whatmustaclassdotoimplementaninterface?Itmustprovideallofthemethodsintheinterfaceandidentifytheinterfaceinitsimplementsclause.

    Q87.Whatmethodisinvokedtocauseanobjecttobeginexecutingasaseparatethread?Thestart()methodoftheThreadclassisinvokedtocauseanobjecttobeginexecutingasaseparatethread.

    Q88.NametwosubclassesoftheTextComponentclass.TextFieldandTextArea

    Q89.Whatistheadvantageoftheeventdelegationmodelovertheearliereventinheritancemodel?Theeventdelegationmodelhastwoadvantagesovertheeventinheritancemodel.First,itenableseventhandlingtobehandledbyobjectsotherthantheonesthatgeneratetheevents(ortheircontainers).Thisallowsacleanseparationbetweenacomponent'sdesignanditsuse.Theotheradvantageoftheeventdelegationmodelisthatitperformsmuchbetterinapplicationswheremanyeventsaregenerated.Thisperformanceimprovementisduetothefactthattheeventdelegationmodeldoesnothavetorepeatedlyprocessunhandledevents,asisthecaseoftheeventinheritancemodel.

    Q90.WhichcontainersmayhaveaMenuBar?Frame

    Q91.Howarecommasusedintheintializationanditerationpartsofaforstatement?Commasareusedtoseparatemultiplestatementswithintheinitialization

    anditerationpartsofaforstatement.

    Q92.Whatisthepurposeofthewait(),notify(),andnotifyAll()methods?Thewait(),notify(),andnotifyAll()methodsareusedtoprovideanefficientwayforthreadstowaitforasharedresource.Whenathreadexecutesanobject'swait()

  • 6/16/2015 JavaInterviewQuestions

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

    method,itentersthewaitingstate.Itonlyentersthereadystateafteranotherthreadinvokestheobject'snotify()ornotifyAll()methods..

    Q93.Whatisanabstractmethod?Anabstractmethodisamethodwhoseimplementationisdeferredtoasubclass.

    Q94.HowareJavasourcecodefilesnamed?AJavasourcecodefiletakesthenameofapublicclassorinterfacethatisdefinedwithinthefile.Asourcecodefilemaycontainatmostonepublicclassorinterface.Ifapublicclassorinterfaceisdefinedwithinasourcecodefile,thenthesourcecodefilemusttakethenameofthepublicclassorinterface.Ifnopublicclassorinterfaceisdefinedwithinasourcecodefile,thenthefilemusttakeonanamethatisdifferentthanitsclassesandinterfaces.Sourcecodefilesusethe.javaextension.

    Q95.WhatistherelationshipbetweentheCanvasclassandtheGraphicsclass?ACanvasobjectprovidesaccesstoaGraphicsobjectviaitspaint()method.

    Q96.Whatarethehighlevelthreadstates?Thehighlevelthreadstatesareready,running,waiting,anddead.

    Q97.Whatvaluedoesread()returnwhenithasreachedtheendofafile?Theread()methodreturns1whenithasreachedtheendofafile.

    Q98.CanaByteobjectbecasttoadoublevalue?No,anobjectcannotbecasttoaprimitivevalue.

    Q99.Whatisthedifferencebetweenastaticandanonstaticinnerclass?Anonstaticinnerclassmayhaveobjectinstancesthatareassociatedwithinstancesoftheclass'souterclass.Astaticinnerclassdoesnothaveanyobjectinstances.

    Q100.WhatisthedifferencebetweentheStringandStringBufferclasses?Stringobjectsareconstants.StringBufferobjectsarenot.

    Q101.Ifavariableisdeclaredasprivate,wheremaythevariablebeaccessed?Aprivatevariablemayonlybeaccessedwithintheclassinwhichitisdeclared.

    Q102.Whatisanobject'slockandwhichobject'shavelocks?Anobject's lock is amechanism that is usedbymultiple threads to obtain synchronizedaccesstotheobject.Athreadmayexecuteasynchronizedmethodofanobjectonlyafterithasacquiredtheobject'slock.Allobjectsandclasseshavelocks.Aclass'slockisacquiredontheclass'sClassobject.

    Q103.WhatistheDictionaryclass?TheDictionaryclassprovidesthecapabilitytostorekeyvaluepairs.

    Q104.HowaretheelementsofaBorderLayoutorganized?TheelementsofaBorderLayoutareorganizedattheborders(North,South,East,andWest)andthecenterofacontainer.

  • 6/16/2015 JavaInterviewQuestions

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

    Q105.Whatisthe%operator?Itisreferredtoasthemoduloorremainderoperator.Itreturnstheremainderofdividingthefirstoperandbythesecondoperand.

    Q106.Whencananobjectreferencebecasttoaninterfacereference?Anobjectreferencebecasttoaninterfacereferencewhentheobjectimplementsthereferencedinterface.Q107.WhatisthedifferencebetweenaWindowandaFrame?TheFrameclassextendsWindowtodefineamainapplicationwindowthatcanhaveamenubar.

    Q108.Whichclassisextendedbyallotherclasses?TheObjectclassisextendedbyallotherclasses.

    Q109.Cananobjectbegarbagecollectedwhileitisstillreachable?Areachableobjectcannotbegarbagecollected.Onlyunreachableobjectsmaybegarbagecollected..

    Q110.Istheternaryoperatorwrittenx:y?zorx?y:z?Itiswrittenx?y:z.

    Q111.WhatisthedifferencebetweentheFontandFontMetricsclasses?TheFontMetricsclassisusedtodefineimplementationspecificproperties,suchasascentanddescent,ofaFontobject.

    Q112.Howisroundingperformedunderintegerdivision?Thefractionalpartoftheresultistruncated.Thisisknownasroundingtowardzero.

    Q113.Whathappenswhenathreadcannotacquirealockonanobject?Ifathreadattemptstoexecuteasynchronizedmethodorsynchronizedstatementandisunable to acquire an object's lock, it enters the waiting state until the lock becomesavailable.

    Q114.WhatisthedifferencebetweentheReader/WriterclasshierarchyandtheInputStream/OutputStreamclasshierarchy?TheReader/Writerclasshierarchyischaracteroriented,andtheInputStream/OutputStreamclasshierarchyisbyteoriented.

    Q115.Whatclassesofexceptionsmaybecaughtbyacatchclause?AcatchclausecancatchanyexceptionthatmaybeassignedtotheThrowabletype.ThisincludestheErrorandExceptiontypes.

    Q116.Ifaclassisdeclaredwithoutanyaccessmodifiers,wheremaytheclassbeaccessed?Aclassthatisdeclaredwithoutanyaccessmodifiersissaidtohavepackageaccess.Thismeansthattheclasscanonlybeaccessedbyotherclassesandinterfacesthataredefinedwithinthesamepackage.

    Q117.WhatistheSimpleTimeZoneclass?TheSimpleTimeZoneclassprovidessupportforaGregoriancalendar.

    Q118.WhatistheMapinterface?TheMapinterfacereplacestheJDK1.1Dictionaryclassandisusedassociatekeyswithvalues.

  • 6/16/2015 JavaInterviewQuestions

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

    Q119.Doesaclassinherittheconstructorsofitssuperclass?Aclassdoesnotinheritconstructorsfromanyofitssuperclasses.

    Q120.Forwhichstatementsdoesitmakesensetousealabel?Theonlystatementsforwhichitmakessensetousealabelarethosestatementsthatcanencloseabreakorcontinuestatement.

    Q121.WhatisthepurposeoftheSystemclass?

    ThepurposeoftheSystemclassistoprovideaccesstosystemresources.

    Q122.WhichTextComponentmethodisusedtosetaTextComponenttothereadonlystate?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,itsetstheclippingregionstotheareaofthewindowthatrequiresrepainting.

    Q128.Is"abc"aprimitivevalue?TheStringliteral"abc"isnotaprimitivevalue.ItisaStringobject.

    Q129.Whatistherelationshipbetweenaneventlistenerinterfaceandaneventadapterclass?Aneventlistenerinterfacedefinesthemethodsthatmustbeimplementedbyaneventhandlerforaparticularkindofevent.Aneventadapterprovidesadefaultimplementationofaneventlistenerinterface.

    Q130.Whatrestrictionsareplacedonthevaluesofeachcaseofaswitchstatement?Duringcompilation,thevaluesofeachcaseofaswitchstatementmustevaluatetoavaluethatcanbepromotedtoanintvalue.

    Q131.Whatmodifiersmaybeusedwithaninterfacedeclaration?Aninterfacemaybedeclaredaspublicorabstract.

    Q132.Isaclassasubclassofitself?Aclassisasubclassofitself.

    Q133.Whatisthehighestleveleventclassoftheeventdelegationmodel?

    Thejava.util.EventObjectclassisthehighestlevelclassintheeventdelegationclasshierarchy.

  • 6/16/2015 JavaInterviewQuestions

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

    Q134.Whateventresultsfromtheclickingofabutton?TheActionEventeventisgeneratedastheresultoftheclickingofabutton.

    Q135.HowcanaGUIcomponenthandleitsownevents?Acomponentcanhandleitsowneventsbyimplementingtherequiredeventlistenerinterfaceandaddingitselfasitsowneventlistener.

    Q136.Whatisthedifferencebetweenawhilestatementandadostatement?A while statement checks at the beginning of a loop to see whether the next loopiterationshouldoccur.Adostatementchecksat theendofa loop toseewhether thenextiterationofaloopshouldoccur.Thedostatementwillalwaysexecutethebodyofaloopatleastonce.

    Q137.HowaretheelementsofaGridBagLayoutorganized?TheelementsofaGridBagLayoutareorganizedaccordingtoagrid.However,theelementsareofdifferentsizesandmayoccupymorethanoneroworcolumnofthegrid.Inaddition,therowsandcolumnsmayhavedifferentsizes.

    Q138.WhatadvantagedoJava'slayoutmanagersprovideovertraditionalwindowingsystems?Java uses layout managers to lay out components in a consistent manner across allwindowing platforms. Since Java's layout managers aren't tied to absolute sizing andpositioning, they are able to accomodate platformspecific differences amongwindowingsystems.

    Q139.WhatistheCollectioninterface?TheCollectioninterfaceprovidessupportfortheimplementationofamathematicalbaganunorderedcollectionofobjectsthatmaycontainduplicates.

    Q140.Whatmodifierscanbeusedwithalocalinnerclass?Alocalinnerclassmaybefinalorabstract.

    Q141.Whatisthedifferencebetweenstaticandnonstaticvariables?Astaticvariableisassociatedwiththeclassasawholeratherthanwithspecificinstancesofaclass.Nonstaticvariablestakeonuniquevalueswitheachobjectinstance.

    Q142.Whatisthedifferencebetweenthepaint()andrepaint()methods?Thepaint()methodsupportspaintingviaaGraphicsobject.Therepaint()methodisusedtocausepaint()tobeinvokedbytheAWTpaintingthread.

    Q143.WhatisthepurposeoftheFileclass?TheFileclassisusedtocreateobjectsthatprovideaccesstothefilesanddirectoriesofalocalfilesystem.

    Q144.Cananexceptionberethrown?Yes,anexceptioncanberethrown.

    Q145.WhichMathmethodisusedtocalculatetheabsolutevalueofanumber?Theabs()methodisusedtocalculateabsolutevalues.

  • 6/16/2015 JavaInterviewQuestions

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

    Q146.HowdoesmultithreadingtakeplaceonacomputerwithasingleCPU?Theoperatingsystem'staskschedulerallocatesexecutiontimetomultipletasks.Byquicklyswitchingbetweenexecutingtasks,itcreatestheimpressionthattasksexecutesequentially.

    Q147.Whendoesthecompilersupplyadefaultconstructorforaclass?Thecompilersuppliesadefaultconstructorforaclassifnootherconstructorsareprovided.

    Q148.Whenisthefinallyclauseofatrycatchfinallystatementexecuted?Thefinallyclauseofthetrycatchfinallystatementisalwaysexecutedunlessthethreadofexecutionterminatesoranexceptionoccurswithintheexecutionofthefinallyclause.

    Q149.WhichclassistheimmediatesuperclassoftheContainerclass?Component

    Q150.Ifamethodisdeclaredasprotected,wheremaythemethodbeaccessed?Aprotectedmethodmayonlybeaccessedbyclassesorinterfacesofthesamepackageorbysubclassesoftheclassinwhichitisdeclared.

    Q151.HowcantheCheckboxclassbeusedtocreatearadiobutton?ByassociatingCheckboxobjectswithaCheckboxGroup.

    Q152.WhichnonUnicodelettercharactersmaybeusedasthefirstcharacterofanidentifier?ThenonUnicodelettercharacters$and_mayappearasthefirstcharacterofanidentifier

    Q153.Whatrestrictionsareplacedonmethodoverloading?Twomethodsmaynothavethesamenameandargumentlistbutdifferentreturntypes.

    Q154.Whathappenswhenyouinvokeathread'sinterruptmethodwhileitissleepingorwaiting?Whenatask'sinterrupt()methodisexecuted,thetaskentersthereadystate.Thenexttimethetaskenterstherunningstate,anInterruptedExceptionisthrown.

    Q155.Whatiscasting?Therearetwotypesofcasting,castingbetweenprimitivenumerictypesandcastingbetweenobjectreferences.Castingbetweennumerictypesisusedtoconvertlargervalues,suchasdoublevalues,tosmallervalues,suchasbytevalues.Castingbetweenobjectreferencesisusedtorefertoanobjectbyacompatibleclass,interface,orarraytypereference.

    Q156.Whatisthereturntypeofaprogram'smain()method?Aprogram'smain()methodhasavoidreturntype.

    Q157.NamefourContainerclasses.Window,Frame,Dialog,FileDialog,Panel,Applet,orScrollPane

    Q158.WhatisthedifferencebetweenaChoiceandaList?

  • 6/16/2015 JavaInterviewQuestions

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

    AChoiceisdisplayedinacompactformthatrequiresyoutopullitdowntoseethelistofavailablechoices.OnlyoneitemmaybeselectedfromaChoice.AListmaybedisplayedinsuchawaythatseveralListitemsarevisible.AListsupportstheselectionofoneormoreListitems.

    Q159.WhatclassofexceptionsaregeneratedbytheJavaruntimesystem?

    TheJavaruntimesystemgeneratesRuntimeExceptionandErrorexceptions.

    Q160.Whatclassallowsyoutoreadobjectsdirectlyfromastream?TheObjectInputStreamclasssupportsthereadingofobjectsfrominputstreams.

    Q161.Whatisthedifferencebetweenafieldvariableandalocalvariable?Afieldvariableisavariablethatisdeclaredasamemberofaclass.Alocalvariableisavariablethatisdeclaredlocaltoamethod.

    Q162.Underwhatconditionsisanobject'sfinalize()methodinvokedbythegarbagecollector?Thegarbagecollectorinvokesanobject'sfinalize()methodwhenitdetectsthattheobjecthasbecomeunreachable.

    Q163.Howarethis()andsuper()usedwithconstructors?

    this()isusedtoinvokeaconstructorofthesameclass.super()isusedtoinvokeasuperclassconstructor.

    Q164.Whatistherelationshipbetweenamethod'sthrowsclauseandtheexceptionsthatcanbethrownduringthemethod'sexecution?

    Amethod'sthrowsclausemustdeclareanycheckedexceptionsthatarenotcaughtwithinthebodyofthemethod.

    Q165.WhatisthedifferencebetweentheJDK1.02eventmodelandtheeventdelegationmodelintroducedwithJDK1.1?

    TheJDK1.02eventmodelusesaneventinheritanceorbubblingapproach.Inthismodel,componentsarerequiredtohandletheirownevents.Iftheydonothandleaparticularevent,theeventisinheritedby(orbubbledupto)thecomponent'scontainer.Thecontainertheneitherhandlestheeventoritisbubbleduptoitscontainerandsoon,untilthehighestlevelcontainerhasbeentried..Intheeventdelegationmodel,specificobjectsaredesignatedaseventhandlersforGUIcomponents.Theseobjectsimplementeventlistenerinterfaces.Theeventdelegationmodelismoreefficientthantheeventinheritancemodelbecauseiteliminatestheprocessingrequiredtosupportthebubblingofunhandledevents.

    Q166.HowisitpossiblefortwoStringobjectswithidenticalvaluesnottobeequalunderthe==operator?The==operatorcomparestwoobjectstodetermineiftheyarethesameobjectinmemory.Itis

  • 6/16/2015 JavaInterviewQuestions

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

    possiblefortwoStringobjectstohavethesamevalue,butlocatedindifferentareasofmemory.

    Q167.WhyarethemethodsoftheMathclassstatic?Sotheycanbeinvokedasiftheyareamathematicalcodelibrary.

    Q168.WhatCheckboxmethodallowsyoutotellifaCheckboxischecked?getState()Q169.Whatstateisathreadinwhenitisexecuting?Anexecutingthreadisintherunningstate.

    Q170.Whatarethelegaloperandsoftheinstanceofoperator?Theleftoperandisanobjectreferenceornullvalueandtherightoperandisaclass,interface,orarraytype.

    Q171.HowaretheelementsofaGridLayoutorganized?TheelementsofaGridBadlayoutareofequalsizeandarelaidoutusingthesquaresofagrid.

    Q172.WhatanI/Ofilter?AnI/Ofilterisanobjectthatreadsfromonestreamandwritestoanother,usuallyalteringthedatainsomewayasitispassedfromonestreamtoanother.

    Q173.Ifanobjectisgarbagecollected,canitbecomereachableagain?Onceanobjectisgarbagecollected,itceasestoexist.Itcannolongerbecomereachableagain.

    Q174.WhatistheSetinterface?TheSetinterfaceprovidesmethodsforaccessingtheelementsofafinitemathematicalset.Setsdonotallowduplicateelements.

    Q175.Whatclassesofexceptionsmaybethrownbyathrowstatement?AthrowstatementmaythrowanyexpressionthatmaybeassignedtotheThrowabletype.

    Q176.WhatareEandPI?EisthebaseofthenaturallogarithmandPIismathematicalvaluepi.

    Q177.Aretrueandfalsekeywords?Thevaluestrueandfalsearenotkeywords.

    Q178.Whatisavoidreturntype?Avoidreturntypeindicatesthatamethoddoesnotreturnavalue.

    Q179.WhatisthepurposeoftheenableEvents()method?TheenableEvents()methodisusedtoenableaneventforaparticularobject.Normally,aneventisenabledwhenalistenerisaddedtoanobjectforaparticularevent.TheenableEvents()methodisusedbyobjectsthathandleeventsbyoverridingtheireventdispatchmethods.

    Q180.WhatisthedifferencebetweentheFileandRandomAccessFileclasses?TheFileclassencapsulatesthefilesanddirectoriesofthelocalfilesystem.TheRandomAccessFileclassprovidesthemethodsneededtodirectlyaccessdatacontainedinanypartofafile.

  • 6/16/2015 JavaInterviewQuestions

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

    Q181.WhathappenswhenyouaddadoublevaluetoaString?TheresultisaStringobject.

    Q182.Whatisyourplatform'sdefaultcharacterencoding?IfyouarerunningJavaonEnglishWindowsplatforms,itisprobablyCp1252.IfyouarerunningJavaonEnglishSolarisplatforms,itismostlikely8859_1..

    Q183.Whichpackageisalwaysimportedbydefault?Thejava.langpackageisalwaysimportedbydefault.

    Q184.Whatinterfacemustanobjectimplementbeforeitcanbewrittentoastreamasanobject?AnobjectmustimplementtheSerializableorExternalizableinterfacebeforeitcanbewrittentoastreamasanobject.

    Q185.Howarethisandsuperused?thisisusedtorefertothecurrentobjectinstance.superisusedtorefertothevariablesandmethodsofthesuperclassofthecurrentobjectinstance.

    Q186.Whatisthepurposeofgarbagecollection?Thepurposeofgarbagecollectionistoidentifyanddiscardobjectsthatarenolongerneededbyaprogramsothattheirresourcesmaybereclaimedandreused.

    Q187.Whatisacompilationunit?AcompilationunitisaJavasourcecodefile.

    Q188.WhatinterfaceisextendedbyAWTeventlisteners?AllAWTeventlistenersextendthejava.util.EventListenerinterface.

    Q189.Whatrestrictionsareplacedonmethodoverriding?Overriddenmethodsmusthavethesamename,argumentlist,andreturntype.Theoverridingmethodmaynotlimittheaccessofthemethoditoverrides. Theoverridingmethodmaynot throwanyexceptions thatmaynot be thrownby theoverriddenmethod.

    Q190.Howcanadeadthreadberestarted?Adeadthreadcannotberestarted.

    Q191.Whathappensifanexceptionisnotcaught?AnuncaughtexceptionresultsintheuncaughtException()methodofthethread'sThreadGroupbeinginvoked,whicheventuallyresultsintheterminationoftheprograminwhichitisthrown.

    Q192.Whatisalayoutmanager?Alayoutmanagerisanobjectthatisusedtoorganizecomponentsinacontainer.

    Q193.WhicharithmeticoperationscanresultinthethrowingofanArithmeticException?Integer/and%canresultinthethrowingofanArithmeticException.

  • 6/16/2015 JavaInterviewQuestions

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

    Q194.Whatarethreewaysinwhichathreadcanenterthewaitingstate?Athreadcanenterthewaitingstatebyinvokingitssleep()method,byblockingonI/O,byunsuccessfully attempting to acquire an object's lock, or by invoking an object's wait()method.Itcanalsoenterthewaitingstatebyinvokingits(deprecated)suspend()method.

    Q195.Cananabstractclassbefinal?Anabstractclassmaynotbedeclaredasfinal.

    Q196.WhatistheResourceBundleclass?TheResourceBundleclassisusedtostorelocalespecificresourcesthatcanbeloadedbyaprogramtotailortheprogram'sappearancetotheparticularlocaleinwhichitisbeingrun.

    Q197.Whathappensifatrycatchfinallystatementdoesnothaveacatchclausetohandleanexceptionthatisthrownwithinthebodyofthetrystatement?Theexceptionpropagatesuptothenexthigherleveltrycatchstatement(ifany)orresultsintheprogram'stermination.

    Q198.Whatisnumericpromotion?Numericpromotionistheconversionofasmallernumerictypetoalargernumerictype,sothatintegerandfloatingpointoperationsmaytakeplace.Innumericalpromotion,byte,char,andshortvaluesareconvertedtointvalues.Theintvaluesarealsoconvertedtolongvalues,ifnecessary.Thelongandfloatvaluesareconvertedtodoublevalues,asrequired.

    Q199.WhatisthedifferencebetweenaScrollbarandaScrollPane?AScrollbarisaComponent,butnotaContainer.AScrollPaneisaContainer.AScrollPanehandlesitsowneventsandperformsitsownscrolling.

    Q200.Whatisthedifferencebetweenapublicandanonpublicclass?Apublicclassmaybeaccessedoutsideofitspackage.Anonpublicclassmaynotbeaccessedoutsideofitspackage.

    Q201.Towhatvalueisavariableofthebooleantypeautomaticallyinitialized?Thedefaultvalueofthebooleantypeisfalse.

    Q202.Cantrystatementsbenested?Trystatementsmaybetested.

    Q203.Whatisthedifferencebetweentheprefixandpostfixformsofthe++operator?Theprefixformperformstheincrementoperationandreturnsthevalueoftheincrementoperation.Thepostfixformreturnsthecurrentvaluealloftheexpressionandthenperformstheincrementoperationonthatvalue.

    Q204.Whatisthepurposeofastatementblock?Astatementblockisusedtoorganizeasequenceofstatementsasasinglestatementgroup.

    Q205.WhatisaJavapackageandhowisitused?AJavapackageisanamingcontextforclassesandinterfaces.Apackageisusedtocreatea

  • 6/16/2015 JavaInterviewQuestions

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

    separatenamespaceforgroupsofclassesandinterfaces.PackagesarealsousedtoorganizerelatedclassesandinterfacesintoasingleAPIunitandtocontrolaccessibilitytotheseclassesandinterfaces.

    Q206.Whatmodifiersmaybeusedwithatoplevelclass?Atoplevelclassmaybepublic,abstract,orfinal.

    Q207.WhataretheObjectandClassclassesusedfor?TheObjectclassisthehighestlevelclassintheJavaclasshierarchy.TheClassclassisusedtorepresenttheclassesandinterfacesthatareloadedbyaJavaprogram..

    Q208.Howdoesatrystatementdeterminewhichcatchclauseshouldbeusedtohandleanexception?Whenanexceptionisthrownwithinthebodyofatrystatement,thecatchclausesofthetrystatementareexaminedintheorderinwhichtheyappear.Thefirstcatchclausethatiscapableofhandlingtheexceptionisexecuted.Theremainingcatchclausesareignored.

    Q209.Cananunreachableobjectbecomereachableagain?Anunreachableobjectmaybecomereachableagain.Thiscanhappenwhentheobject'sfinalize()methodisinvokedandtheobjectperformsanoperationwhichcausesittobecomeaccessibletoreachableobjects.

    Q210.Whenisanobjectsubjecttogarbagecollection?Anobjectissubjecttogarbagecollectionwhenitbecomesunreachabletotheprograminwhichitisused.

    Q211.Whatmethodmustbeimplementedbyallthreads?Alltasksmustimplementtherun()method,whethertheyareasubclassofThreadorimplementtheRunnableinterface.

    Q212.WhatmethodsareusedtogetandsetthetextlabeldisplayedbyaButtonobject?getLabel()andsetLabel()

    Q213.WhichComponentsubclassisusedfordrawingandpainting?Canvas

    Q214.Whataresynchronizedmethodsandsynchronizedstatements?

    Synchronizedmethodsaremethodsthatareusedtocontrolaccesstoanobject.Athreadonlyexecutesasynchronizedmethodafterithasacquiredthelockforthemethod'sobjectorclass.Synchronizedstatementsaresimilartosynchronizedmethods.Asynchronizedstatementcanonlybeexecutedafterathreadhasacquiredthelockfortheobjectorclassreferencedinthesynchronizedstatement.

    Q215.Whatarethetwobasicwaysinwhichclassesthatcanberunasthreadsmaybedefined?AthreadclassmaybedeclaredasasubclassofThread,oritmayimplementtheRunnableinterface.

    Q216.WhataretheproblemsfacedbyJavaprogrammerswhodon'tuselayoutmanagers?Withoutlayoutmanagers,JavaprogrammersarefacedwithdetermininghowtheirGUIwillbedisplayedacrossmultiplewindowingsystemsandfindingacommonsizingand

  • 6/16/2015 JavaInterviewQuestions

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

    positioningthatwillworkwithintheconstraintsimposedbyeachwindowingsystem.

    Q217.Whatisthedifferencebetweenanifstatementandaswitchstatement?

    Theifstatementisusedtoselectamongtwoalternatives.Itusesabooleanexpressiontodecidewhichalternativeshouldbeexecuted.Theswitchstatementisusedtoselectamongmultiplealternatives.Itusesanintexpressiontodeterminewhichalternativeshouldbeexecuted.

    Q218.WhathappenswhenyouaddadoublevaluetoaString?TheresultisaStringobject.

    Q219.WhatistheListinterface?TheListinterfaceprovidessupportfororderedcollectionsofobjects

    Q220.WhatisanException?Ans.Anunwanted,unexpectedeventthatdisturbsnormalflowoftheprogramiscalledException.Example:FileNotFondException.

    Q221.WhatisthepurposeofExceptionHandling?Ans.ThemainpurposeofExceptionHandlingisforgracefulterminationoftheprogram.

    Q222.WhatisthemeaningofExceptionHandling?Ans.ExceptionHandlingdoesntmeanrepairinganException,wehavetodefinealternativewaytocontinuerestofthecodenormally.Example:IfourprogrammingrequirementistoreadthedatafromthefilelocatingatLondonbutatRuntimeifLondonfileisnotavailablethenwehavetouselocalfilealternativelytocontinuerestofprogramnormally.ThisisnothingbutExceptionHandling.

    Q223.ExplainDefaultExceptionHandlingMechanisminjava?

    Ans.Ifanexceptionraised,themethodinwhichitsraisedisresponsibleforthecreationofExceptionsobjectbyincludingthefollowinginformation:NameoftheExceptionDescriptionoftheExceptionStackTraceAftercreatingExceptionobjectthemethodhandoverittotheJVM.JVMchecksforExceptionHandlingcodeinthatmethod.IfthemethoddoesntcontainanyExceptionhandlingcodethenJVMterminatesthemethodabnormallyandremovesthecorrespondingentryfromthestack.JVMidentifythecallermethodandchecksforExceptionHandlingcodeinthatmethod.IfthecallerdoesntcontainanyexceptionhandlingcodethenJVMterminatesthatmethodabnormallyandremovesthecorrespondingentryfromthestack.Thisprocesswillbecontinueuntilmain()method.Ifthemain()methodalsodoesntcontainexceptionhandlingcodetheJVMterminatesthatmain()methodandremovesthecorrespondingentryfromthestack.JustbeforeterminatingtheprogramabnormallyJVMhandoverstheresponsibilityofexceptionhandlingtotheDefaultExceptionHandlerwhichisthecomponentofJVM.DefaultExceptionHandlerjustprintexceptioninformationtotheconsolinthefollowingformat

    NameofException:DescriptionStackTrace(LocationoftheException)

    Q224.Whatisthepurposeoftry?AnsWeshouldmaintainallriskycodeinsidethetryblock.

  • 6/16/2015 JavaInterviewQuestions

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

    Q225.Whatisthepurposeofcatchblock?Ans.WehavetomaintainallExceptionHandlingcodeinsidethecatchblock.

    Q226.Istrywithmultiplecatchblockispossible?Ans.Thewayofhandlinganexceptionisvariedfromexceptiontoexceptioncompulsorywehavetowriteaseparatecatchblockforeveryexception.Hencetrywillmultiplecatchblockispossibleanditisrecommendedtouse.Example:try{//Riskycode}catch(IOExceptione){//HndlingcodeforIOException

    }catch(ArithmeticExceptione){//handlingcodeforAE}catch(NullPointerExcetpione){//handlingcodeforNPE}catch(Exceptione){//defaultexceptionhandlingcode}

    Q227.Iftrywithmultiplecatchblockpresentisorderofcatchblocksimportantinwhichorderwehavetotake?Ans.Iftrywithmultiplecatchblockpresentthentheorderofcatchblockisveryimportantitshouldbefromchildtoparentbutnotfromparenttochild.

    Q228.WhatarevariousmethodstoprintExceptioninformation?anddifferentiatethem.Ans.Throwableclassdefinesthefollowingmethodtoprintexceptionorerrorinformation.1.printStackTrace():Thismethodprintexceptioninformationinthefollowingformat.NameoftheException:DescriptionStackTrace2.toString():Thismethodprintexceptioninformationinthefollowingformat.NameoftheException:Description3.getMessage():Thismethodprintsonlydescriptionoftheexception.Description

    Q229.Ifanexceptionrisedinsidecatchblockthenwhatwillhappen?Ans.Ifanexceptionraisedinsidecatchblockanditisnotpartofanytryblockthenitisalwaysabnormaltermination.

    Q230.Isitpossibletotaketry,catchinsidetryblock?Ans.Yes,Itispossibletotaketry,catchinsidetryblock.Thatisnestingoftrycatchispossible.

  • 6/16/2015 JavaInterviewQuestions

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

    Q231.Isitpossibletotaketry,catchinsidecatchblock?Ans.Yes,Itispossibletotaketry,catchinsidecatchblock.

    Q232.Isitpossibletotaketrywithoutcatch?Ans.Yes,itispossibletotaketrywithoutcatchbutcompulsoryfinallyblockshouldbeavailable.

    Q233.Whatisthepurposeoffinallyblock?Ans.Themainpurposeoffinallyblockis,tomaintainthecleanupcode.Thisblockwillexecutealways.

    Q234.Isfinallyblockwillbeexecutealways?Ans.Yesfinallyblockwillbeexecutedalwaysirrespectiveofwhetherexceptionraisedornotraisedwhetherexceptionsarehandledornothandle.ThereisonesituationwherethefinallyblockwontbeexecutediftheJVMisgoingtobeshutdown.

    Q235.Inwhichsituationfinallyblockwillnotexecuted?Ans.Thereisonesituationwherethefinallyblockwontbeexecutedifweareusingsystem.exit(0)explicitlythenJVMitselfwillbeshutdownandthereisnochanceofexecutingfinallyblock.

    Q236.Ifreturnstatementpresentinsidetryisfinallyblockwillbeexecuted?Ans.Yes,ifreturnstatementpresentinsidetry,thenalsofinallyblockwillbeexecuted.finallyblockwilldominatereturnstatementalso.

    Q237.Whatisthedifferencebetweenfinal,finallyandfinalize()?Ans.final:finalisamodifierapplicableforvariables,methodsandclasses.finalvariablemeansconstantandreassignment isnotpossible.finalmethodmeansimplementationis final in the child classeswe cant override. final classmeans itwont participate ininheritanceandchildclasscreationisnotpossible.finally:Itisablockassociatedwithtrycatchtomaintaincleanupcode.Finallyblockwillbeexecutedalwaysirrespectiveofwhetherexceptionisraisedornotraisedorwhethertheexceptionishandleornothandle.finalize():Itisamethod,Garbagecollectoralwayscallsthismethodjustbeforedestroyinganyobjecttoperformcleanupactivities.

    Q238.Isitpossibletowriteanystatementbetweentrycatchandfinally?Ans.No,itisnotpossibletowriteanystatementbetweentrycatchandfinally.Ifwewilltrytowriteanystatementbetweenthemthenwewillgetcompiletimeerror.

    Q239.Isitpossibletotaketwofinallyblocksforthesametry?Ans.No,itisnotpossibletotaketwofinallyblocksforthesametry.Ifwetrytotakethenwewillgetcompiletimeerror.

    Q240.Issyntaxtryfinallycatchisvalid?Ans.No,thissyntaxisnotvalid.Itshouldbeliketrycatchfinallythenonlycodewillcompile.

    Q241.Whatisthepurposeofthrow?Ans.SometimeswecancreateExceptionobjectexplicitlyandwecanhandoverthatexceptionobjecttotheJVMexplicitlybythrowkeyword.Thepurposeofthrowkeywordistohandoverourcreatedexceptionobjectexplicitlytothe

  • 6/16/2015 JavaInterviewQuestions

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

    JVM.Example1:classTest{publicstaticvoidmain(String[]args){System.out.println(10/0)}}InthiscaseArithmeticExceptionobjectcreatedimplicitlyandhandovertotheJVMautomaticallybythemainmethod.Example2:classTest{Publicstaticvoidmain(String[]args){ThrownewArithmeticException(/byZero)}}InthiscasecreationofanexceptionobjectandhandovertotheJVMexplicitlybytheprogrammer.

    Q242.IsitpossibletothrowanError?Ans.Yes,ItispossibletothrowanyThrowabletypeincludingError.

    Q243.Isitpossibletothrowanyjavaobject?Ans.No,wecanusethrowkeywordonlyforthrowableobjectsotherwisewewillgetcompiletimeerrorsayingincompatibletype.*CoreJava*Servlets&JSP*Struts*EJB*J2ME

    Q244.Afterthrowisitallowtotakeanystatementdirectly?

    Ans.AfterthrowstatementwearenotallowtoplaceanystatementdirectlyviolationleadstocompiletimeerrorsayingUnreachableStatement.

    Q245.Whatisthepurposeofthrows?Ans.Themainpurposeofthrowskeywordistodelegatetheresponsibilitiesofexceptionhandlingtothecaller.Itrequiresinthecaseofcheckedexception.

    Q246.Whatisthedifferencebetweenthrowandthrows?Ans.SometimeswecancreateExceptionobjectexplicitlyandwecanhandoverthatexceptionobjecttotheJVMexplicitlybythrowkeyword.ThemainpurposeofthrowkeywordistohandoverourcreatedexceptionobjectexplicitlytotheJVM.Themainpurposeofthrowskeywordistodelegatetheresponsibilitiesofexceptionhandlingtothecaller.Itrequiresinthecaseofcheckedexception.

    Q47.Whatisthedifferencebetweenthrowandthrown?Ans.Thereisnoterminologyofthrowninjava.

    Q248.Isitpossibletousethrowskeywordforanyjavaclass?Ans.No,wecanusethrowskeywordonlyforThrowableclasses.OtherwisewewillgetcompiletimeerrorsayingIncompatibletypes.

  • 6/16/2015 JavaInterviewQuestions

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

    Q249.Ifwearetakingcatchblockforanexceptionbutthereisnochanceofrisingthatexceptionintrythenwhatwillhappen?

    Ans. If there isnochanceof raisinganexception in try thenwearenotallow towritecatchblockforthatexceptionviolationleadstocompiletimeerror.Butthisruleisapplicableonlyforfullycheckedexception.

    Q250.ExplainExceptionHandlingkeyword?Ans.ExceptionHandlingkeyword:Try:TomaintainRiskycode.Catch:TomaintainExceptionHandlingcode.Finally:Tomaintainthecleanupcode.Throw: To handover our created exception object to the JVM explicitly. Throws: TodelegatetheresponsibilitiesofExceptionHandlingtothecaller.

    Q251.WhichclassactasrootforentirejavaExceptionhierarchy?Ans.ThrowableclassactasrootforentirejavaExceptionhierarchy.

    Q252.WhatisthedifferencebetweenErrorandException?Ans.Throwableclasscontaintwochildclasses.Exception:Thesearemostlycausedbyourprogramandarerecoverable.

    Error: These are not caused by our program, mostly caused by lake of systemresources.Thesearenonrecoverable.

    Q253. What is difference between checked exception and uncheckedexception?Ans.Theexceptionswhichare checkedby the compiler for smoothexecutionofthe program at Runtime is called checked exception. Example: IOException,InterruptedException.Theexceptions which are not checked by the compiler are called unchecked exception.Example:ArithmeticException,RuntimeException.

    Q254.WhatisdifferencebetweenpartiallycheckedandfullycheckedException?Ans.Acheckedexceptionissaidtobefullycheckedifandonlyifallthechildclassesalsocheckedotherwiseitiscalledpartiallycheckedexception.Example:IOException: fully checked exception Exception:partially checked exception Throwable: partiallychecked exception RuntimeException: uncheckedexception

    Q255.WhatisacustomizedException?Ans.SometimesbasedonourprogrammingrequirementwehavetocreateourownexceptionsuchtypeofexceptionarecalledcustomizeException.Example:TooYoungExceptionTooOldExceptionInsufficientFundException

    Q256.ExplaintheprocessofcreatingthecustomizedException.Ans.CreatingcustomizedException:ClassTooYoungExceptionextendsRuntimeException{TooYoungExcetpion(Stringdesc){Super(desc)}

  • 6/16/2015 JavaInterviewQuestions

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

    }ClassTooOldExceptionextendsRuntimeException{TooOldException(Stringdesc){super(desc)}}ClasscustExcepiton{Publicstaticvoidmain(String[]args){intage=Integer.parseInt(args[0])if(age>60)

    {ThrownewTooYoungException(Pleasewaitsomemoretime,definitelyyouwillgetbestmatch)}elseif(age

  • 6/16/2015 JavaInterviewQuestions

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

    Ans.NullPointerException,ArrayIndexOutofBoundException,StackOverFlowError,ClassCastException,NoClassDefFoundError,ExceptionInitilizerError,IllegalArgumentException,NumberFormatException,IllegalStateException,AssertionError.

    Q259.WhatisMultitasking?Ans.Executingseveraltasksimultaneouslyiscalledmultitasking.

    Q260.WhatisthedifferencebetweenprocessbasedandThreadbasedMultitasking?Ans.Processbasedmultitasking:Executingseveraltasksimultaneouslywhereeachtaskisaseparate independent process such type of multitasking is called process basedMultitasking.Example:While typing a program in the editor we can listenMP3 audio songs. At thesametimewedownloada file from thenet.all these taskareexecutingsimultaneouslyandeachtaskisaseparateindependentprogram.henceitisprocessbasedmultitasking.Itisbestsuitableatoperatingsystemlevel.Threadbasedmultitasking:ExecutingseveraltasksimultaneouslywhereeachtaskisaseparateindependentpartofthesameprogramiscalledThreadbasedmultitasking.andeveryindependentpartiscalledathread.Thistypeofmultitaskingisbestsuitableatprogrammaticlevel.

    Q261.WhatisMultithreadingandexplainitsapplicationareas?Ans.Executingseveralthreadsimultaneouslywhereeachthreadisaseparateindependentpartofthesameprogramiscalledmultithreading.Javalanguageprovidesinbuiltsupportformultithreadingbydefiningareachlibrary,classesandinterfaceslikeThread,ThreadGroup,Runnableetc.Themainimportantapplicationareaofmultithreadingarevideogamesimplementation,animationdevelopment,multimediagraphicsetc.

    Q262.WhatisadvantageofMultithreadin

    Ans.Themainadvantageofmultithreadingisreducesresponsetimeandimprovesperformanceofthesystem.

    Q263.WhencomparedwithC++whatistheadvantageinjavawithrespecttoMultithreading?Ans.Javalanguageprovidesinbuiltsupportformultithreadingbydefiningareachlibrary,classesandinterfaceslikeThread,ThreadGroup,Runnableetc.Butinc++thereisnoinbuiltsupportformultithreading.

    Q264.InhowmanywayswecandefineaThread?AmongextendingThreadandimplementingRunnablewhichisrecommended?Ans.WecandefineaThreadinthefollowingtwoways:1.byextendingThreadclassor2.byimplementingRunnableinterface.

    AmongthetwowaysofdefiningathreadimplementingRunnablemechanismisalwaysrecommended.InthefirstapproachasourThreadclassalreadyextendingThreadthereisnochanceofextendinganyother.Hence,wemissingthekeybenefitofoops(inheritanceproperties).

    Q265.Whatisthedifferencebetweent.start()andt.run()method?

  • 6/16/2015 JavaInterviewQuestions

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

    Ans.Inthecaseoft.start()method,anewthreadwillbecreatedwhichisresponsiblefortheexecutionofrun()method.Butinthecaseoft.run()methodnonewthreadwillbecreatedmainthreadexecutesrun()methodjustlikeanormalmethodcall.

    Q266.ExplainaboutThreadScheduler?Ans.IfmultiplethreadsarewaitingforgettingthechanceforexecutingthenwhichthreadwillgetchancefirstdecidedbyThreadScheduler.ItisthepartofJVManditsbehaviorisvendordependentandwecantexpectexactoutput.Wheneverthesituationcomestomultithreadingtheguaranteebehaviorisveryverylow.

    Q267.Ifwearenotoverridingrun()methodwhatwillhappened?Ans.Ifwearenotoverridingrun()methodthenThreadclassrun()methodwillexecutedwhichhasemptyimplementationandhencewewillnotgetanyoutput.

    Q268.Isoverloadingofrun()methodispossible?Ans.Yes,wecanoverloadrun()methodbutThreadclassstart()methodalwaysinvokesnoargumentrun()methodonly.Theotherrun()methodwehavetocallexplicitlythenonlywillbeexecuted.

    Q269.Isitpossibletooverridestart()method?Ans.Yesitispossible.Butnotrecommended.

    Q270.Ifweareoverridingstart()methodthenwhatwillhappen?Ans.Itweareoverridingstart()methodthenourownstart()methodwillbeexecutedjustlikeanormalmethodcall.InthiscasenonewThreadwillbecreated.

    Q271.ExplainlifecycleofaThread?Ans.OncewecreateaThreadobjectthentheThreadissaidtobeinNew/Bornstateoncewecallt.start()methodnowtheThreadwillbeenteredintoready/RunnablestatethatisThreadisreadytoexecute.IfThreadSchedulerallocatesCPUnowtheThreadwillenteredintotheRunningstateandstartexecutionofrun()method.Aftercompletingrun()methodtheThreadenteredintoDeadState.

    Q272.WhatistheimportanceofThreadclassstart()method?Ans.Start()methodpresentinThreadclassperformingalllowleveljoiningformalitiesforthenewlycreatedthreadlikeregisteringthreadwithThreadScheduleretcandthenstart()methodinvoking run() method.As the start() method is doing all low level mandatoryactivities,Programmerhas 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.AfterstartingaThreadifwetryingtorestartthesamethreadonceagainwhatwillhappen?

    Ans. After starting a Thread restarting of the same Thread once again is not allowedviolationleadstoRuntimeExceptionsayingIllegalThreadStateException.

    Q274.ExplainThreadclassconstructors?Ans.ThereareeightconstructorsareavailableinThreadclass:

  • 6/16/2015 JavaInterviewQuestions

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

    1.Threadt=newThread()2.Threadt=newThread(Runnabler)3.Threadt=newThread(Stringname)4.Threadt=newThread(Runnabler,Stringname)5.Threadt=newThread(ThreadGroupg,Stringname)6.Threadt=newThread(ThreadGroupg,Runnabler)

    7.Threadt=newThread(ThreadGroupg,Runnabler,Stringname)8.Threadt=newThread(ThreadGroupg,Runnabler,Stringname,longstacksize)

    Q275.HowtogetandsetnameofaThread?Ans.ForeveryThreadinjavathereisaname.TosetandgetthenameofaThreadwecanusethefollowingmethods.Allmethodsarefinal.1.PublicfinalvoidsetName(Stringname)TosetthenameofaThread2.PublicfinalStringgetName()TogetthenameofaThread.

    Q276.WhatistherangeofThreadpriorityinjava?Ans.ThevalidrangeofaThreadpriorityis110.(1isleastpriorityand10ishighestpriority)

    Q277.WhousesThreadpriority?Ans.ThreadSchedulerusesprioritieswhileallocatingCPU.TheThreadwhichishavinghighestprioritywillgetchancefirstforexecution.

    Q278.WhatisthedefaultpriorityoftheThread?Ans.Thedefaultpriorityonlyforthemainthreadis5butforallremainingthreadsdefaultprioritywillbeinheritingfromparenttochild.Whateverpriorityparentthreadhasthesamewillbeinheritedtothechildthread.

    Q279.OncewecreatedanewThreadwhataboutitspriority?Ans.Whateverpriorityparentthreadhasthesamewillbeinheritedtothenewchildthread.

    Q280.HowtogetandsetpriorityofaThread?Ans.TogetandsetpriorityofaThread,Threadclassdefinesthefollowingtwomethods:1. Public final intgetPriority()2.PublicfinalvoidsetPriority(intpriority)

    Q281.IfwearetryingtosetpriorityofaThreadas100whatwillhappen?Ans.IfwearetryingtosetpriorityofaThreadas100thenwewillnotgetanycompiletimeerrorbutattheruntimewewillgetRuntimeexceptionIllegalArgumentException.BecausethevalidrangeoftheThreadpriorityis(110)only.

    Q282.Iftwothreadshavingsameprioritythenwhichthreadwillgetchancefirstforexecution?Ans.IftwothreadshavingsameprioritythenwhichthreadwillgetthechancefirstforexecutiondecidedbyThreadScheduler.Itisthepartof

    JVManditsbehaviorisvendordependentandwecantexpectexactoutput.

    Q283.Iftwothreadshavingdifferentprioritythenwhichthreadwillgetchancefirstforexecution?Ans.IftwothreadshavingdifferentprioritythentheThreadwhichishavinghighestprioritywillgetchancefirstforexecution.

  • 6/16/2015 JavaInterviewQuestions

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

    Q284.Howwecanpreventathreadfromexecution?Ans.WecanpreventaThreadfromexecutinbyusingthefollowingmethods:1.Yield()2.Join()3.Sleep()

    Q285.Whatisyield()method?Explainitspurpose?Ans.yield()methodcausesthecurrentexecutingthreadtopauseexecutionandgivethechanceforwaitingthreadaresamepriority.Ifthereisnowaitingthreadoralltheremainingwaitingthreadhavelowprioritythenthesamethreadwillgetchanceonceagainforexecution.TheThreadwhichisyieldedwhenitwillgetchanceonceagainforexecutiondependsuponmercyofThreadscheduler.Publicstaticnativevoidyield()

    Q286.Whatispurposeofjoin()method?Ans.IfaThreadwantstowaituntilsomeotherThreadcompletionthenweshouldgoforjoin()method.Example:ifaThreadt1executet2.join()thent1willenteredintowaitingstateuntilt2Threadcompletion.

    Q287.Isjoin()methodisoverloaded?Ans.Yesjoin()methodisoverloadedmethod.Publicfinalvoidjoin()throwsInterruptedExceptionByusingthismethodthreadwillwaituptoanotherthreadcompletion.Publicfinalvoidjoin(longms)throwsInterruptedExceptionByusingthismethodthreadwillwailuptosometimewhatwearepassingasaargumentinmillisecondPublic final void join(long ms, int ns)throws InterruptedException By using thismethod threadwill wait up to sometimewhat we are passing as a argument inmillisecondandnanosecond.

    Q288.Whatisthepurposeofsleep()method?Ans.IfaThreaddontwanttoperformanyoperationforaparticularamountoftimethenweshouldgoforsleep()method.Wheneverweare

    usingsleep()methodcompulsoryweshouldhandleInterruptedExceptioneitherbyusingtrycatchorbyusingthrowskeywordotherwisewewillgetcompiletimeerror.

    Q289.Whatissynchronizedkeyword?Explainitsadvantagesanddisadvantages.Ans.Synchronizedkeywordisapplicableformethodandblocksonly.Wecantuseforvariablesandclasses.IfamethoddeclaredasasynchronizedthenatatimeonlyoneThreadisallowtoexecutethatmethodonthegivenobject.Themainadvantagesofsynchronizedkeywordare,wecanpreventdatainconsistencyproblemsandwecanprovideThreadsafty.ButthemainlimitationofsynchronizedkeywordisitincreaseswaitingtimeofThreadsandeffectperformanceofthesystem.Henceifthereisnospecificrequirementitisnotrecommendedtousesynchronizedkeyword.

    Q290.Wherewecanusesynchronizedkeyword?Ans.SynchronizationconceptisapplicablewhenevermultipleThreadsareoperatingonthe

  • 6/16/2015 JavaInterviewQuestions

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

    sameobjectsimultaneously.ButwhenevermultipleThreadsareoperatingondifferentobjectsthenthereisnoimpactofsynchronization.

    Q291.Whatisobjectlock?Explainwhenitisrequired?Ans.Everyobjectinjavahasauniquelockwheneverweareusingsynchronizationconceptthenonlylockconceptwillcomingtothepicture.IfaThreadwantstoexecuteasynchronizedmethodfirstithastogetthelockoftheobject.OnceaThreadgotthelockthenitisallowtoexecuteanysynchronizedmethodonthatobject.AftercompletingsynchronizedmethodexecutionThreadreleasesthelockautomatically.WhileaThreadexecutingsynchronizedmethodonthegivenobjecttheremainingThreadsarenotallowtoexecuteanysynchronizedmethodonthatobjectsimultaneously.ButremainingThreadsareallowtoexecuteanynonsynchronizedmethodsimultaneously.(Lockconceptisimplementedbasedonobjectbutnotbasedonmethod.)

    Q292.Whatistheclasslevellock?Explainitspurpose.Ans.EveryclassinjavahasauniquelockifaThreadwantstoexecutestaticsynchronizedmethodthatThreadhastogetclasslevellockonceaThreadgotclasslevellockthenonlyitisallowtoexecutestaticsynchronizedmethod.WhileaThreadexecutinganystaticsynchronizedmethodthenremainingThreadsarenotallowtoexecuteanystaticsynchronizedmethodofthesameclasssimultaneously.ButtheremainingThreadsareallowtoexecutethefollowingmethodsimultaneously:

    1.Anystaticnonsynchronizedmethod.2.Synchronizedinstancemethods3.Nonsynchronizedinstancemethod.Thereisnorelationshipbetweenobjectlockandclasslevellock,bothareindependent.

    Q293.Whileathreadexecutinganysynchronizedmethodonthegivenobjectisitpossibletoexecuteremainingsynchronizedmethodofthesameobjectsimultaneouslybyanyotherthread?Ans.No,itisnopossible.

    Q294.Whatisthedifferencebetweensynchronizedmethodandstaticsynchronizedmethod?Ans.IfaThreadwantstoexecuteasynchronizedmethodfirstithastogetthelockoftheobject.OnceaThreadgotthelockthenitisallowtoexecuteanysynchronizedmethodonthatobject.IfaThreadwantstoexecutestaticsynchronizedmethodthatThreadhastogetclasslevellockonceaThreadgotclasslevellockthenonlyitisallowtoexecutestaticsynchronizedmethod.

    Q295.Whatistheadvantageofsynchronizedblockoversynchronizedmethod?Ans.Ifveryfewlinesofthecoderequiredsynchronizationthendeclaringentiremethodasthesynchronizedisnotrecommended.Wehavetodeclarethosefewlinesofthecodeinsidesynchronizedblock.ThisapproachreduceswaitingtimeoftheThreadandimprovesperformanceofthesystem.

    Q296.Whatissynchronizedstatement?Ans.TheStatementwhichisinsidethesynchronizedarea(synchronizedmethodorsynchronizedblock)iscalledsynchronizedstatement.

  • 6/16/2015 JavaInterviewQuestions

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

    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()methoddefinesinobjectclassinsteadofThreadclass?Ans.ThesemethodsaredefinedinObjectclassbutnotinThreadbecauseThreadsarecallingthismethodonthesharedobject.

    Q301.Ifawaitingthreadgotnotificationthenitwillenteredintowhichstate?Ans.Itwillenteredintoanotherwaitingstatetogetlock.

    Q302.Inwhichmethodthreadscanreleasethelock?Ans.OnceaThreadcallswait()method it immediately releases the lockof thatobjectandthenenteredintowaitingstatesimilarlyaftercallingnotify()methodThreadreleasesthelockbutmaynotimmediately.Exceptthesethreemethods(wait(),notify(),notifyAll())methodThreadneverreleasesthelockanywhereelse.

    Q303.Explainwait(),notify(),notifyAll()methoduses.Ans.TwoThreadswillcommunicatewitheachotherbyusingwait(),notify()ornotifyAll()methods.ThesemethodsaredefinedinObjectclassbutnotinThreadbecauseThreadsarecallingthismethod.

    Q304.Whatisthedifferencebetweennotify()andnotifyAll()?Ans.Togivenotification to thesinglewaitingThread.Weusenotify()methodand togivenotificationtoallwaitingthreadweusenotifyAll()method.

    Q305.OnceaThreadgotthenotificationthenwhichwaitingthreadwillgetchance?Ans.ItisdependsontheThreadScheduler.

    Q306.Howathreadcaninterruptanotherthread?Ans.AThreadcaninterruptanotherThreadbyusinginterrupt()method.

    Q307.WhichkeywordcausesDeadLocksituation?Ans.SynchronizedkeywordisthethingtocausesofDeadLock.IfwearenotusingproperlysynchronizedkeywordtheprogramwillenteredintoDeadLocksituation.

    Q308.Howwecanstopathreadexplacitly?Ans.Threadclassdefinesstop()methodbyusingthismethodwecanstopaThread.Butitisdeprecated.Andhencenotrecommendedtouse.

  • 6/16/2015 JavaInterviewQuestions

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

    Q309.Explainaboutsuspend()andresume()method?Ans.AThreadcansuspendanotherThreadbyusingsuspend()method.AThreadcanresumeasuspendedThreadbyusingresume()method.

    Q310.WhatisStarvation()?AndExplainthedifferencebetweenDeadlockandStarvation?Ans.AlongwaitingThreadissaidtobeinstarvation(becauseofleastpriority)butaftercertaintimedefiantlyitwillgetthechanceforexecution.ButinthecaseofDeadlocktwoThreadswillwaitforeachotherforever.Itwillnevergetthechanceforexecution.

    Q311.Whatisracecondition?Ans.MultipleThreadsareaccessingsimultaneouslyandcausingdata inconsistencyproblemiscalledracecondition,wecanresolvethisbyusingsynchronizedkeyword.

    Q312.WhatisDaemonThread?Andgiveanexample?Ans.TheThreadswhicharerunninginthebackgroundarecalledDaemonThread.Example:Garbagecollector.

    Q313.WhatisthepurposeofaDaemonThread?Ans.ThemainpurposeofDaemonThreadsistoprovidesupportfornondaemonThreads.

    Q314.HowwecancheckDaemonnatureofaThread?Ans.WecancheckDaemonnatureofaThreadbyusingisDaemon()method.

    Q315.IsitpossibletochangeaDaemonnatureofaThread?Ans.Yes,wecanchangeDaemonnatureofaThreadbyusingsetDaemon()method.

    Q316.IsmainthreadisDaemonornondaemon?Ans.Bydefaultmainthreadisalwaysnondaemonnature.

    Q317.Oncewecreatedanewthreadisitdaemonornondaemon.Ans.OncewecreatedanewThread,TheDaemonnaturewillbeinheritingfromparenttochild.IftheparentisDaemonthechildisalsoDaemonandiftheparentisnondaemonthenchildisalsonondaemon

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

    Q318.AfterstartingathreadisitpossibletochangeDaemonnature?Ans.WecanchangetheDaemonnaturebeforestartingtheThreadonly.OnceThreadstartedwearenotallowtochangeDaemonnatureotherwisewewillgetRuntimeExceptionsyingIllegalThreadStateException.

    Q319.WhentheDaemonthreadwillbeterminated?Ans.OncelastnondaemonThreadterminatesautomaticallyeveryDaemonThreadwillbeterminated.

    Q320.WhatisgreenThread?Ans.AgreenthreadreferstoamodeofoperationfortheJavaVirtualMachine(JVM)inwhichallcodeisexecutedinasingleoperatingsystemthread.IftheJavaprogramhas

  • 6/16/2015 JavaInterviewQuestions

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

    anyconcurrentthreads,theJVMmanagesmultithreadinginternallyratherthanusingotheroperatingsystemthreads.ThereisasignificantprocessingoverheadfortheJVMtokeeptrackofthreadstatesandswap between them, so green threadmode has been deprecated and removed frommorerecentJavaimplementations.

    Q321.ExplainaboutThreadgroup?Ans.EveryJavathreadisamemberofathreadgroup.Threadgroupsprovideamechanismforcollectingmultiplethreadsintoasingleobjectandmanipulatingthosethreadsallatonce,ratherthanindividually.Forexample,youcanstartorsuspendallthethreadswithinagroupwithasinglemethodcall.JavathreadgroupsareimplementedbytheThreadGroupapiclassinthejava.langpackage.

    Q322.WhatistheThreadLocal?Ans.It'sawayforeachthreadinmultithreadedcodetokeepitsowncopyofaninstancevariable.Generally,instancevariablearesharedbetweenallthreadsthatuseanobjectThreadLocalisawayforeachthreadtokeepitsowncopyofsuchavariable.Thepurposemightbethateachthreadkeepsdifferentdatainthatvariable,orthatthedeveloperwantstoavoidtheoverheadofsynchronizingaccesstoit.

    Q323.Whatisinnerclassandwhenweshouldgoforinnerclasses?SometimeswecandeclareaclassinsideanotherclasssuchtypeofclassesarecalledinnerclassesExampleClassCar{

    //morecodehereClassEngine{//morecodehere}}WithoutexistingCarobjectthereisnochanceofexistingEngineobject,henceEngineclasshasdeclaredinsideCarclass.

    Q324.Howmanytypesofinnerclassesarepresent?TherearefourtypesofinnerclassesarepresentoNormalorregularinnerclassoMethodlocalinnerclassoAnonymousinnerclassoStaticnestedclass

    Q325.Whatismethodlocalinnerclass?SometimeswecandeclareaclassinsideamethodsuchtypeofclassesarecalledmethodlocalinnerclassesThemainpurposeofmethodlocalinnerclassesistodefinemethodspecificfunctionalityThescopeofmethodlocalinnerclassesisthescopeofthemethodwhereitisdeclared.Thisisthemostlyrarelyusedtypeofinnerclasses.ExampleclassTest{publicvoidm1(){classInner{publicvoidsum(intI,intj){

  • 6/16/2015 JavaInterviewQuestions

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

    System.out.println(i+J)}//sum}//innerInneri=newInner()i.sum(10,20)//morecodehereI.sum(100,303)//morecodeherei.sum(102,84)}//m1()Publicstaticvoidmain(){NewTest().m1()}}

    Q326.Whatisanonymousinnerclass?SometimeswecandeclareainnerclasswithoutnamesuchtypeofinnerclassesarecalledAnonymousinnerclassesAnonymousinnerclassescanbedividedinto3categoriesAnonymousinnerclassthatextendsaclass

    AnonymousinnerclassthatimplementsaninterfaceAnonymousinnerclassthatdefinesinsideamethodargumentANONYMOUSINNERCLASSTHATEXTENDSACLASSExampleClasspopcorn{Publicvoidtaste(){System.out.println(itissalty)}//morecodehere}ClassTest{Publicstaticvoidmain(String[]args){Popcornp=newPopcorn(){//herewearecreatingchildclassforpopcornPublicvoidtaste(){System.out.println(itissweet)}}//heresemicolonindicateswercreatingchildclassobjectwithparent//classreferenceherechildclassdosentcontainnamep.taste()//itissweetPopcornp=newPopcorn()p1.taste()//itissalty}}

    ANONYMOUSINNERCLASSTHATIMPLEMENTSANINTERFACEexampleclassTest{Publicstaticvoidmain(String[]args){Runnabler=newRunnable(){Publicvoidrun(){for(inti=0i

  • 6/16/2015 JavaInterviewQuestions

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

    Q327.Whatisstaticnestedcalss?whythetermnestedinsteadofinnerinstaticnestedclass?

    Sometimeswecandeclareinnerclasswithstaticmodifiersuchtypeofinnerclassarecalledstaticnestedclasses.thetermnestedinsteadofstaticbecausewithoutexistingouterclassobjectinnerclassobjectcanexist.ExampleClassouter{StaticclassNested{Publicstaticvoidmain(String[]args){System.out.println(nestedclassmain())}}Publicstaticvoidmain(String[]args){System.out.println(outerclassmain())}}JavaOuterO/POuterclassmain()JavaOuter$NestedO/PNestedclassmain()

    Q328.Insideinnerclassisitpossibletodeclaremain()?Noitisnotpossibletodeclaremain()insideinnerclassbutinstaticnestedclassitispossibleforExamplereferaboveco