You are on page 1of 16

9/4/2016

JavaInterviewQuestionstutorialspoint

JAVAINTERVIEWQUESTIONS
http://www.tutorialspoint.com/java/java_interview_questions.htm

Copyrighttutorialspoint.com

Dearreaders,theseJavaInterviewQuestionshavebeendesignedespeciallytogetyouacquaintedwiththenatureofquestionsyoumayencounterduringyourinterviewforthesubjectofJavaProgrammingLanguage.Aspermy
experience,goodinterviewershardlyplannedtoaskanyparticularquestionduringyourinterview,normallyquestionsstartwithsomebasicconceptofthesubjectandlatertheycontinuebasedonfurtherdiscussionandwhatyouanswer
WhatdoyouknowaboutJava?
JavaisahighlevelprogramminglanguageoriginallydevelopedbySunMicrosystemsandreleasedin1995.Javarunsonavarietyofplatforms,suchasWindows,MacOS,andthevariousversionsofUNIX.
WhatarethesupportedplatformsbyJavaProgrammingLanguage?
Javarunsonavarietyofplatforms,suchasWindows,MacOS,andthevariousversionsofUNIX/LinuxlikeHPUnix,SunSolaris,RedhatLinux,Ubuntu,CentOS,etc.
ListanyfivefeaturesofJava?
SomefeaturesincludeObjectOriented,PlatformIndependent,Robust,Interpreted,Multithreaded
WhyisJavaArchitecturalNeutral?
Itscompilergeneratesanarchitectureneutralobjectfileformat,whichmakesthecompiledcodetobeexecutableonmanyprocessors,withthepresenceofJavaruntimesystem.
HowJavaenabledHighPerformance?
JavausesJustInTimecompilertoenablehighperformance.JustInTimecompilerisaprogramthatturnsJavabytecode,whichisaprogramthatcontainsinstructionsthatmustbeinterpretedintoinstructionsthatcanbesentdirectlytothe
processor.
WhyJavaisconsidereddynamic?
Itisdesignedtoadapttoanevolvingenvironment.Javaprogramscancarryextensiveamountofruntimeinformationthatcanbeusedtoverifyandresolveaccessestoobjectsonruntime.
WhatisJavaVirtualMachineandhowitisconsideredincontextofJavasplatformindependentfeature?
WhenJavaiscompiled,itisnotcompiledintoplatformspecificmachine,ratherintoplatformindependentbytecode.ThisbytecodeisdistributedoverthewebandinterpretedbyvirtualMachineJ V M onwhicheverplatformitisbeingrun.
ListtwoJavaIDEs?
Netbeans,Eclipse,etc.
ListsomeJavakeywordsunlikeC , C + +keywords ?
SomeJavakeywordsareimport,super,finally,etc.
WhatdoyoumeanbyObject?
Objectisaruntimeentityanditsstateisstoredinfieldsandbehaviorisshownviamethods.Methodsoperateonanobject'sinternalstateandserveastheprimarymechanismforobjecttoobjectcommunication.
Defineclass?
Aclassisablueprintfromwhichindividualobjectsarecreated.Aclasscancontainfieldsandmethodstodescribethebehaviorofanobject.
Whatkindofvariablesaclasscanconsistof?
AclassconsistofLocalvariable,instancevariablesandclassvariables.

http://www.tutorialspoint.com/cgibin/printpage.cgi

1/16

9/4/2016

JavaInterviewQuestionstutorialspoint

WhatisaLocalVariable?
Variablesdefinedinsidemethods,constructorsorblocksarecalledlocalvariables.Thevariablewillbedeclaredandinitializedwithinthemethodanditwillbedestroyedwhenthemethodhascompleted.
WhatisaInstanceVariable?
Instancevariablesarevariableswithinaclassbutoutsideanymethod.Thesevariablesareinstantiatedwhentheclassisloaded.
WhatisaClassVariable?
Thesearevariablesdeclaredwithinaclass,outsideanymethod,withthestatickeyword.
WhatisSingletonclass?
Singletonclasscontrolobjectcreation,limitingthenumbertoonebutallowingtheflexibilitytocreatemoreobjectsifthesituationchanges.
WhatdoyoumeanbyConstructor?
Constructorgetsinvokedwhenanewobjectiscreated.Everyclasshasaconstructor.Ifwedonotexplicitlywriteaconstructorforaclassthejavacompilerbuildsadefaultconstructorforthatclass.
ListthethreestepsforcreatinganObjectforaclass?
AnObjectisfirstdeclared,theninstantiatedandthenitisinitialized.
WhatisthedefaultvalueofbytedatatypeinJava?
Defaultvalueofbytedatatypeis0.
WhatisthedefaultvalueoffloatanddoubledatatypeinJava?
DefaultvalueoffloatanddoubledatatypeindifferentascomparedtoC/C++.Forfloatits0.0fandfordoubleits0.0d
Whenabytedatatypeisused?
Thisdatatypeisusedtosavespaceinlargearrays,mainlyinplaceofintegers,sinceabyteisfourtimessmallerthananint.
Whatisastaticvariable?
Classvariablesalsoknownasstaticvariablesaredeclaredwiththestatickeywordinaclass,butoutsideamethod,constructororablock.
WhatdoyoumeanbyAccessModifier?
Javaprovidesaccessmodifierstosetaccesslevelsforclasses,variables,methodsandconstructors.Amemberhaspackageordefaultaccessibilitywhennoaccessibilitymodifierisspecified.
Whatisprotectedaccessmodifier?
Variables,methodsandconstructorswhicharedeclaredprotectedinasuperclasscanbeaccessedonlybythesubclassesinotherpackageoranyclasswithinthepackageoftheprotectedmembers'class.
WhatdoyoumeanbysynchronizedNonAccessModifier?
JavaprovidesthesemodifiersforprovidingfunctionalitiesotherthanAccessModifiers,synchronizedusedtoindicatethatamethodcanbeaccessedbyonlyonethreadatatime.
AccordingtoJavaOperatorprecedence,whichoperatorisconsideredtobewithhighestprecedence?
Postfixoperatorsi.e[].isatthehighestprecedence.
Variablesusedinaswitchstatementcanbeusedwithwhichdatatypes?

http://www.tutorialspoint.com/cgibin/printpage.cgi

2/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Variablesusedinaswitchstatementcanonlybeastring,enum,byte,short,int,orchar.
WhenparseIntmethodcanbeused?
ThismethodisusedtogettheprimitivedatatypeofacertainString.
WhyisStringclassconsideredimmutable?
TheStringclassisimmutable,sothatonceitiscreatedaStringobjectcannotbechanged.SinceStringisimmutableitcansafelybesharedbetweenmanythreads,whichisconsideredveryimportantformultithreadedprogramming.
WhyisStringBuffercalledmutable?
TheStringclassisconsideredasimmutable,sothatonceitiscreatedaStringobjectcannotbechanged.IfthereisanecessitytomakealotofmodificationstoStringsofcharactersthenStringBuffershouldbeused.
WhatisthedifferencebetweenStringBufferandStringBuilderclass?
UseStringBuilderwheneverpossiblebecauseitisfasterthanStringBuffer.But,ifthreadsafetyisnecessarythenuseStringBufferobjects.
Whichpackageisusedforpatternmatchingwithregularexpressions?
java.util.regexpackageisusedforthispurpose.
java.util.regexconsistsofwhichclasses?
java.util.regexconsistsofthreeclassesPatternclass,MatcherclassandPatternSyntaxExceptionclass.
Whatisfinalizemethod?
Itispossibletodefineamethodthatwillbecalledjustbeforeanobject'sfinaldestructionbythegarbagecollector.Thismethodiscalledfinalize,anditcanbeusedtoensurethatanobjectterminatescleanly.
WhatisanException?
Anexceptionisaproblemthatarisesduringtheexecutionofaprogram.Exceptionsarecaughtbyhandlerspositionedalongthethread'smethodinvocationstack.
WhatdoyoumeanbyCheckedExceptions?
Itisanexceptionthatistypicallyausererrororaproblemthatcannotbeforeseenbytheprogrammer.Forexample,ifafileistobeopened,butthefilecannotbefound,anexceptionoccurs.Theseexceptionscannotsimplybeignoredatthetime
ofcompilation.
ExplainRuntimeExceptions?
Itisanexceptionthatoccursthatprobablycouldhavebeenavoidedbytheprogrammer.Asopposedtocheckedexceptions,runtimeexceptionsareignoredatthetimeofcompliation.
WhicharethetwosubclassesunderExceptionclass?
TheExceptionclasshastwomainsubclasses:IOExceptionclassandRuntimeExceptionClass.
Whenthrowskeywordisused?
Ifamethoddoesnothandleacheckedexception,themethodmustdeclareitusingthethrowskeyword.Thethrowskeywordappearsattheendofamethod'ssignature.
Whenthrowkeywordisused?
Anexceptioncanbethrown,eitheranewlyinstantiatedoneoranexceptionthatyoujustcaught,byusingthrowkeyword.
HowfinallyusedunderExceptionHandling?

http://www.tutorialspoint.com/cgibin/printpage.cgi

3/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Thefinallykeywordisusedtocreateablockofcodethatfollowsatryblock.Afinallyblockofcodealwaysexecutes,whetherornotanexceptionhasoccurred.
WhatthingsshouldbekeptinmindwhilecreatingyourownexceptionsinJava?
Whilecreatingyourownexception
AllexceptionsmustbeachildofThrowable.
IfyouwanttowriteacheckedexceptionthatisautomaticallyenforcedbytheHandleorDeclareRule,youneedtoextendtheExceptionclass.
Youwanttowritearuntimeexception,youneedtoextendtheRuntimeExceptionclass.
DefineInheritance?
Itistheprocesswhereoneobjectacquiresthepropertiesofanother.Withtheuseofinheritancetheinformationismademanageableinahierarchicalorder.
Whensuperkeywordisused?
Ifthemethodoverridesoneofitssuperclass'smethods,overriddenmethodcanbeinvokedthroughtheuseofthekeywordsuper.Itcanbealsousedtorefertoahiddenfield.
WhatisPolymorphism?
Polymorphismistheabilityofanobjecttotakeonmanyforms.ThemostcommonuseofpolymorphisminOOPoccurswhenaparentclassreferenceisusedtorefertoachildclassobject.
WhatisAbstraction?
ItreferstotheabilitytomakeaclassabstractinOOP.Ithelpstoreducethecomplexityandalsoimprovesthemaintainabilityofthesystem.
WhatisAbstractclass?
Theseclassescannotbeinstantiatedandareeitherpartiallyimplementedornotatallimplemented.Thisclasscontainsoneormoreabstractmethodswhicharesimplymethoddeclarationswithoutabody.
WhenAbstractmethodsareused?
Ifyouwantaclasstocontainaparticularmethodbutyouwanttheactualimplementationofthatmethodtobedeterminedbychildclasses,youcandeclarethemethodintheparentclassasabstract.
WhatisEncapsulation?
Itisthetechniqueofmakingthefieldsinaclassprivateandprovidingaccesstothefieldsviapublicmethods.Ifafieldisdeclaredprivate,itcannotbeaccessedbyanyoneoutsidetheclass,therebyhidingthefieldswithintheclass.Therefore
encapsulationisalsoreferredtoasdatahiding.
WhatistheprimarybenefitofEncapsulation?
Themainbenefitofencapsulationistheabilitytomodifyourimplementedcodewithoutbreakingthecodeofotherswhouseourcode.WiththisEncapsulationgivesmaintainability,flexibilityandextensibilitytoourcode.
WhatisanInterface?
Aninterfaceisacollectionofabstractmethods.Aclassimplementsaninterface,therebyinheritingtheabstractmethodsoftheinterface.
GivesomefeaturesofInterface?
Itincludes
Interfacecannotbeinstantiated
Aninterfacedoesnotcontainanyconstructors.

http://www.tutorialspoint.com/cgibin/printpage.cgi

4/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Allofthemethodsinaninterfaceareabstract.
DefinePackagesinJava?
APackagecanbedefinedasagroupingofrelatedtypesclasses, interf aces, enumerationsandannotations providingaccessprotectionandnamespacemanagement.
WhyPackagesareused?
PackagesareusedinJavainordertopreventnamingconflicts,tocontrolaccess,tomakesearching/locatingandusageofclasses,interfaces,enumerationsandannotations,etc.,easier.
WhatdoyoumeanbyMultithreadedprogram?
Amultithreadedprogramcontainstwoormorepartsthatcanrunconcurrently.Eachpartofsuchaprogramiscalledathread,andeachthreaddefinesaseparatepathofexecution.
WhatarethetwowaysinwhichThreadcanbecreated?
Threadcanbecreatedby:implementingRunnableinterface,extendingtheThreadclass.
Whatisanapplet?
AnappletisaJavaprogramthatrunsinaWebbrowser.AnappletcanbeafullyfunctionalJavaapplicationbecauseithastheentireJavaAPIatitsdisposal.
Anappletextendwhichclass?
Anappletextendsjava.applet.Appletclass.
ExplaingarbagecollectioninJava?
Itusesgarbagecollectiontofreethememory.Bycleaningthoseobjectsthatisnolongerreferencebyanyoftheprogram.
Defineimmutableobject?
Animmutableobjectcantbechangedonceitiscreated.
Explaintheusageofthiswithconstructors?
Itisusedwithvariablesormethodsandusedtocallconstructerofsameclass.
ExplainSetInterface?
Itisacollectionofelementwhichcannotcontainduplicateelements.TheSetinterfacecontainsonlymethodsinheritedfromCollectionandaddstherestrictionthatduplicateelementsareprohibited.
ExplainTreeSet?
ItisaSetimplementedwhenwewantelementsinasortedorder.
WhatisComparableInterface?
Itisusedtosortcollectionsandarraysofobjectsusingthecollections.sortandjava.utils.TheobjectsoftheclassimplementingtheComparableinterfacecanbeordered.
Differencebetweenthrowandthrows?
Itincludes:
Throwisusedtotriggeranexceptionwhereasthrowsisusedindeclarationofexception.
Withoutthrows,Checkedexceptioncannotbehandledwhereascheckedexceptioncanbepropagatedwiththrows.

http://www.tutorialspoint.com/cgibin/printpage.cgi

5/16

9/4/2016

JavaInterviewQuestionstutorialspoint

ExplainthefollowinglineusedunderJavaProgram
publicstaticvoidmainS tringargs[]
Thefollowingshowstheexplanationindividually
publicitistheaccessspecifier.
staticitallowsmaintobecalledwithoutinstantiatingaparticularinstanceofaclass.
voiditaffirnsthecompilerthatnovalueisreturnedbymain.
mainthismethodiscalledatthebeginningofaJavaprogram.
Stringargs[]argsparameterisaninstancearrayofclassString
DefineJREi.e.JavaRuntimeEnvironment?
JavaRuntimeEnvironmentisanimplementationoftheJavaVirtualMachinewhichexecutesJavaprograms.ItprovidestheminimumrequirementsforexecutingaJavaapplication
WhatisJARfile?
JARfilesisJavaArchiveflesanditaggregatesmanyfilesintoone.ItholdsJavaclassesinalibrary.JARfilesarebuiltonZIPfileformatandhave.jarfileextension.
WhatisaWARfile?
ThisisWebArchiveFileandusedtostoreXML,javaclasses,andJavaServerpages.whichisusedtodistributeacollectionofJavaServerPages,JavaServlets,Javaclasses,XMLfiles,staticWebpagesetc.
DefineJITcompiler?
Itimprovestheruntimeperformanceofcomputerprogramsbasedonbytecode.
Whatisthedifferencebetweenobjectorientedprogramminglanguageandobjectbasedprogramminglanguage?
ObjectbasedprogramminglanguagesfollowallthefeaturesofOOPsexceptInheritance.JavaScriptisanexampleofobjectbasedprogramminglanguages.
Whatisthepurposeofdefaultconstructor?
Thejavacompilercreatesadefaultconstructoronlyifthereisnoconstructorintheclass.
Canaconstructorbemadefinal?
No,thisisnotpossible.
Whatisstaticblock?
Itisusedtoinitializethestaticdatamember,Itisexcutedbeforemainmethodatthetimeofclassloading.
Definecomposition?
Holdingthereferenceoftheotherclasswithinsomeotherclassisknownascomposition.
Whatisfunctionoverloading?
Ifaclasshasmultiplefunctionsbysamenamebutdifferentparameters,itisknownasMethodOverloading.
Whatisfunctionoverriding?

http://www.tutorialspoint.com/cgibin/printpage.cgi

6/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Ifasubclassprovidesaspecificimplementationofamethodthatisalreadyprovidedbyitsparentclass,itisknownasMethodOverriding.
DifferencebetweenOverloadingandOverriding?
Methodoverloadingincreasesthereadabilityoftheprogram.Methodoverridingprovidesthespecificimplementationofthemethodthatisalreadyprovidedbyitssuperclassparametermustbedifferentincaseofoverloading,parametermustbe
sameincaseofoverriding.
Whatisfinalclass?
Finalclassesarecreatedsothemethodsimplementedbythatclasscannotbeoverridden.Itcantbeinherited.
WhatisNullPointerException?
ANullPointerExceptionisthrownwhencallingtheinstancemethodofanullobject,accessingormodifyingthefieldofanullobjectetc.
Whatarethewaysinwhichathreadcanenterthewaitingstate?
Athreadcanenterthewaitingstatebyinvokingitssleepmethod,byblockingonIO,byunsuccessfullyattemptingtoacquireanobject'slock,orbyinvokinganobject'swaitmethod.Itcanalsoenterthewaitingstatebyinvokingitsdeprecated
suspendmethod.
HowdoesmultithreadingtakeplaceonacomputerwithasingleCPU?
Theoperatingsystem'staskschedulerallocatesexecutiontimetomultipletasks.Byquicklyswitchingbetweenexecutingtasks,itcreatestheimpressionthattasksexecutesequentially.
Whatinvokesathread'srunmethod?
Afterathreadisstarted,viaitsstartmethodoftheThreadclass,theJVMinvokesthethread'srunmethodwhenthethreadisinitiallyexecuted.
DoesitmatterinwhatordercatchstatementsforFileNotFoundExceptionandIOExceptionarewritten?
Yes,itdoes.TheFileNoFoundExceptionisinheritedfromtheIOException.Exception'ssubclasseshavetobecaughtfirst.
Whatisthedifferencebetweenyieldingandsleeping?
Whenataskinvokesitsyieldmethod,itreturnstothereadystate.Whenataskinvokesitssleepmethod,itreturnstothewaitingstate.
WhyVectorclassisused?
TheVectorclassprovidesthecapabilitytoimplementagrowablearrayofobjects.Vectorprovestobeveryusefulifyoudon'tknowthesizeofthearrayinadvance,oryoujustneedonethatcanchangesizesoverthelifetimeofaprogram.
HowmanybitsareusedtorepresentUnicode,ASCII,UTF16,andUTF8characters?
Unicoderequires16bitsandASCIIrequire7bits.AlthoughtheASCIIcharactersetusesonly7bits,itisusuallyrepresentedas8bits.UTF8representscharactersusing8,16,and18bitpatterns.UTF16uses16bitandlargerbitpatterns.
WhatareWrapperclasses?
Theseareclassesthatallowprimitivetypestobeaccessedasobjects.Example:Integer,Character,Double,Booleanetc.
WhatisthedifferencebetweenaWindowandaFrame?
TheFrameclassextendsWindowtodefineamainapplicationwindowthatcanhaveamenubar.
Whichpackagehaslightweightcomponents?
javax.Swingpackage.AllcomponentsinSwing,exceptJApplet,JDialog,JFrameandJWindowarelightweightcomponents.
Whatisthedifferencebetweenthepaintandrepaintmethods?

http://www.tutorialspoint.com/cgibin/printpage.cgi

7/16

9/4/2016

JavaInterviewQuestionstutorialspoint

ThepaintmethodsupportspaintingviaaGraphicsobject.TherepaintmethodisusedtocausepainttobeinvokedbytheAWTpaintingthread.
WhatisthepurposeofFileclass?
Itisusedtocreateobjectsthatprovideaccesstothefilesanddirectoriesofalocalfilesystem.
WhatisthedifferencebetweentheReader/WriterclasshierarchyandtheInputStream/OutputStreamclasshierarchy?
TheReader/Writerclasshierarchyischaracteroriented,andtheInputStream/OutputStreamclasshierarchyisbyteoriented.
Whichclassshouldyouusetoobtaindesigninformationaboutanobject?
TheClassclassisusedtoobtaininformationaboutanobject'sdesignandjava.lang.Classclassinstancerepresentclasses,interfacesinarunningJavaapplication.
Whatisthedifferencebetweenstaticandnonstaticvariables?
Astaticvariableisassociatedwiththeclassasawholeratherthanwithspecificinstancesofaclass.Nonstaticvariablestakeonuniquevalueswitheachobjectinstance.
WhatisSerializationanddeserialization?
Serializationistheprocessofwritingthestateofanobjecttoabytestream.Deserializationistheprocessofrestoringtheseobjects.
Whatareusecases?
Itispartoftheanalysisofaprogramanddescribesasituationthataprogrammightencounterandwhatbehaviortheprogramshouldexhibitinthatcircumstance.
ExplaintheuseofsublassinaJavaprogram?
Subclassinheritsallthepublicandprotectedmethodsandtheimplementation.Italsoinheritsallthedefaultmodifiermethodsandtheirimplementation.
Howtoaddmenushortcuttomenuitem?
Ifthereisabuttoninstancecalledb1,youmayaddmenushortcutbycallingb1.setMnemonic F ,sotheusermaybeabletouseAlt+Ftoclickthebutton.

CanyouwriteaJavaclassthatcouldbeusedbothasanappletaswellasanapplication?
Yes,justaddamainmethodtotheapplet.
WhatisthedifferencebetweenSwingandAWTcomponents?
AWTcomponentsareheavyweight,whereasSwingcomponentsarelightweight.Heavyweightcomponentsdependonthelocalwindowingtoolkit.Forexample,java.awt.Buttonisaheavyweightcomponent,whenitisrunningontheJavaplatform
forUnixplatform,itmapstoarealMotifbutton.
What'sthedifferencebetweenconstructorsandothermethods?
Constructorsmusthavethesamenameastheclassandcannotreturnavalue.Theyareonlycalledoncewhileregularmethodscouldbecalledmanytimes.
IsthereanylimitationofusingInheritance?
Yes,sinceinheritanceinheritseverythingfromthesuperclassandinterface,itmaymakethesubclasstooclusteringandsometimeserrorpronewhendynamicoverridingordynamicoverloadinginsomesituation.
WhenistheArrayStoreExceptionthrown?
Whencopyingelementsbetweendifferentarrays,ifthesourceordestinationargumentsarenotarraysortheirtypesarenotcompatible,anArrayStoreExceptionwillbethrown.
Canyoucalloneconstructorfromanotherifaclasshasmultipleconstructors?

http://www.tutorialspoint.com/cgibin/printpage.cgi

8/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Yes,usethissyntax.
What'sthedifferencebetweenthemethodssleepandwait?
Thecodesleep2000putsthreadasideforexactlytwoseconds.Thecodewait2000,causesawaitofuptotwosecond.AthreadcouldstopwaitingearlierifitreceivesthenotifyornotifyAllcall.ThemethodwaitisdefinedintheclassObjectandthe
methodsleepisdefinedintheclassThread.
WhenArithmeticExceptionisthrown?
TheArithmeticExceptionisthrownwhenintegerisdividedbyzeroortakingtheremainderofanumberbyzero.Itisneverthrowninfloatingpointoperations.
Whatisatransientvariable?
AtransientvariableisavariablethatmaynotbeserializedduringSerializationandwhichisinitializedbyitsdefaultvalueduringdeserialization,
Whatissynchronization?
Synchronizationisthecapabilitytocontroltheaccessofmultiplethreadstosharedresources.synchronizedkeywordinjavaprovideslockingwhichensuresmutualexclusiveaccessofsharedresourceandpreventdatarace.
WhatistheCollectionsAPI?
TheCollectionsAPIisasetofclassesandinterfacesthatsupportoperationsoncollectionsofobjects.
Doesgarbagecollectionguaranteethataprogramwillnotrunoutofmemory?
Garbagecollectiondoesnotguaranteethataprogramwillnotrunoutofmemory.Itispossibleforprogramstouseupmemoryresourcesfasterthantheyaregarbagecollected.Itisalsopossibleforprogramstocreateobjectsthatarenotsubjectto
garbagecollection.
TheimmediatesuperclassoftheAppletclass?
Panelistheimmediatesuperclass.Apanelprovidesspaceinwhichanapplicationcanattachanyothercomponent,includingotherpanels.
WhichJavaoperatorisrightassociative?
The=operatorisrightassociative.
Whatisthedifferencebetweenabreakstatementandacontinuestatement?
Abreakstatementresultsintheterminationofthestatementtowhichitappliesswitch, f or, do, orwhile .Acontinuestatementisusedtoendthecurrentloopiterationandreturncontroltotheloopstatement.
Ifavariableisdeclaredasprivate,wheremaythevariablebeaccessed?
Aprivatevariablemayonlybeaccessedwithintheclassinwhichitisdeclared.
WhatisthepurposeoftheSystemclass?
ThepurposeoftheSystemclassistoprovideaccesstosystemresources.
ListprimitiveJavatypes?
Theeightprimitivetypesarebyte,char,short,int,long,float,double,andboolean.
WhatistherelationshipbetweenclippingandrepaintingunderAWT?
WhenawindowisrepaintedbytheAWTpaintingthread,itsetstheclippingregionstotheareaofthewindowthatrequiresrepainting.
WhichclassistheimmediatesuperclassoftheContainerclass?

http://www.tutorialspoint.com/cgibin/printpage.cgi

9/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Componentclassistheimmediatesuperclass.
WhatclassofexceptionsaregeneratedbytheJavaruntimesystem?
TheJavaruntimesystemgeneratesRuntimeExceptionandErrorexceptions.
Underwhatconditionsisanobject'sfinalizemethodinvokedbythegarbagecollector?
Thegarbagecollectorinvokesanobject'sfinalizemethodwhenitdetectsthattheobjecthasbecomeunreachable.
Howcanadeadthreadberestarted?
Adeadthreadcannotberestarted.
WhicharithmeticoperationscanresultinthethrowingofanArithmeticException?
Integer/and%canresultinthethrowingofanArithmeticException.
Variableofthebooleantypeisautomaticallyinitializedas?
Thedefaultvalueofthebooleantypeisfalse.
Cantrystatementsbenested?
Yes
WhatareClassLoaders?
Aclassloaderisanobjectthatisresponsibleforloadingclasses.TheclassClassLoaderisanabstractclass.
WhatisthedifferencebetweenanInterfaceandanAbstractclass?
Anabstractclasscanhaveinstancemethodsthatimplementadefaultbehavior.AnInterfacecanonlydeclareconstantsandinstancemethods,butcannotimplementdefaultbehaviorandallmethodsareimplicitlyabstract.Aninterfacehasallpublic
membersandnoimplementation.
Whatwillhappenifstaticmodifierisremovedfromthesignatureofthemainmethod?
Programthrows"NoSuchMethodError"erroratruntime.
Whatisthedefaultvalueofanobjectreferencedeclaredasaninstancevariable?
Null,unlessitisdefinedexplicitly.
Canatoplevelclassbeprivateorprotected?
No,atoplevelclasscannotbeprivateorprotected.Itcanhaveeither"public"ornomodifier.
Whydoweneedwrapperclasses?
Wecanpassthemaroundasmethodparameterswhereamethodexpectsanobject.Italsoprovidesutilitymethods.
Whatisthedifferencebetweenerrorandanexception?
Anerrorisanirrecoverableconditionoccurringatruntime.SuchasOutOfMemoryerror.Exceptionsareconditionsthatoccurbecauseofbadinputetc.e.g.FileNotFoundExceptionwillbethrownifthespecifiedfiledoesnotexist.
Isitnecessarythateachtryblockmustbefollowedbyacatchblock?

http://www.tutorialspoint.com/cgibin/printpage.cgi

10/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Itisnotnecessarythateachtryblockmustbefollowedbyacatchblock.Itshouldbefollowedbyeitheracatchblockorafinallyblock.
Whenathreadiscreatedandstarted,whatisitsinitialstate?
Athreadisinthereadystateasinitialstateafterithasbeencreatedandstarted.
WhatistheLocaleclass?
TheLocaleclassisusedtotailorprogramoutputtotheconventionsofaparticulargeographic,political,orculturalregion.
Whataresynchronizedmethodsandsynchronizedstatements?
Synchronizedmethodsaremethodsthatareusedtocontrolaccesstoanobject.Asynchronizedstatementcanonlybeexecutedafterathreadhasacquiredthelockfortheobjectorclassreferencedinthesynchronizedstatement.
Whatisruntimepolymorphismordynamicmethoddispatch?
Runtimepolymorphismordynamicmethoddispatchisaprocessinwhichacalltoanoverriddenmethodisresolvedatruntimeratherthanatcompiletime.Inthisprocess,anoverriddenmethodiscalledthroughthereferencevariableofa
superclass.
WhatisDynamicBindinglatebinding ?
Bindingreferstothelinkingofaprocedurecalltothecodetobeexecutedinresponsetothecall.Dynamicbindingmeansthatthecodeassociatedwithagivenprocedurecallisnotknownuntilthetimeofthecallatruntime.
Canconstructorbeinherited?
No,constructorcannotbeinherited.
WhataretheadvantagesofArrayListoverarrays?
ArrayListcangrowdynamicallyandprovidesmorepowerfulinsertionandsearchmechanismsthanarrays.
WhydeletioninLinkedListisfastthanArrayList?
Deletioninlinkedlistisfastbecauseitinvolvesonlyupdatingthenextpointerinthenodebeforethedeletednodeandupdatingthepreviouspointerinthenodeafterthedeletednode.
HowdoyoudecidewhentouseArrayListandLinkedList?
Ifyouneedtofrequentlyaddandremoveelementsfromthemiddleofthelistandonlyaccessthelistelementssequentially,thenLinkedListshouldbeused.Ifyouneedtosupportrandomaccess,withoutinsertingorremovingelementsfromany
placeotherthantheend,thenArrayListshouldbeused.
WhatisaValuesCollectionView?
ItisacollectionreturnedbythevaluesmethodoftheMapInterface,Itcontainsalltheobjectspresentasvaluesinthemap.
Whatisdotoperator?
Thedotoperator.isusedtoaccesstheinstancevariablesandmethodsofclassobjects.Itisalsousedtoaccessclassesandsubpackagesfromapackage.
Whereandhowcanyouuseaprivateconstructor?
Privateconstructorisusedifyoudonotwantotherclassestoinstantiatetheobjectandtopreventsubclassing.T
Whatistypecasting?
Typecastingmeanstreatingavariableofonetypeasthoughitisanothertype.
Describelifecycleofthread?

http://www.tutorialspoint.com/cgibin/printpage.cgi

11/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Athreadisaexecutioninaprogram.Thelifecycleofathreadinclude
Newbornstate
Runnablestate
Runningstate
Blockedstate
Deadstate
Whatisthedifferencebetweenthe>>and>>>operators?
The>>operatorcarriesthesignbitwhenshiftingright.The>>>zerofillsbitsthathavebeenshiftedout.
WhichmethodoftheComponentclassisusedtosetthepositionandsizeofacomponent?
setBoundsmethodisusedforthispurpose.
Whatistherangeoftheshorttype?
Therangeoftheshorttypeis2 5to2^151.
1

WhatistheimmediatesuperclassofMenu?
MenuItemclass
DoesJavaallowDefaultArguments?
No,JavadoesnotallowDefaultArguments.
Whichnumberisdenotedbyleadingzeroinjava?
OctalNumbersaredenotedbyleadingzeroinjava,example:06
Whichnumberisdenotedbyleading0xor0Xinjava?
HexadecimalNumbersaredenotedbyleading0xor0Xinjava,example0XF
BreakstatementcanbeusedaslabelsinJava?
Yes,anexamplecanbebreakone
WhereimportstatementisusedinaJavaprogram?
Importstatementisallowedatthebeginningoftheprogramfileafterpackagestatement.
ExplainsuspendmethodunderThreadclass>
Itisusedtopauseortemporarilystoptheexecutionofthethread.
ExplainisAlivemethodunderThreadclass?
Itisusedtofindoutwhetherathreadisstillrunningornot.
WhatiscurrentThread?

http://www.tutorialspoint.com/cgibin/printpage.cgi

12/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Itisapublicstaticmethodusedtoobtainareferencetothecurrentthread.
ExplainmainthreadunderThreadclassexecution?
Themainthreadiscreatedautomaticallyanditbeginstoexecuteimmediatelywhenaprogramstarts.Itiathreadfromwhichallotherchildthreadsoriginate.
Lifecycleofanappletincludeswhichsteps?
Lifecycleinvolvesthefollowingsteps
Initialization
Starting
Stopping
Destroying
Painting
Whyistheroleofinitmethodunderapplets?
Itinitializestheappletandisthefirstmethodtobecalled.
WhichmethodiscalledbyAppletclasstoloadanimage?
getImageU RLobject, f ilename isusedforthispurpose.
DefinecodeasanattributeofApplet?
Itisusedtospecifythenameoftheappletclass.
Definecanvas?
Itisasimpledrawingsurfacewhichareusedforpaintingimagesortoperformothergraphicaloperations.
DefineNetworkProgramming?
Itreferstowritingprogramsthatexecuteacrossmultipledevicescomputers ,inwhichthedevicesareallconnectedtoeachotherusinganetwork.
WhatisaSocket?
SocketsprovidethecommunicationmechanismbetweentwocomputersusingTCP.Aclientprogramcreatesasocketonitsendofthecommunicationandattemptstoconnectthatsockettoaserver.
AdvantagesofJavaSockets?
Socketsareflexibleandsufficient.Efficientsocketbasedprogrammingcanbeeasilyimplementedforgeneralcommunications.Itcauselownetworktraffic.
DisadvantagesofJavaSockets?
Socketbasedcommunicationsallowsonlytosendpacketsofrawdatabetweenapplications.Boththeclientsideandserversidehavetoprovidemechanismstomakethedatausefulinanyway.
Whichclassisusedbyserverapplicationstoobtainaportandlistenforclientrequests?
java.net.ServerSocketclassisusedbyserverapplicationstoobtainaportandlistenforclientrequests
Whichclassrepresentsthesocketthatboththeclientandserverusetocommunicatewitheachother?

http://www.tutorialspoint.com/cgibin/printpage.cgi

13/16

9/4/2016

JavaInterviewQuestionstutorialspoint

java.net.Socketclassrepresentsthesocketthatboththeclientandserverusetocommunicatewitheachother.
WhyGenericsareusedinJava?
Genericsprovidecompiletimetypesafetythatallowsprogrammerstocatchinvalidtypesatcompiletime.JavaGenericmethodsandgenericclassesenableprogrammerstospecify,withasinglemethoddeclaration,asetofrelatedmethodsor,with
asingleclassdeclaration,asetofrelatedtypes.
WhatenvironmentvariablesdoIneedtosetonmymachineinordertobeabletorunJavaprograms?
CLASSPATHandPATHarethetwovariables.
Isthereanyneedtoimportjava.langpackage?
No,thereisnoneedtoimportthispackage.ItisbydefaultloadedinternallybytheJVM.
WhatisNestedtoplevelclass?
Ifaclassisdeclaredwithinaclassandspecifythestaticmodifier,thecompilertreatstheclassjustlikeanyothertoplevelclass.NestedtoplevelclassisanInnerclass.
WhatisExternalizableinterface?
ExternalizableisaninterfacewhichcontainstwomethodsreadExternalandwriteExternal.Thesemethodsgiveyouacontrolovertheserializationmechanism.
IfSystem.exit0iswrittenattheendofthetryblock,willthefinallyblockstillexecute?
NointhiscasethefinallyblockwillnotexecutebecausewhenyousaySystem.exit0thecontrolimmediatelygoesoutoftheprogram,andthusfinallyneverexecutes.
Whatisdaemonthread?
Daemonthreadisalowprioritythread,whichrunsintermittentlyinthebackgrounddoingthegarbagecollectionoperationforthejavaruntimesystem.
Whichmethodisusedtocreatethedaemonthread?
setDaemonmethodisusedtocreateadaemonthread.
Whichmethodmustbeimplementedbyallthreads?
Alltasksmustimplementtherunmethod
WhatistheGregorianCalendarclass?
TheGregorianCalendarprovidessupportfortraditionalWesterncalendars
WhatistheSimpleTimeZoneclass?
TheSimpleTimeZoneclassprovidessupportforaGregoriancalendar.
WhatisthedifferencebetweenthesizeandcapacityofaVector?
Thesizeisthenumberofelementsactuallystoredinthevector,whilecapacityisthemaximumnumberofelementsitcanstoreatagiveninstanceoftime.
Canavectorcontainheterogenousobjects?
YesaVectorcancontainheterogenousobjects.BecauseaVectorstoreseverythingintermsofObject.
Whatisanenumeration?

http://www.tutorialspoint.com/cgibin/printpage.cgi

14/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Anenumerationisaninterfacecontainingmethodsforaccessingtheunderlyingdatastructurefromwhichtheenumerationisobtained.Itallowssequentialaccesstoalltheelementsstoredinthecollection.
WhatisdifferencebetweenPathandClasspath?
PathandClasspathareoperatingsystemlevelenvironmentvariales.Pathisdefineswherethesystemcanfindtheexecutables. exefilesandclasspathisusedtospecifythelocationof.classfiles.
Canaclassdeclaredasprivatebeaccessedoutsideit'spackage?
No,it'snotpossibletoaccessedoutsideit'spackage.
Whataretherestrictionimposedonastaticmethodorastaticblockofcode?
Astaticmethodshouldnotrefertoinstancevariableswithoutcreatinganinstanceandcannotuse"this"operatortorefertheinstance.
CananInterfaceextendanotherInterface?
YesanInterfacecaninheritanotherInterface,forthatmatteranInterfacecanextendmorethanoneInterface.
WhichobjectorientedConceptisachievedbyusingoverloadingandoverriding?
Polymorphism
Whatisanobject'slockandwhichobject'shavelocks?
Anobject'slockisamechanismthatisusedbymultiplethreadstoobtainsynchronizedaccesstotheobject.Athreadmayexecuteasynchronizedmethodofanobjectonlyafterithasacquiredtheobject'slock.
WhatisDowncasting?
Itisthecastingfromageneraltoamorespecifictype,i.e.castingdownthehierarchy.
Whatareorderofprecedenceandassociativityandhowaretheyused?
Orderofprecedencedeterminestheorderinwhichoperatorsareevaluatedinexpressions.Associatitydetermineswhetheranexpressionisevaluatedlefttorightorrighttoleft.
Ifamethodisdeclaredasprotected,wheremaythemethodbeaccessed?
Aprotectedmethodmayonlybeaccessedbyclassesorinterfacesofthesamepackageorbysubclassesoftheclassinwhichitisdeclared.
Whatisthedifferencebetweeninnerclassandnestedclass?
Whenaclassisdefinedwithinascopeofanotherclass,thenitbecomesinnerclass.Iftheaccessmodifieroftheinnerclassisstatic,thenitbecomesnestedclass.
Whatrestrictionsareplacedonmethodoverriding?
Overriddenmethodsmusthavethesamename,argumentlist,andreturntype.Theoverridingmethodmaynotlimittheaccessofthemethoditoverrides.
WhatisconstructorchainingandhowisitachievedinJava?
Achildobjectconstructoralwaysfirstneedstoconstructitsparent.InJavaitisdoneviaanimplicitcalltothenoargsconstructorasthefirststatement.
Canadoublevaluebecasttoabyte?
Yes,adoublevaluecanbecasttoabyte.
Howdoesatrystatementdeterminewhichcatchclauseshouldbeusedtohandleanexception?

http://www.tutorialspoint.com/cgibin/printpage.cgi

15/16

9/4/2016

JavaInterviewQuestionstutorialspoint

Whenanexceptionisthrownwithinthebodyofatrystatement,thecatchclausesofthetrystatementareexaminedintheorderinwhichtheyappear.Thefirstcatchclausethatiscapableofhandlingtheexceptionisexecuted.Theremainingcatch
clausesareignored.
Whatwillbethedefaultvaluesofalltheelementsofanarraydefinedasaninstancevariable?
Ifthearrayisanarrayofprimitivetypes,thenalltheelementsofthearraywillbeinitializedtothedefaultvaluecorrespondingtothatprimitivetype.

WhatisNext?
Further,youcangothroughyourpastassignmentsyouhavedonewiththesubjectandmakesureyouareabletospeakconfidentlyonthem.Ifyouarefreshertheninterviewerdoesnotexpectyouwillanswerverycomplexquestions,ratheryou
havetomakeyourbasicsconceptsverystrong.
Seconditreallydoesn'tmattermuchifyoucouldnotanswerfewquestionsbutitmattersthatwhateveryouanswered,youmusthaveansweredwithconfidence.Sojustfeelconfidentduringyourinterview.Weattutorialspointwishyoubestluckto
haveagoodinterviewerandalltheverybestforyourfutureendeavor.Cheers:)

http://www.tutorialspoint.com/cgibin/printpage.cgi

16/16

You might also like