0% found this document useful (0 votes)
292 views18 pages

Java Interview Questions - Tutorialspoint

All Java interview Question...

Uploaded by

Rohit Rasal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
292 views18 pages

Java Interview Questions - Tutorialspoint

All Java interview Question...

Uploaded by

Rohit Rasal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

10/2/2016

JavaInterviewQuestionstutorialspoint

JavaInterviewQuestions
https://www.tutorialspoint.com/java/java_interview_questions.htm
Copyrighttutorialspoint.com
Dearreaders,theseJavaInterviewQuestionshavebeendesignedespeciallytogetyouacquaintedwiththe
natureofquestionsyoumayencounterduringyourinterviewforthesubjectofJavaProgrammingLanguage.
Aspermyexperience,goodinterviewershardlyplannedtoaskanyparticularquestionduringyourinterview,
normallyquestionsstartwithsomebasicconceptofthesubjectandlatertheycontinuebasedonfurther
discussionandwhatyouanswer
WhatdoyouknowaboutJava?
JavaisahighlevelprogramminglanguageoriginallydevelopedbySunMicrosystemsandreleasedin1995.
Javarunsonavarietyofplatforms,suchasWindows,MacOS,andthevariousversionsofUNIX.
WhatarethesupportedplatformsbyJavaProgrammingLanguage?
Javarunsonavarietyofplatforms,suchasWindows,MacOS,andthevariousversionsofUNIX/Linuxlike
HPUnix,SunSolaris,RedhatLinux,Ubuntu,CentOS,etc.
ListanyfivefeaturesofJava?
SomefeaturesincludeObjectOriented,PlatformIndependent,Robust,Interpreted,Multithreaded
WhyisJavaArchitecturalNeutral?
Itscompilergeneratesanarchitectureneutralobjectfileformat,whichmakesthecompiledcodetobe
executableonmanyprocessors,withthepresenceofJavaruntimesystem.
HowJavaenabledHighPerformance?
JavausesJustInTimecompilertoenablehighperformance.JustInTimecompilerisaprogramthatturnsJava
bytecode,whichisaprogramthatcontainsinstructionsthatmustbeinterpretedintoinstructionsthatcanbesent
directlytotheprocessor.
WhyJavaisconsidereddynamic?
Itisdesignedtoadapttoanevolvingenvironment.Javaprogramscancarryextensiveamountofruntime
informationthatcanbeusedtoverifyandresolveaccessestoobjectsonruntime.
WhatisJavaVirtualMachineandhowitisconsideredincontextofJavasplatformindependentfeature?
WhenJavaiscompiled,itisnotcompiledintoplatformspecificmachine,ratherintoplatformindependentbyte
code.ThisbytecodeisdistributedoverthewebandinterpretedbyvirtualMachine(JVM)onwhichever
platformitisbeingrun.
ListtwoJavaIDEs?
Netbeans,Eclipse,etc.
ListsomeJavakeywords(unlikeC,C++keywords)?
https://www.tutorialspoint.com/cgibin/printpage.cgi

1/18

10/2/2016

JavaInterviewQuestionstutorialspoint

SomeJavakeywordsareimport,super,finally,etc.
WhatdoyoumeanbyObject?
Objectisaruntimeentityanditsstateisstoredinfieldsandbehaviorisshownviamethods.Methodsoperate
onanobject'sinternalstateandserveastheprimarymechanismforobjecttoobjectcommunication.
Defineclass?
Aclassisablueprintfromwhichindividualobjectsarecreated.Aclasscancontainfieldsandmethodsto
describethebehaviorofanobject.
Whatkindofvariablesaclasscanconsistof?
AclassconsistofLocalvariable,instancevariablesandclassvariables.
WhatisaLocalVariable?
Variablesdefinedinsidemethods,constructorsorblocksarecalledlocalvariables.Thevariablewillbedeclared
andinitializedwithinthemethodanditwillbedestroyedwhenthemethodhascompleted.
WhatisaInstanceVariable?
Instancevariablesarevariableswithinaclassbutoutsideanymethod.Thesevariablesareinstantiatedwhenthe
classisloaded.
WhatisaClassVariable?
Thesearevariablesdeclaredwithinaclass,outsideanymethod,withthestatickeyword.
WhatisSingletonclass?
Singletonclasscontrolobjectcreation,limitingthenumbertoonebutallowingtheflexibilitytocreatemore
objectsifthesituationchanges.
WhatdoyoumeanbyConstructor?
Constructorgetsinvokedwhenanewobjectiscreated.Everyclasshasaconstructor.Ifwedonotexplicitly
writeaconstructorforaclassthejavacompilerbuildsadefaultconstructorforthatclass.
ListthethreestepsforcreatinganObjectforaclass?
AnObjectisfirstdeclared,theninstantiatedandthenitisinitialized.
WhatisthedefaultvalueofbytedatatypeinJava?
Defaultvalueofbytedatatypeis0.
WhatisthedefaultvalueoffloatanddoubledatatypeinJava?
DefaultvalueoffloatanddoubledatatypeindifferentascomparedtoC/C++.Forfloatits0.0fandfordouble
its0.0d
Whenabytedatatypeisused?
Thisdatatypeisusedtosavespaceinlargearrays,mainlyinplaceofintegers,sinceabyteisfourtimessmaller
thananint.
https://www.tutorialspoint.com/cgibin/printpage.cgi

2/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Whatisastaticvariable?
Classvariablesalsoknownasstaticvariablesaredeclaredwiththestatickeywordinaclass,butoutsidea
method,constructororablock.
WhatdoyoumeanbyAccessModifier?
Javaprovidesaccessmodifierstosetaccesslevelsforclasses,variables,methodsandconstructors.Amember
haspackageordefaultaccessibilitywhennoaccessibilitymodifierisspecified.
Whatisprotectedaccessmodifier?
Variables,methodsandconstructorswhicharedeclaredprotectedinasuperclasscanbeaccessedonlybythe
subclassesinotherpackageoranyclasswithinthepackageoftheprotectedmembers'class.
WhatdoyoumeanbysynchronizedNonAccessModifier?
JavaprovidesthesemodifiersforprovidingfunctionalitiesotherthanAccessModifiers,synchronizedusedto
indicatethatamethodcanbeaccessedbyonlyonethreadatatime.
AccordingtoJavaOperatorprecedence,whichoperatorisconsideredtobewithhighestprecedence?
Postfixoperatorsi.e()[].isatthehighestprecedence.
Variablesusedinaswitchstatementcanbeusedwithwhichdatatypes?
Variablesusedinaswitchstatementcanonlybeastring,enum,byte,short,int,orchar.
WhenparseInt()methodcanbeused?
ThismethodisusedtogettheprimitivedatatypeofacertainString.
WhyisStringclassconsideredimmutable?
TheStringclassisimmutable,sothatonceitiscreatedaStringobjectcannotbechanged.SinceStringis
immutableitcansafelybesharedbetweenmanythreads,whichisconsideredveryimportantformultithreaded
programming.
WhyisStringBuffercalledmutable?
TheStringclassisconsideredasimmutable,sothatonceitiscreatedaStringobjectcannotbechanged.Ifthere
isanecessitytomakealotofmodificationstoStringsofcharactersthenStringBuffershouldbeused.
WhatisthedifferencebetweenStringBufferandStringBuilderclass?
UseStringBuilderwheneverpossiblebecauseitisfasterthanStringBuffer.But,ifthreadsafetyisnecessary
thenuseStringBufferobjects.
Whichpackageisusedforpatternmatchingwithregularexpressions?
java.util.regexpackageisusedforthispurpose.
java.util.regexconsistsofwhichclasses?
java.util.regexconsistsofthreeclassesPatternclass,MatcherclassandPatternSyntaxExceptionclass.
https://www.tutorialspoint.com/cgibin/printpage.cgi

3/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Whatisfinalize()method?
Itispossibletodefineamethodthatwillbecalledjustbeforeanobject'sfinaldestructionbythegarbage
collector.Thismethodiscalledfinalize(),anditcanbeusedtoensurethatanobjectterminatescleanly.
WhatisanException?
Anexceptionisaproblemthatarisesduringtheexecutionofaprogram.Exceptionsarecaughtbyhandlers
positionedalongthethread'smethodinvocationstack.
WhatdoyoumeanbyCheckedExceptions?
Itisanexceptionthatistypicallyausererrororaproblemthatcannotbeforeseenbytheprogrammer.For
example,ifafileistobeopened,butthefilecannotbefound,anexceptionoccurs.Theseexceptionscannot
simplybeignoredatthetimeofcompilation.
ExplainRuntimeExceptions?
Itisanexceptionthatoccursthatprobablycouldhavebeenavoidedbytheprogrammer.Asopposedtochecked
exceptions,runtimeexceptionsareignoredatthetimeofcompliation.
WhicharethetwosubclassesunderExceptionclass?
TheExceptionclasshastwomainsubclasses:IOExceptionclassandRuntimeExceptionClass.
Whenthrowskeywordisused?
Ifamethoddoesnothandleacheckedexception,themethodmustdeclareitusingthethrowskeyword.The
throwskeywordappearsattheendofamethod'ssignature.
Whenthrowkeywordisused?
Anexceptioncanbethrown,eitheranewlyinstantiatedoneoranexceptionthatyoujustcaught,byusingthrow
keyword.
HowfinallyusedunderExceptionHandling?
Thefinallykeywordisusedtocreateablockofcodethatfollowsatryblock.Afinallyblockofcodealways
executes,whetherornotanexceptionhasoccurred.
WhatthingsshouldbekeptinmindwhilecreatingyourownexceptionsinJava?
Whilecreatingyourownexception
AllexceptionsmustbeachildofThrowable.
IfyouwanttowriteacheckedexceptionthatisautomaticallyenforcedbytheHandleorDeclareRule,
youneedtoextendtheExceptionclass.
Youwanttowritearuntimeexception,youneedtoextendtheRuntimeExceptionclass.
DefineInheritance?
Itistheprocesswhereoneobjectacquiresthepropertiesofanother.Withtheuseofinheritancetheinformation
ismademanageableinahierarchicalorder.
https://www.tutorialspoint.com/cgibin/printpage.cgi

4/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Whensuperkeywordisused?
Ifthemethodoverridesoneofitssuperclass'smethods,overriddenmethodcanbeinvokedthroughtheuseof
thekeywordsuper.Itcanbealsousedtorefertoahiddenfield.
WhatisPolymorphism?
Polymorphismistheabilityofanobjecttotakeonmanyforms.Themostcommonuseofpolymorphismin
OOPoccurswhenaparentclassreferenceisusedtorefertoachildclassobject.
WhatisAbstraction?
ItreferstotheabilitytomakeaclassabstractinOOP.Ithelpstoreducethecomplexityandalsoimprovesthe
maintainabilityofthesystem.
WhatisAbstractclass?
Theseclassescannotbeinstantiatedandareeitherpartiallyimplementedornotatallimplemented.Thisclass
containsoneormoreabstractmethodswhicharesimplymethoddeclarationswithoutabody.
WhenAbstractmethodsareused?
Ifyouwantaclasstocontainaparticularmethodbutyouwanttheactualimplementationofthatmethodtobe
determinedbychildclasses,youcandeclarethemethodintheparentclassasabstract.
WhatisEncapsulation?
Itisthetechniqueofmakingthefieldsinaclassprivateandprovidingaccesstothefieldsviapublicmethods.If
afieldisdeclaredprivate,itcannotbeaccessedbyanyoneoutsidetheclass,therebyhidingthefieldswithinthe
class.Thereforeencapsulationisalsoreferredtoasdatahiding.
WhatistheprimarybenefitofEncapsulation?
Themainbenefitofencapsulationistheabilitytomodifyourimplementedcodewithoutbreakingthecodeof
otherswhouseourcode.WiththisEncapsulationgivesmaintainability,flexibilityandextensibilitytoourcode.
WhatisanInterface?
Aninterfaceisacollectionofabstractmethods.Aclassimplementsaninterface,therebyinheritingtheabstract
methodsoftheinterface.
GivesomefeaturesofInterface?
Itincludes
Interfacecannotbeinstantiated
Aninterfacedoesnotcontainanyconstructors.
Allofthemethodsinaninterfaceareabstract.
DefinePackagesinJava?
APackagecanbedefinedasagroupingofrelatedtypes(classes,interfaces,enumerationsandannotations)
providingaccessprotectionandnamespacemanagement.
https://www.tutorialspoint.com/cgibin/printpage.cgi

5/18

10/2/2016

JavaInterviewQuestionstutorialspoint

WhyPackagesareused?
PackagesareusedinJavainordertopreventnamingconflicts,tocontrolaccess,tomakesearching/locatingand
usageofclasses,interfaces,enumerationsandannotations,etc.,easier.
WhatdoyoumeanbyMultithreadedprogram?
Amultithreadedprogramcontainstwoormorepartsthatcanrunconcurrently.Eachpartofsuchaprogramis
calledathread,andeachthreaddefinesaseparatepathofexecution.
WhatarethetwowaysinwhichThreadcanbecreated?
Threadcanbecreatedby:implementingRunnableinterface,extendingtheThreadclass.
Whatisanapplet?
AnappletisaJavaprogramthatrunsinaWebbrowser.AnappletcanbeafullyfunctionalJavaapplication
becauseithastheentireJavaAPIatitsdisposal.
Anappletextendwhichclass?
Anappletextendsjava.applet.Appletclass.
ExplaingarbagecollectioninJava?
Itusesgarbagecollectiontofreethememory.Bycleaningthoseobjectsthatisnolongerreferencebyanyofthe
program.
Defineimmutableobject?
Animmutableobjectcantbechangedonceitiscreated.
Explaintheusageofthis()withconstructors?
Itisusedwithvariablesormethodsandusedtocallconstructerofsameclass.
ExplainSetInterface?
Itisacollectionofelementwhichcannotcontainduplicateelements.TheSetinterfacecontainsonlymethods
inheritedfromCollectionandaddstherestrictionthatduplicateelementsareprohibited.
ExplainTreeSet?
ItisaSetimplementedwhenwewantelementsinasortedorder.
WhatisComparableInterface?
Itisusedtosortcollectionsandarraysofobjectsusingthecollections.sort()andjava.utils.Theobjectsofthe
classimplementingtheComparableinterfacecanbeordered.
Differencebetweenthrowandthrows?
Itincludes:
Throwisusedtotriggeranexceptionwhereasthrowsisusedindeclarationofexception.

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

6/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Withoutthrows,Checkedexceptioncannotbehandledwhereascheckedexceptioncanbepropagated
withthrows.
ExplainthefollowinglineusedunderJavaProgram
publicstaticvoidmain(Stringargs[])
Thefollowingshowstheexplanationindividually
publicitistheaccessspecifier.
staticitallowsmain()tobecalledwithoutinstantiatingaparticularinstanceofaclass.
voiditaffirnsthecompilerthatnovalueisreturnedbymain().
main()thismethodiscalledatthebeginningofaJavaprogram.
Stringargs[]argsparameterisaninstancearrayofclassString
DefineJREi.e.JavaRuntimeEnvironment?
JavaRuntimeEnvironmentisanimplementationoftheJavaVirtualMachinewhichexecutesJavaprograms.It
providestheminimumrequirementsforexecutingaJavaapplication
WhatisJARfile?
JARfilesisJavaArchiveflesanditaggregatesmanyfilesintoone.ItholdsJavaclassesinalibrary.JARfiles
arebuiltonZIPfileformatandhave.jarfileextension.
WhatisaWARfile?
ThisisWebArchiveFileandusedtostoreXML,javaclasses,andJavaServerpages.whichisusedtodistribute
acollectionofJavaServerPages,JavaServlets,Javaclasses,XMLfiles,staticWebpagesetc.
DefineJITcompiler?
Itimprovestheruntimeperformanceofcomputerprogramsbasedonbytecode.
Whatisthedifferencebetweenobjectorientedprogramminglanguageandobjectbasedprogramminglanguage?
ObjectbasedprogramminglanguagesfollowallthefeaturesofOOPsexceptInheritance.JavaScriptisan
exampleofobjectbasedprogramminglanguages.
Whatisthepurposeofdefaultconstructor?
Thejavacompilercreatesadefaultconstructoronlyifthereisnoconstructorintheclass.
Canaconstructorbemadefinal?
No,thisisnotpossible.
Whatisstaticblock?
Itisusedtoinitializethestaticdatamember,Itisexcutedbeforemainmethodatthetimeofclassloading.
Definecomposition?
https://www.tutorialspoint.com/cgibin/printpage.cgi

7/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Holdingthereferenceoftheotherclasswithinsomeotherclassisknownascomposition.
Whatisfunctionoverloading?
Ifaclasshasmultiplefunctionsbysamenamebutdifferentparameters,itisknownasMethodOverloading.
Whatisfunctionoverriding?
Ifasubclassprovidesaspecificimplementationofamethodthatisalreadyprovidedbyitsparentclass,itis
knownasMethodOverriding.
DifferencebetweenOverloadingandOverriding?
Methodoverloadingincreasesthereadabilityoftheprogram.Methodoverridingprovidesthespecific
implementationofthemethodthatisalreadyprovidedbyitssuperclassparametermustbedifferentincaseof
overloading,parametermustbesameincaseofoverriding.
Whatisfinalclass?
Finalclassesarecreatedsothemethodsimplementedbythatclasscannotbeoverridden.Itcantbeinherited.
WhatisNullPointerException?
ANullPointerExceptionisthrownwhencallingtheinstancemethodofanullobject,accessingormodifyingthe
fieldofanullobjectetc.
Whatarethewaysinwhichathreadcanenterthewaitingstate?
Athreadcanenterthewaitingstatebyinvokingitssleep()method,byblockingonIO,byunsuccessfully
attemptingtoacquireanobject'slock,orbyinvokinganobject'swait()method.Itcanalsoenterthewaiting
statebyinvokingits(deprecated)suspend()method.
HowdoesmultithreadingtakeplaceonacomputerwithasingleCPU?
Theoperatingsystem'staskschedulerallocatesexecutiontimetomultipletasks.Byquicklyswitchingbetween
executingtasks,itcreatestheimpressionthattasksexecutesequentially.
Whatinvokesathread'srun()method?
Afterathreadisstarted,viaitsstart()methodoftheThreadclass,theJVMinvokesthethread'srun()method
whenthethreadisinitiallyexecuted.
DoesitmatterinwhatordercatchstatementsforFileNotFoundExceptionandIOExceptionarewritten?
Yes,itdoes.TheFileNoFoundExceptionisinheritedfromtheIOException.Exception'ssubclasseshavetobe
caughtfirst.
Whatisthedifferencebetweenyieldingandsleeping?
Whenataskinvokesitsyield()method,itreturnstothereadystate.Whenataskinvokesitssleep()method,it
returnstothewaitingstate.
WhyVectorclassisused?
TheVectorclassprovidesthecapabilitytoimplementagrowablearrayofobjects.Vectorprovestobevery
usefulifyoudon'tknowthesizeofthearrayinadvance,oryoujustneedonethatcanchangesizesoverthe
https://www.tutorialspoint.com/cgibin/printpage.cgi

8/18

10/2/2016

JavaInterviewQuestionstutorialspoint

lifetimeofaprogram.
HowmanybitsareusedtorepresentUnicode,ASCII,UTF16,andUTF8characters?
Unicoderequires16bitsandASCIIrequire7bits.AlthoughtheASCIIcharactersetusesonly7bits,itis
usuallyrepresentedas8bits.UTF8representscharactersusing8,16,and18bitpatterns.UTF16uses16bit
andlargerbitpatterns.
WhatareWrapperclasses?
Theseareclassesthatallowprimitivetypestobeaccessedasobjects.Example:Integer,Character,Double,
Booleanetc.
WhatisthedifferencebetweenaWindowandaFrame?
TheFrameclassextendsWindowtodefineamainapplicationwindowthatcanhaveamenubar.
Whichpackagehaslightweightcomponents?
javax.Swingpackage.AllcomponentsinSwing,exceptJApplet,JDialog,JFrameandJWindowarelightweight
components.
Whatisthedifferencebetweenthepaint()andrepaint()methods?
Thepaint()methodsupportspaintingviaaGraphicsobject.Therepaint()methodisusedtocausepaint()tobe
invokedbytheAWTpaintingthread.
WhatisthepurposeofFileclass?
Itisusedtocreateobjectsthatprovideaccesstothefilesanddirectoriesofalocalfilesystem.
WhatisthedifferencebetweentheReader/WriterclasshierarchyandtheInputStream/OutputStreamclass
hierarchy?
TheReader/Writerclasshierarchyischaracteroriented,andtheInputStream/OutputStreamclasshierarchyis
byteoriented.
Whichclassshouldyouusetoobtaindesigninformationaboutanobject?
TheClassclassisusedtoobtaininformationaboutanobject'sdesignandjava.lang.Classclassinstance
representclasses,interfacesinarunningJavaapplication.
Whatisthedifferencebetweenstaticandnonstaticvariables?
Astaticvariableisassociatedwiththeclassasawholeratherthanwithspecificinstancesofaclass.Nonstatic
variablestakeonuniquevalueswitheachobjectinstance.
WhatisSerializationanddeserialization?
Serializationistheprocessofwritingthestateofanobjecttoabytestream.Deserializationistheprocessof
restoringtheseobjects.
Whatareusecases?
Itispartoftheanalysisofaprogramanddescribesasituationthataprogrammightencounterandwhat
behaviortheprogramshouldexhibitinthatcircumstance.
https://www.tutorialspoint.com/cgibin/printpage.cgi

9/18

10/2/2016

JavaInterviewQuestionstutorialspoint

ExplaintheuseofsublassinaJavaprogram?
Subclassinheritsallthepublicandprotectedmethodsandtheimplementation.Italsoinheritsallthedefault
modifiermethodsandtheirimplementation.
Howtoaddmenushortcuttomenuitem?
Ifthereisabuttoninstancecalledb1,youmayaddmenushortcutbycallingb1.setMnemonic('F'),sotheuser
maybeabletouseAlt+Ftoclickthebutton.
CanyouwriteaJavaclassthatcouldbeusedbothasanappletaswellasanapplication?
Yes,justaddamain()methodtotheapplet.
WhatisthedifferencebetweenSwingandAWTcomponents?
AWTcomponentsareheavyweight,whereasSwingcomponentsarelightweight.Heavyweightcomponents
dependonthelocalwindowingtoolkit.Forexample,java.awt.Buttonisaheavyweightcomponent,whenitis
runningontheJavaplatformforUnixplatform,itmapstoarealMotifbutton.
What'sthedifferencebetweenconstructorsandothermethods?
Constructorsmusthavethesamenameastheclassandcannotreturnavalue.Theyareonlycalledoncewhile
regularmethodscouldbecalledmanytimes.
IsthereanylimitationofusingInheritance?
Yes,sinceinheritanceinheritseverythingfromthesuperclassandinterface,itmaymakethesubclasstoo
clusteringandsometimeserrorpronewhendynamicoverridingordynamicoverloadinginsomesituation.
WhenistheArrayStoreExceptionthrown?
Whencopyingelementsbetweendifferentarrays,ifthesourceordestinationargumentsarenotarraysortheir
typesarenotcompatible,anArrayStoreExceptionwillbethrown.
Canyoucalloneconstructorfromanotherifaclasshasmultipleconstructors?
Yes,usethis()syntax.
What'sthedifferencebetweenthemethodssleep()andwait()?
Thecodesleep(2000)putsthreadasideforexactlytwoseconds.Thecodewait(2000),causesawaitofupto
twosecond.Athreadcouldstopwaitingearlierifitreceivesthenotify()ornotifyAll()call.Themethodwait()is
definedintheclassObjectandthemethodsleep()isdefinedintheclassThread.
WhenArithmeticExceptionisthrown?
TheArithmeticExceptionisthrownwhenintegerisdividedbyzeroortakingtheremainderofanumberbyzero.
Itisneverthrowninfloatingpointoperations.
Whatisatransientvariable?
AtransientvariableisavariablethatmaynotbeserializedduringSerializationandwhichisinitializedbyits
defaultvalueduringdeserialization,
Whatissynchronization?
https://www.tutorialspoint.com/cgibin/printpage.cgi

10/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Synchronizationisthecapabilitytocontroltheaccessofmultiplethreadstosharedresources.synchronized
keywordinjavaprovideslockingwhichensuresmutualexclusiveaccessofsharedresourceandpreventdata
race.
WhatistheCollectionsAPI?
TheCollectionsAPIisasetofclassesandinterfacesthatsupportoperationsoncollectionsofobjects.
Doesgarbagecollectionguaranteethataprogramwillnotrunoutofmemory?
Garbagecollectiondoesnotguaranteethataprogramwillnotrunoutofmemory.Itispossibleforprogramsto
useupmemoryresourcesfasterthantheyaregarbagecollected.Itisalsopossibleforprogramstocreateobjects
thatarenotsubjecttogarbagecollection.
TheimmediatesuperclassoftheAppletclass?
Panelistheimmediatesuperclass.Apanelprovidesspaceinwhichanapplicationcanattachanyother
component,includingotherpanels.
WhichJavaoperatorisrightassociative?
The=operatorisrightassociative.
Whatisthedifferencebetweenabreakstatementandacontinuestatement?
Abreakstatementresultsintheterminationofthestatementtowhichitapplies(switch,for,do,orwhile).A
continuestatementisusedtoendthecurrentloopiterationandreturncontroltotheloopstatement.
Ifavariableisdeclaredasprivate,wheremaythevariablebeaccessed?
Aprivatevariablemayonlybeaccessedwithintheclassinwhichitisdeclared.
WhatisthepurposeoftheSystemclass?
ThepurposeoftheSystemclassistoprovideaccesstosystemresources.
ListprimitiveJavatypes?
Theeightprimitivetypesarebyte,char,short,int,long,float,double,andboolean.
WhatistherelationshipbetweenclippingandrepaintingunderAWT?
WhenawindowisrepaintedbytheAWTpaintingthread,itsetstheclippingregionstotheareaofthewindow
thatrequiresrepainting.
WhichclassistheimmediatesuperclassoftheContainerclass?
Componentclassistheimmediatesuperclass.
WhatclassofexceptionsaregeneratedbytheJavaruntimesystem?
TheJavaruntimesystemgeneratesRuntimeExceptionandErrorexceptions.
Underwhatconditionsisanobject'sfinalize()methodinvokedbythegarbagecollector?
Thegarbagecollectorinvokesanobject'sfinalize()methodwhenitdetectsthattheobjecthasbecome
unreachable.
https://www.tutorialspoint.com/cgibin/printpage.cgi

11/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Howcanadeadthreadberestarted?
Adeadthreadcannotberestarted.
WhicharithmeticoperationscanresultinthethrowingofanArithmeticException?
Integer/and%canresultinthethrowingofanArithmeticException.
Variableofthebooleantypeisautomaticallyinitializedas?
Thedefaultvalueofthebooleantypeisfalse.
Cantrystatementsbenested?
Yes
WhatareClassLoaders?
Aclassloaderisanobjectthatisresponsibleforloadingclasses.TheclassClassLoaderisanabstractclass.
WhatisthedifferencebetweenanInterfaceandanAbstractclass?
Anabstractclasscanhaveinstancemethodsthatimplementadefaultbehavior.AnInterfacecanonlydeclare
constantsandinstancemethods,butcannotimplementdefaultbehaviorandallmethodsareimplicitlyabstract.
Aninterfacehasallpublicmembersandnoimplementation.
Whatwillhappenifstaticmodifierisremovedfromthesignatureofthemainmethod?
Programthrows"NoSuchMethodError"erroratruntime.
Whatisthedefaultvalueofanobjectreferencedeclaredasaninstancevariable?
Null,unlessitisdefinedexplicitly.
Canatoplevelclassbeprivateorprotected?
No,atoplevelclasscannotbeprivateorprotected.Itcanhaveeither"public"ornomodifier.
Whydoweneedwrapperclasses?
Wecanpassthemaroundasmethodparameterswhereamethodexpectsanobject.Italsoprovidesutility
methods.
Whatisthedifferencebetweenerrorandanexception?
Anerrorisanirrecoverableconditionoccurringatruntime.SuchasOutOfMemoryerror.Exceptionsare
conditionsthatoccurbecauseofbadinputetc.e.g.FileNotFoundExceptionwillbethrownifthespecifiedfile
doesnotexist.
Isitnecessarythateachtryblockmustbefollowedbyacatchblock?
Itisnotnecessarythateachtryblockmustbefollowedbyacatchblock.Itshouldbefollowedbyeitheracatch
blockorafinallyblock.
Whenathreadiscreatedandstarted,whatisitsinitialstate?
https://www.tutorialspoint.com/cgibin/printpage.cgi

12/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Athreadisinthereadystateasinitialstateafterithasbeencreatedandstarted.
WhatistheLocaleclass?
TheLocaleclassisusedtotailorprogramoutputtotheconventionsofaparticulargeographic,political,or
culturalregion.
Whataresynchronizedmethodsandsynchronizedstatements?
Synchronizedmethodsaremethodsthatareusedtocontrolaccesstoanobject.Asynchronizedstatementcan
onlybeexecutedafterathreadhasacquiredthelockfortheobjectorclassreferencedinthesynchronized
statement.
Whatisruntimepolymorphismordynamicmethoddispatch?
Runtimepolymorphismordynamicmethoddispatchisaprocessinwhichacalltoanoverriddenmethodis
resolvedatruntimeratherthanatcompiletime.Inthisprocess,anoverriddenmethodiscalledthroughthe
referencevariableofasuperclass.
WhatisDynamicBinding(latebinding)?
Bindingreferstothelinkingofaprocedurecalltothecodetobeexecutedinresponsetothecall.Dynamic
bindingmeansthatthecodeassociatedwithagivenprocedurecallisnotknownuntilthetimeofthecallatrun
time.
Canconstructorbeinherited?
No,constructorcannotbeinherited.
WhataretheadvantagesofArrayListoverarrays?
ArrayListcangrowdynamicallyandprovidesmorepowerfulinsertionandsearchmechanismsthanarrays.
WhydeletioninLinkedListisfastthanArrayList?
Deletioninlinkedlistisfastbecauseitinvolvesonlyupdatingthenextpointerinthenodebeforethedeleted
nodeandupdatingthepreviouspointerinthenodeafterthedeletednode.
HowdoyoudecidewhentouseArrayListandLinkedList?
Ifyouneedtofrequentlyaddandremoveelementsfromthemiddleofthelistandonlyaccessthelistelements
sequentially,thenLinkedListshouldbeused.Ifyouneedtosupportrandomaccess,withoutinsertingor
removingelementsfromanyplaceotherthantheend,thenArrayListshouldbeused.
WhatisaValuesCollectionView?
Itisacollectionreturnedbythevalues()methodoftheMapInterface,Itcontainsalltheobjectspresentas
valuesinthemap.
Whatisdotoperator?
Thedotoperator(.)isusedtoaccesstheinstancevariablesandmethodsofclassobjects.Itisalsousedtoaccess
classesandsubpackagesfromapackage.
Whereandhowcanyouuseaprivateconstructor?
https://www.tutorialspoint.com/cgibin/printpage.cgi

13/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Privateconstructorisusedifyoudonotwantotherclassestoinstantiatetheobjectandtopreventsubclassing.T
Whatistypecasting?
Typecastingmeanstreatingavariableofonetypeasthoughitisanothertype.
Describelifecycleofthread?
Athreadisaexecutioninaprogram.Thelifecycleofathreadinclude
Newbornstate
Runnablestate
Runningstate
Blockedstate
Deadstate
Whatisthedifferencebetweenthe>>and>>>operators?
The>>operatorcarriesthesignbitwhenshiftingright.The>>>zerofillsbitsthathavebeenshiftedout.
WhichmethodoftheComponentclassisusedtosetthepositionandsizeofacomponent?
setBounds()methodisusedforthispurpose.
Whatistherangeoftheshorttype?
Therangeoftheshorttypeis(2^15)to2^151.
WhatistheimmediatesuperclassofMenu?
MenuItemclass
DoesJavaallowDefaultArguments?
No,JavadoesnotallowDefaultArguments.
Whichnumberisdenotedbyleadingzeroinjava?
OctalNumbersaredenotedbyleadingzeroinjava,example:06
Whichnumberisdenotedbyleading0xor0Xinjava?
HexadecimalNumbersaredenotedbyleading0xor0Xinjava,example0XF
BreakstatementcanbeusedaslabelsinJava?
Yes,anexamplecanbebreakone
WhereimportstatementisusedinaJavaprogram?
Importstatementisallowedatthebeginningoftheprogramfileafterpackagestatement.
Explainsuspend()methodunderThreadclass>
Itisusedtopauseortemporarilystoptheexecutionofthethread.
ExplainisAlive()methodunderThreadclass?
https://www.tutorialspoint.com/cgibin/printpage.cgi

14/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Itisusedtofindoutwhetherathreadisstillrunningornot.
WhatiscurrentThread()?
Itisapublicstaticmethodusedtoobtainareferencetothecurrentthread.
ExplainmainthreadunderThreadclassexecution?
Themainthreadiscreatedautomaticallyanditbeginstoexecuteimmediatelywhenaprogramstarts.Itiathread
fromwhichallotherchildthreadsoriginate.
Lifecycleofanappletincludeswhichsteps?
Lifecycleinvolvesthefollowingsteps
Initialization
Starting
Stopping
Destroying
Painting
Whyistheroleofinit()methodunderapplets?
Itinitializestheappletandisthefirstmethodtobecalled.
WhichmethodiscalledbyAppletclasstoloadanimage?
getImage(URLobject,filename)isusedforthispurpose.
DefinecodeasanattributeofApplet?
Itisusedtospecifythenameoftheappletclass.
Definecanvas?
Itisasimpledrawingsurfacewhichareusedforpaintingimagesortoperformothergraphicaloperations.
DefineNetworkProgramming?
Itreferstowritingprogramsthatexecuteacrossmultipledevices(computers),inwhichthedevicesareall
connectedtoeachotherusinganetwork.
WhatisaSocket?
SocketsprovidethecommunicationmechanismbetweentwocomputersusingTCP.Aclientprogramcreatesa
socketonitsendofthecommunicationandattemptstoconnectthatsockettoaserver.
AdvantagesofJavaSockets?
Socketsareflexibleandsufficient.Efficientsocketbasedprogrammingcanbeeasilyimplementedforgeneral
communications.Itcauselownetworktraffic.
DisadvantagesofJavaSockets?
https://www.tutorialspoint.com/cgibin/printpage.cgi

15/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Socketbasedcommunicationsallowsonlytosendpacketsofrawdatabetweenapplications.Boththeclientside
andserversidehavetoprovidemechanismstomakethedatausefulinanyway.
Whichclassisusedbyserverapplicationstoobtainaportandlistenforclientrequests?
java.net.ServerSocketclassisusedbyserverapplicationstoobtainaportandlistenforclientrequests
Whichclassrepresentsthesocketthatboththeclientandserverusetocommunicatewitheachother?
java.net.Socketclassrepresentsthesocketthatboththeclientandserverusetocommunicatewitheachother.
WhyGenericsareusedinJava?
Genericsprovidecompiletimetypesafetythatallowsprogrammerstocatchinvalidtypesatcompiletime.Java
Genericmethodsandgenericclassesenableprogrammerstospecify,withasinglemethoddeclaration,asetof
relatedmethodsor,withasingleclassdeclaration,asetofrelatedtypes.
WhatenvironmentvariablesdoIneedtosetonmymachineinordertobeabletorunJavaprograms?
CLASSPATHandPATHarethetwovariables.
Isthereanyneedtoimportjava.langpackage?
No,thereisnoneedtoimportthispackage.ItisbydefaultloadedinternallybytheJVM.
WhatisNestedtoplevelclass?
Ifaclassisdeclaredwithinaclassandspecifythestaticmodifier,thecompilertreatstheclassjustlikeanyother
toplevelclass.NestedtoplevelclassisanInnerclass.
WhatisExternalizableinterface?
ExternalizableisaninterfacewhichcontainstwomethodsreadExternalandwriteExternal.Thesemethodsgive
youacontrolovertheserializationmechanism.
IfSystem.exit(0)iswrittenattheendofthetryblock,willthefinallyblockstillexecute?
NointhiscasethefinallyblockwillnotexecutebecausewhenyousaySystem.exit(0)thecontrolimmediately
goesoutoftheprogram,andthusfinallyneverexecutes.
Whatisdaemonthread?
Daemonthreadisalowprioritythread,whichrunsintermittentlyinthebackgrounddoingthegarbage
collectionoperationforthejavaruntimesystem.
Whichmethodisusedtocreatethedaemonthread?
setDaemonmethodisusedtocreateadaemonthread.
Whichmethodmustbeimplementedbyallthreads?
Alltasksmustimplementtherun()method
WhatistheGregorianCalendarclass?
TheGregorianCalendarprovidessupportfortraditionalWesterncalendars
https://www.tutorialspoint.com/cgibin/printpage.cgi

16/18

10/2/2016

JavaInterviewQuestionstutorialspoint

WhatistheSimpleTimeZoneclass?
TheSimpleTimeZoneclassprovidessupportforaGregoriancalendar.
WhatisthedifferencebetweenthesizeandcapacityofaVector?
Thesizeisthenumberofelementsactuallystoredinthevector,whilecapacityisthemaximumnumberof
elementsitcanstoreatagiveninstanceoftime.
Canavectorcontainheterogenousobjects?
YesaVectorcancontainheterogenousobjects.BecauseaVectorstoreseverythingintermsofObject.
Whatisanenumeration?
Anenumerationisaninterfacecontainingmethodsforaccessingtheunderlyingdatastructurefromwhichthe
enumerationisobtained.Itallowssequentialaccesstoalltheelementsstoredinthecollection.
WhatisdifferencebetweenPathandClasspath?
PathandClasspathareoperatingsystemlevelenvironmentvariales.Pathisdefineswherethesystemcanfind
theexecutables(.exe)filesandclasspathisusedtospecifythelocationof.classfiles.
Canaclassdeclaredasprivatebeaccessedoutsideit'spackage?
No,it'snotpossibletoaccessedoutsideit'spackage.
Whataretherestrictionimposedonastaticmethodorastaticblockofcode?
Astaticmethodshouldnotrefertoinstancevariableswithoutcreatinganinstanceandcannotuse"this"operator
torefertheinstance.
CananInterfaceextendanotherInterface?
YesanInterfacecaninheritanotherInterface,forthatmatteranInterfacecanextendmorethanoneInterface.
WhichobjectorientedConceptisachievedbyusingoverloadingandoverriding?
Polymorphism
Whatisanobject'slockandwhichobject'shavelocks?
Anobject'slockisamechanismthatisusedbymultiplethreadstoobtainsynchronizedaccesstotheobject.A
threadmayexecuteasynchronizedmethodofanobjectonlyafterithasacquiredtheobject'slock.
WhatisDowncasting?
Itisthecastingfromageneraltoamorespecifictype,i.e.castingdownthehierarchy.
Whatareorderofprecedenceandassociativityandhowaretheyused?
Orderofprecedencedeterminestheorderinwhichoperatorsareevaluatedinexpressions.Associatity
determineswhetheranexpressionisevaluatedlefttorightorrighttoleft.
Ifamethodisdeclaredasprotected,wheremaythemethodbeaccessed?

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

17/18

10/2/2016

JavaInterviewQuestionstutorialspoint

Aprotectedmethodmayonlybeaccessedbyclassesorinterfacesofthesamepackageorbysubclassesofthe
classinwhichitisdeclared.
Whatisthedifferencebetweeninnerclassandnestedclass?
Whenaclassisdefinedwithinascopeofanotherclass,thenitbecomesinnerclass.Iftheaccessmodifierofthe
innerclassisstatic,thenitbecomesnestedclass.
Whatrestrictionsareplacedonmethodoverriding?
Overriddenmethodsmusthavethesamename,argumentlist,andreturntype.Theoverridingmethodmaynot
limittheaccessofthemethoditoverrides.
WhatisconstructorchainingandhowisitachievedinJava?
Achildobjectconstructoralwaysfirstneedstoconstructitsparent.InJavaitisdoneviaanimplicitcalltothe
noargsconstructorasthefirststatement.
Canadoublevaluebecasttoabyte?
Yes,adoublevaluecanbecasttoabyte.
Howdoesatrystatementdeterminewhichcatchclauseshouldbeusedtohandleanexception?
Whenanexceptionisthrownwithinthebodyofatrystatement,thecatchclausesofthetrystatementare
examinedintheorderinwhichtheyappear.Thefirstcatchclausethatiscapableofhandlingtheexceptionis
executed.Theremainingcatchclausesareignored.
Whatwillbethedefaultvaluesofalltheelementsofanarraydefinedasaninstancevariable?
Ifthearrayisanarrayofprimitivetypes,thenalltheelementsofthearraywillbeinitializedtothedefaultvalue
correspondingtothatprimitivetype.

WhatisNext?
Further,youcangothroughyourpastassignmentsyouhavedonewiththesubjectandmakesureyouareableto
speakconfidentlyonthem.Ifyouarefreshertheninterviewerdoesnotexpectyouwillanswerverycomplex
questions,ratheryouhavetomakeyourbasicsconceptsverystrong.
Seconditreallydoesn'tmattermuchifyoucouldnotanswerfewquestionsbutitmattersthatwhateveryou
answered,youmusthaveansweredwithconfidence.Sojustfeelconfidentduringyourinterview.Weat
tutorialspointwishyoubestlucktohaveagoodinterviewerandalltheverybestforyourfutureendeavor.
Cheers:)

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

18/18

You might also like