60 likes | 217 Views
Crack your Java interview by knowing all the questions that your interviewer may ask. Brush up your knowledge with this superb set of Java interview questions
E N D
1 1.To implement keyObjectin HashMapwhich twomethodsareused? InHashMap,touseanyobjectasKeyitmustimplementequalsandHashCodemethodin Java. 2.What is an immutableobject?Mention animmutableobject? ObjectsthatcannotbemodifiedoncecreatedareimmutableobjectsinJAVA.Anewobject canberesultedduetoanymodificationinanimmutableobject.Forexample,inJAVA,String is immutable. In order to prevent sub classfromoverridingmethods inJava whichcan compromiseImmutability,immutableobjectaremostlyfinalinJAVA.Thissamefunctionality canbeachieved bymakingmemberasnonfinalbutprivateandnotmodifyingthemexceptin constructor. 3.Statethedifferencebetweencreating String asnew() andliteral? When string is created withnew()Operator,it’screated in aheap and not added into string pool whereas using literal String arecreated in Stringpool itself which exists in PermGen area ofheap,Example:String s =newString("Test"); It does not put the object in String pool ,but needs to be called String.intern()method which is used to put them intoStringpool explicitly.It’sonly then that’sit create String object as String literal.Fore.g.String s = "Test"Java automatically put that intoString pool. 4.What isdifference between StringBuffer and StringBuilderin Java? Classic Javaquestions canseemtobetricky andveryeasy.InJava5,StringBuilderis introducedandtheonlydifferencebetweenbothofthemisthat StringBuffermethods aresynchronized while StringBuilderis non-synchronized. 5. Overriding HashCode() method has any difference in performance implication? Yes.ApoorHashCodefunctionwillresultinfrequentcollisioninHashMapwhicheventually increase time for adding an object into Hash Map. 6.Whilewritingstoredprocedureoraccessingstoredprocedurefromjavahowisthe error condition handled? ThisisoneofthetoughquestionsnormallyaskedinJavainterview.Thestoredprocedure shouldreturnerrorcodeifsomeoperationfailsbutifstoredprocedureitselffailsthan catching SQLExceptionisthe only choiceleft. 7.Atthecompiletimearetheimportscheckedforvalidity?Thatis,willthecode containing an import suchasjava.lang.ABCD compileup? Yes.Theimportsarecheckedforthesemanticvalidityatthecompiletime.Theabovelineof import will not compile if ithas the code, anerroris shown saying, cannot resolve symbol. Symbol:class ABCD JavaInterviewQuestions&AnswersbyBestOnlineTrainers http://www.bestonlinetrainers.com
2 Location:package io Import java.io.ABCD; 8.StatedifferencebetweenExecutor.submit()and Executer.execute()method? When looking at exception handling, there is a difference. If the tasks throws an exception and if it was submitted with theexecutethen this exception will go to the uncaughtexceptionhandler(thatiswhenoneexplicitlyisnotprovided,thedefaultone will just print the stack trace to System.err). Ifthe task is submitted with anythrown exceptionoracheckedexceptionornot,isthenpartofthetask'sreturnstatus.Andfora taskthatwassubmittedwithsubmit andthatterminateswithanexception,thefuture.get will re-throw this exceptionwrapped in an ExecutionException. 9.What isthedifferencebetweenfactory andabstract factory pattern? OnemorelevelofabstractionisprovidedbyAbstractFactory.Differentfactoriesfromeach Abstract Factoryresponsible forthe creationofdifferent hierarchies ofobjects basedontype offactoryareconsidered.Forexample;Abstract FactoryextendedbyAutomobileFactory, UserFactory, RoleFactoryetc.Foreveryobjectcreatedinthatgenre,eachindividualfactory would be responsible. 10.DefineSingleton? Whichis better:to makewholemethodsynchronized or only critical section synchronized? SingletoninJAVAisaclasswithjustoneinstanceinthewholeJavaapplication.Onesuch exampleisjava.lang.RuntimeisaSingletonclass.WiththeintroductionEnumbyJava5, creating a Singleton is easyratherthan being tricky as earlier. 11.Differentiatebetween aconstructor and amethod? A member function of a class that is used to create objects of thatclass is called a Constructoris.Itsnameissameastheclassitself,hasnoreturntype.Itisinvokedusingthe new operator. AnordinarymemberfunctionofaclassiscalledMethod.Ithasitsownnameandareturn type (which may be void).Itis invoked using thedot operator. 12.State thepurposeof garbagecollection in Java,and also whenisit used? Identifyinganddiscardingobjectsthatarenolongerneededbyaprogramsothattheir resourcescan bereclaimed andreused is the purpose of garbagecollection. WhenaJavaobjectissubjectedbecomesunreachabletotheprograminwhichitisused;itis subjected to garbage collection. JavaInterviewQuestions&AnswersbyBestOnlineTrainers http://www.bestonlinetrainers.com
3 13.When isHashCodeand equals()overridded ? To doequality check oruse object as a key inHashMap,HashCode and equals()are overridden. 14.What is the issueifHashCode()method are not overridded? IftheHashCode()isnotoverridded,theobjectwillnotberecoveredfromtheHashMapif used as key. 15.Statewhichisbetter:tosynchronizecritical section of getInstance() methodor whole getInstance()method ? Heretheanswerisabitcriticalasifwelockthewholemethodthaneverytimethenthis method will be called and wouldhave to waiteven though any object isnot being created. 16.WhenString getscreated using literal or new() operator,what differenceisseen? When a string is created with new()its created in heap and not added into stringpool while using literal ,String canbe createdin String poolitself which exists in Perm area of heap. 17.Does overridingHashCode()methodhaveany performanceimplicationor not ? PoorHashCode functionresults in frequent collision in HashMap which eventually increases the timeforadding an object into Hash Map. 18. In multithreaded environment what’swrong in using HashMap? Whendoesget() method goto infiniteloop? This happens during concurrent access and re-sizing. 19. Whatisthread-safety?Why isit required? And howto achievethread-safety inJava Applications? The legal interaction of threads with the memory in a realcomputersystemdefines Java Memory Model.It alsodescribes what behaviors arelegal ina multi-threaded code.It can also determine when a Thread canreliably see writes to variables made by otherthreads. It also defines semanticsforvolatile,final andsynchronize, that makes guarantee of visibility of memory operations across the Threads. In a MemoryBarrier whichtherearetwo type of memory barrierinstructions in JMM-read barriers and write barrier. To make the changes made by otherthreads visible to the currentThread,the read barrier invalidates the local memory(cache, registers,etc)and then reads thecontents from the main memory.To make the changes made bycurrent Thread visible to otherThread,a Write barrierflushes out the contents of the processor’s local memory to themain memory. JavaInterviewQuestions&AnswersbyBestOnlineTrainers http://www.bestonlinetrainers.com
4 20. WhathappensifyoucallreturnstatementorSystem.exitontryorcatchblock?Will it finally block execute? ThisisaverypopulartrickyJavaquestionbecausemanyprogrammersthinkthatfinallythe blockalwaysgetsexecuted.Thisquestionchallengestheconceptbyputtingreturn statement intryorcatchblockorcallingSystem.exitfromtryorcatchblock.InJava,thisfinally block willexecuteevenifyouputreturn statementinthetryblockorcatchblockfinallyblock won't run even if youcallSystem.exitformto try orcatch. 21.Howare stringscomparedUsing “==”orequals ()? “==” tests if referencesareequal and equals () tests if values areequal.To check iftwo strings are the same object,equals()is always used. 22.Char[]is preferredoverStringforsecuritysensitive information. Why? Strings areimmutable,that is oncethey arecreated,and they stay unchanged until Garbage Collectorkicks in.Its elements can be explicitlychanged with an array.Hence,security sensitive information like passwordwill not be present anywherein the system. 23.Canstringbeused to switchstatement? String can be used to switch statementto version 7.FromJDK7,string can be used as switch condition. Beforeversion 6,stringcannot be usedas switch condition. viewsource print? 01.// java 7 only! 02.switch (str.toLowerCase()) 03.case "a": 04.value =1; 05.break; 06.case "b": 07.value =2; 08.break; 09.} 24.Canstringbeconvertedto int? Yes .It canbe .But its frequently used and ignored at times. viewsource print? 1.int n = Integer.parseInt("10"); JavaInterviewQuestions&AnswersbyBestOnlineTrainers http://www.bestonlinetrainers.com
5 25.How can astring be split with white spacecharacters? String can be slitusing regularexpression. White spacecharactersarerepresented as“\s”. viewsource print? 1.String []strArray = aString.split("\\s+"); 26.What does substring()method do? The existing String is represented by thesubstring()methodwhich givesa window to an array of charsas inJDK6.A new one is not created.Anempty string needsto be added to create a new one. print ? 1.str.substring(m,n)+ "" This creates a new char array representing a new string.This method can help to code faster because the Garbage Collector collects the unusedlarge string and the keeps the substring. 27.What is String vs StringBuilder vsStringBuffer In String vs StringBuilder,StringBuilderis mutable,that is it means itcan be modified afterits creation. In StringBuildervs StringBuffer,StringBufferis synchronized, that is it means itis thread-safe but would be slowerthan StringBuilder. 28.How isastringrepeated? In Python,to repeat a stringjust multiple a number.In Java, the repeat()method of StringUtils from ApacheCommons Lang packagecan be used. 29.In Java,what isthe defaultvalueofbyte datatype? 0 is the default value ofbyte datatype. JavaInterviewQuestions&AnswersbyBestOnlineTrainers http://www.bestonlinetrainers.com
6 30.In astring howto count #of occurrences of acharacter? StringUtils from apachecommons lang can be used. viewsource print? 1.int n = StringUtils.countMatches("11112222","1"); 2.System.out.println(n); WANTTOLEARNJAVAORANYOTHER PROGRAMMINGCOURSE? AskforFREEDEMOToday RegisterNOW http://www.bestonlinetrainers.com/demo/index.html USA: +(1)6783896789|UK:+(44)-2032393637|India:+(91)9246449191 info@bestonlinetrainers.com|www.bestonlinetrainers.com JavaInterviewQuestions&AnswersbyBestOnlineTrainers http://www.bestonlinetrainers.com