Java interview questions tutorialspoint

Download Java interview questions   tutorialspoint

Post on 18-Aug-2015

24 views

Category:

Education

0 download

Embed Size (px)

TRANSCRIPT

<ol><li> 1. 6/1/2015 JavaInterviewQuestionstutorialspoint http://www.tutorialspoint.com/cgibin/printpage.cgi 1/20 http://www.tutorialspoint.com/java/java_interview_questions.htm Copyrighttutorialspoint.com JAVAINTERVIEWQUESTIONS Dearreaders,theseJavaInterviewQuestionshavebeendesignedespeciallytogetyouacquaintedwith thenatureofquestionsyoumayencounterduringyourinterviewforthesubjectofJavaProgramming Language.Aspermyexperience,goodinterviewershardlyplannedtoaskanyparticularquestionduring yourinterview,normallyquestionsstartwithsomebasicconceptofthesubjectandlatertheycontinue basedonfurtherdiscussionandwhatyouanswer: WhatdoyouknowaboutJava? JavaisahighlevelprogramminglanguageoriginallydevelopedbySunMicrosystemsandreleasedin1995. Javarunsonavarietyofplatforms,suchasWindows,MacOS,andthevariousversionsofUNIX. WhatarethesupportedplatformsbyJavaProgrammingLanguage? Javarunsonavarietyofplatforms,suchasWindows,MacOS,andthevariousversionsofUNIX/Linux likeHPUnix,SunSolaris,RedhatLinux,Ubuntu,CentOS,etc. ListanyfivefeaturesofJava? SomefeaturesincludeObjectOriented,PlatformIndependent,Robust,Interpreted,Multithreaded WhyisJavaArchitecturalNeutral? Itscompilergeneratesanarchitectureneutralobjectfileformat,whichmakesthecompiledcodetobe executableonmanyprocessors,withthepresenceofJavaruntimesystem. HowJavaenabledHighPerformance? JavausesJustInTimecompilertoenablehighperformance.JustInTimecompilerisaprogramthat turnsJavabytecode,whichisaprogramthatcontainsinstructionsthatmustbeinterpretedinto instructionsthatcanbesentdirectlytotheprocessor. WhyJavaisconsidereddynamic? Itisdesignedtoadapttoanevolvingenvironment.Javaprogramscancarryextensiveamountofruntime informationthatcanbeusedtoverifyandresolveaccessestoobjectsonruntime. WhatisJavaVirtualMachineandhowitisconsideredincontextofJavasplatformindependentfeature? WhenJavaiscompiled,itisnotcompiledintoplatformspecificmachine,ratherintoplatformindependent bytecode.ThisbytecodeisdistributedoverthewebandinterpretedbyvirtualMachine on whicheverplatformitisbeingrun. ListtwoJavaIDEs? Netbeans,Eclipse,etc. ListsomeJavakeywords ? JV M unlikeC, C + +keywords </li><li> 2. 6/1/2015 JavaInterviewQuestionstutorialspoint http://www.tutorialspoint.com/cgibin/printpage.cgi 2/20 SomeJavakeywordsareimport,super,finally,etc. WhatdoyoumeanbyObject? Objectisaruntimeentityanditsstateisstoredinfieldsandbehaviorisshownviamethods.Methods operateonanobject'sinternalstateandserveastheprimarymechanismforobjecttoobject communication. Defineclass? Aclassisablueprintfromwhichindividualobjectsarecreated.Aclasscancontainfieldsandmethodsto describethebehaviorofanobject. Whatkindofvariablesaclasscanconsistof? AclassconsistofLocalvariable,instancevariablesandclassvariables. WhatisaLocalVariable? Variablesdefinedinsidemethods,constructorsorblocksarecalledlocalvariables.Thevariablewillbe declaredandinitializedwithinthemethodanditwillbedestroyedwhenthemethodhascompleted. WhatisaInstanceVariable? Instancevariablesarevariableswithinaclassbutoutsideanymethod.Thesevariablesareinstantiated whentheclassisloaded. WhatisaClassVariable? Thesearevariablesdeclaredwithinaclass,outsideanymethod,withthestatickeyword. WhatisSingletonclass? Singletonclasscontrolobjectcreation,limitingthenumbertoonebutallowingtheflexibilitytocreate moreobjectsifthesituationchanges. WhatdoyoumeanbyConstructor? Constructorgetsinvokedwhenanewobjectiscreated.Everyclasshasaconstructor.Ifwedonotexplicitly writeaconstructorforaclassthejavacompilerbuildsadefaultconstructorforthatclass. ListthethreestepsforcreatinganObjectforaclass? AnObjectisfirstdeclared,theninstantiatedandthenitisinitialized. WhatisthedefaultvalueofbytedatatypeinJava? Defaultvalueofbytedatatypeis0. WhatisthedefaultvalueoffloatanddoubledatatypeinJava? DefaultvalueoffloatanddoubledatatypeindifferentascomparedtoC/C++.Forfloatits0.0fandfor doubleits0.0d </li><li> 3. 6/1/2015 JavaInterviewQuestionstutorialspoint http://www.tutorialspoint.com/cgibin/printpage.cgi 3/20 Whenabytedatatypeisused? Thisdatatypeisusedtosavespaceinlargearrays,mainlyinplaceofintegers,sinceabyteisfourtimes smallerthananint. Whatisastaticvariable? Classvariablesalsoknownasstaticvariablesaredeclaredwiththestatickeywordinaclass,butoutsidea method,constructororablock. WhatdoyoumeanbyAccessModifier? Javaprovidesaccessmodifierstosetaccesslevelsforclasses,variables,methodsandconstructors.A memberhaspackageordefaultaccessibilitywhennoaccessibilitymodifierisspecified. Whatisprotectedaccessmodifier? Variables,methodsandconstructorswhicharedeclaredprotectedinasuperclasscanbeaccessedonlyby thesubclassesinotherpackageoranyclasswithinthepackageoftheprotectedmembers'class. WhatdoyoumeanbysynchronizedNonAccessModifier? JavaprovidesthesemodifiersforprovidingfunctionalitiesotherthanAccessModifiers,synchronizedused toindicatethatamethodcanbeaccessedbyonlyonethreadatatime. AccordingtoJavaOperatorprecedence,whichoperatorisconsideredtobewithhighestprecedence? Postfixoperatorsi.e[].isatthehighestprecedence. Variablesusedinaswitchstatementcanbeusedwithwhichdatatypes? Variablesusedinaswitchstatementcanonlybeabyte,short,int,orchar. WhenparseIntmethodcanbeused? ThismethodisusedtogettheprimitivedatatypeofacertainString. WhyisStringclassconsideredimmutable? TheStringclassisimmutable,sothatonceitiscreatedaStringobjectcannotbechanged.SinceStringis immutableitcansafelybesharedbetweenmanythreads,whichisconsideredveryimportantfor multithreadedprogramming. WhyisStringBuffercalledmutable? TheStringclassisconsideredasimmutable,sothatonceitiscreatedaStringobjectcannotbechanged.If thereisanecessitytomakealotofmodificationstoStringsofcharactersthenStringBuffershouldbeused. WhatisthedifferencebetweenStringBufferandStringBuilderclass? UseStringBuilderwheneverpossiblebecauseitisfasterthanStringBuffer.But,ifthreadsafetyis necessarythenuseStringBufferobjects. </li><li> 4. 6/1/2015 JavaInterviewQuestionstutorialspoint http://www.tutorialspoint.com/cgibin/printpage.cgi 4/20 Whichpackageisusedforpatternmatchingwithregularexpressions? java.util.regexpackageisusedforthispurpose. java.util.regexconsistsofwhichclasses? java.util.regexconsistsofthreeclasses:Patternclass,MatcherclassandPatternSyntaxExceptionclass. Whatisfinalizemethod? Itispossibletodefineamethodthatwillbecalledjustbeforeanobject'sfinaldestructionbythegarbage collector.Thismethodiscalledfinalize,anditcanbeusedtoensurethatanobjectterminatescleanly. WhatisanException? Anexceptionisaproblemthatarisesduringtheexecutionofaprogram.Exceptionsarecaughtbyhandlers positionedalongthethread'smethodinvocationstack. WhatdoyoumeanbyCheckedExceptions? Itisanexceptionthatistypicallyausererrororaproblemthatcannotbeforeseenbytheprogrammer.For example,ifafileistobeopened,butthefilecannotbefound,anexceptionoccurs.Theseexceptions cannotsimplybeignoredatthetimeofcompilation. ExplainRuntimeExceptions? Itisanexceptionthatoccursthatprobablycouldhavebeenavoidedbytheprogrammer.Asopposedto checkedexceptions,runtimeexceptionsareignoredatthetimeofcompliation. WhicharethetwosubclassesunderExceptionclass? TheExceptionclasshastwomainsubclasses:IOExceptionclassandRuntimeExceptionClass. Whenthrowskeywordisused? Ifamethoddoesnothandleacheckedexception,themethodmustdeclareitusingthethrowskeyword.The throwskeywordappearsattheendofamethod'ssignature. Whenthrowkeywordisused? Anexceptioncanbethrown,eitheranewlyinstantiatedoneoranexceptionthatyoujustcaught,byusing throwkeyword. HowfinallyusedunderExceptionHandling? Thefinallykeywordisusedtocreateablockofcodethatfollowsatryblock.Afinallyblockofcodealways executes,whetherornotanexceptionhasoccurred. WhatthingsshouldbekeptinmindwhilecreatingyourownexceptionsinJava? Whilecreatingyourownexception: AllexceptionsmustbeachildofThrowable. </li><li> 5. 6/1/2015 JavaInterviewQuestionstutorialspoint http://www.tutorialspoint.com/cgibin/printpage.cgi 5/20 IfyouwanttowriteacheckedexceptionthatisautomaticallyenforcedbytheHandleorDeclare Rule,youneedtoextendtheExceptionclass. Youwanttowritearuntimeexception,youneedtoextendtheRuntimeExceptionclass. DefineInheritance? Itistheprocesswhereoneobjectacquiresthepropertiesofanother.Withtheuseofinheritancethe informationismademanageableinahierarchicalorder. Whensuperkeywordisused? Ifthemethodoverridesoneofitssuperclass'smethods,overriddenmethodcanbeinvokedthroughthe useofthekeywordsuper.Itcanbealsousedtorefertoahiddenfield. WhatisPolymorphism? Polymorphismistheabilityofanobjecttotakeonmanyforms.Themostcommonuseofpolymorphismin OOPoccurswhenaparentclassreferenceisusedtorefertoachildclassobject. WhatisAbstraction? ItreferstotheabilitytomakeaclassabstractinOOP.Ithelpstoreducethecomplexityandalsoimproves themaintainabilityofthesystem. WhatisAbstractclass? Theseclassescannotbeinstantiatedandareeitherpartiallyimplementedornotatallimplemented.This classcontainsoneormoreabstractmethodswhicharesimplymethoddeclarationswithoutabody. WhenAbstractmethodsareused? Ifyouwantaclasstocontainaparticularmethodbutyouwanttheactualimplementationofthatmethod tobedeterminedbychildclasses,youcandeclarethemethodintheparentclassasabstract. WhatisEncapsulation? Itisthetechniqueofmakingthefieldsinaclassprivateandprovidingaccesstothefieldsviapublic methods.Ifafieldisdeclaredprivate,itcannotbeaccessedbyanyoneoutsidetheclass,therebyhidingthe fieldswithintheclass.Thereforeencapsulationisalsoreferredtoasdatahiding. WhatistheprimarybenefitofEncapsulation? Themainbenefitofencapsulationistheabilitytomodifyourimplementedcodewithoutbreakingthecode ofotherswhouseourcode.WiththisEncapsulationgivesmaintainability,flexibilityandextensibilityto ourcode. WhatisanInterface? Aninterfaceisacollectionofabstractmethods.Aclassimplementsaninterface,therebyinheritingthe abstractmethodsoftheinterface. GivesomefeaturesofInterface? </li><li> 6. 6/1/2015 JavaInterviewQuestionstutorialspoint http://www.tutorialspoint.com/cgibin/printpage.cgi 6/20 Itincludes: Interfacecannotbeinstantiated Aninterfacedoesnotcontainanyconstructors. Allofthemethodsinaninterfaceareabstract. DefinePackagesinJava? APackagecanbedefinedasagroupingofrelatedtypes providingaccessprotectionandnamespacemanagement. WhyPackagesareused? PackagesareusedinJavainordertopreventnamingconflicts,tocontrolaccess,tomake searching/locatingandusageofclasses,interfaces,enumerationsandannotations,etc.,easier. WhatdoyoumeanbyMultithreadedprogram? Amultithreadedprogramcontainstwoormorepartsthatcanrunconcurrently.Eachpartofsucha programiscalledathread,andeachthreaddefinesaseparatepathofexecution. WhatarethetwowaysinwhichThreadcanbecreated? Threadcanbecreatedby:implementingRunnableinterface,extendingtheThreadclass. Whatisanapplet? AnappletisaJavaprogramthatrunsinaWebbrowser.AnappletcanbeafullyfunctionalJavaapplication becauseithastheentireJavaAPIatitsdisposal. Anappletextendwhichclass? Anappletextendsjava.applet.Appletclass. ExplaingarbagecollectioninJava? Itusesgarbagecollectiontofreethememory.Bycleaningthoseobjectsthatisnolongerreferencebyany oftheprogram. Defineimmutableobject? Animmutableobjectcantbechangedonceitiscreated. Explaintheusageofthiswithconstructors? Itisusedwithvariablesormethodsandusedtocallconstructerofsameclass. ExplainSetInterface? Itisacollectionofelementwhichcannotcontainduplicateelements.TheSetinterfacecontainsonly methodsinheritedfromCollectionandaddstherestrictionthatduplicateelementsareprohibited. classes, interfaces, enumerationsandannotations </li><li> 7. 6/1/2015 JavaInterviewQuestionstutorialspoint http://www.tutorialspoint.com/cgibin/printpage.cgi 7/20 ExplainTreeSet? ItisaSetimplementedwhenwewantelementsinasortedorder. WhatisComparableInterface? Itisusedtosortcollectionsandarraysofobjectsusingthecollections.sortandjava.utils.Theobjectsofthe classimplementingtheComparableinterfacecanbeordered. Differencebetweenthrowandthrows? Itincludes: Throwisusedtotriggeranexceptionwhereasthrowsisusedindeclarationofexception. Withoutthrows,Checkedexceptioncannotbehandledwhereascheckedexceptioncanbe propagatedwiththrows. ExplainthefollowinglineusedunderJavaProgram: publicstaticvoidmain Thefollowingshowstheexplanationindividually: public:itistheaccessspecifier. static:itallowsmaintobecalledwithoutinstantiatingaparticularinstanceofaclass. void:itaffirnsthecompilerthatnovalueisreturnedbymain. main:thismethodiscalledatthebeginningofaJavaprogram. Stringargs[]:argsparameterisaninstancearrayofclassString DefineJREi.e.JavaRuntimeEnvironment? JavaRuntimeEnvironmentisanimplementationoftheJavaVirtualMachinewhichexecutesJava programs.ItprovidestheminimumrequirementsforexecutingaJavaapplication WhatisJARfile? JARfilesisJavaArchiveflesanditaggregatesmanyfilesintoone.ItholdsJavaclassesinalibrary.JAR filesarebuiltonZIPfileformatandhave.jarfileextension. WhatisaWARfile? ThisisWebArchiveFileandusedtostoreXML,javaclasses,andJavaServerpages.whichisusedto distributeacollectionofJavaServerPages,JavaServlets,Javaclasses,XMLfiles,staticWebpagesetc. DefineJITcompiler? Itimprovestheruntimeperformanceofcomputerprogramsbasedonbytecode. Stringargs[] </li><li> 8. 6/1/2015 JavaInterviewQuestionstutorialspoint http://www.tutorialspoint.com/cgibin/printpage.cgi 8/20 Whatisthedifferencebetweenobjectorientedprogramminglanguageandobjectbasedprogramming language? ObjectbasedprogramminglanguagesfollowallthefeaturesofOOPsexceptInheritance.JavaScriptisan exampleofobjectbasedprogramminglanguages. Whatisthepurposeofdefaultconstructor? Thejavacompilercreatesadefaultconstructoronlyifthereisnoconstructorintheclass. Canaconstructorbemadefinal? No,thisisnotpossible. Whatisstaticblock? Itisusedtoinitializethestaticdatamember,Itisexcutedbeforemainmethodatthetimeofclassloading. Definecomposition? Holdingthereferenceoftheotherclasswithinsomeotherclassisknownascomposition. Whatisfunctionoverloading? Ifaclasshasmultiplefunctionsbysamenamebutdifferentparameters,itisknownasMethod Overloading. Whatisfunctionoverriding? Ifasubclassprovidesaspecificimplementationofamethodthatisalreadyprovidedbyitsparentclass,itis knownasMethodOverriding. DifferencebetweenOverloadingandOverriding? Methodoverloadingincreasesthereadabilityoftheprogram.Methodoverridingprovidesthespecific implementationofthemethodthatisalreadyprovidedbyitssuperclassparametermustbedifferentin caseofoverloading,parametermustbesameincaseofoverriding. Whatisfinalclass? Finalclassesarecreatedsothemethodsimplementedbythatclasscannotbeoverridden.Itcantbe inherited. WhatisNullPointerException? ANullPointerExceptionisthrownwhencallingtheinstancemethodofanullobject,accessingormodifying thefieldofanullobjectetc. Whatarethewaysinwhichathreadcanenterthewaitingstate? Athreadcanenterthewaitingstatebyinvokingitssleepmethod,byblockingonIO,byunsuccessfully attemptingtoacquireanobject'slock,orbyinvokinganobject'swaitmethod.Itcanalsoenterthewaiting statebyinvokingits suspendmethod.deprecated </li><li> 9. 6/1/2015 JavaInterviewQuestionstutorialspoint http://www.tutorialspoint.com/cgibin/printpage.cgi 9/20 HowdoesmultithreadingtakeplaceonacomputerwithasingleCPU? Theoperatingsystem'staskschedulerallocatesexecutiontimetomultipletasks.Byquicklyswitching betweenexecutingtasks,itcreatestheimpressionthattasksexecutesequentially. Whatinvokesa...</li></ol>