Java Interview Prep Guide
Java Interview Prep Guide
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
164JavaInterviewQuestionsbyNageswaraRao
>>FRIDAY,AUGUST14,2009
[Link]
[Link]
throughttheseQuestionsthiswouldbehelpfultoyou..
Ifyouarealreadyattendedanyinterviewsonjavayoumighthavefacedmostofthe
[Link].
1)Whypointersareeliminatedfromjava?
Ans)
1. Pointersleadtoconfusionforaprogrammer.
2. Pointersmaycrashaprogrameasily,forexample,whenweaddtwopointers,theprogramcrashersimmediately.
3. [Link],harmfulprogramslikeVirusandotherhackingprogramscanbedeveloped.
Becauseoftheabovereasons,pointershavebeeneliminatedfromjava.
2)Whatisthedifferencebetweenafunctionandamethod?
Ans).[Link].
Thismeanswheneverafunctioniswritteninjava,[Link]++,we
can write the functions inside as well as outside the class. So in C++, they are called member functions and not
methods.
3)WhichpartofJVMwillallocatethememoryforajavaprogram?
Ans).ClassloadersubsystemofJVMwillallocatethenecessarymemoryneededbythejavaprogram.
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%2
1/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
4).whichalgorithmisusedbygarbagecollectortoremovetheunusedvariablesorobjects
frommemory?
Ans).Garbagecollectorusesmanyalgorithmsbutthemostcommonlyusedalgorithmismarkandsweep.
5).Howcanyoucallthegarbagecollector?
Ans).[Link]()
methodofRuntimeclassorSystemclassinJava.
6)WhatisJITCompiler?
Ans).JITcompileristhepartofJVMwhichincreasesthespeedofexecutionofaJavaprogram.
7)WhatisanAPIdocument?
Ans).An API document is a .html file that contains description of all the features of a softwar, a product, or a
[Link].
8)Whatisthedifferencebetween#includeandimportstatement?
Ans).#includedirective makes the compiler go to the C/C++ standard library and copy the code from the header
[Link],theprogramsizeincreases,thuswastingmemoryandprocessorstime.
importstatement makes the JVM go to the Java standard library, execute the code there , and substitute the result
into the program. Here, no code is copied and hence no waste of memory or processors time. so import is an
efficientmechanismthan#include.
9)Whatisthedifferencebetweenprint()andprintln()method?
Ans).Both methods are used to display the results on the monitor. print( ) method displays the result and then
retains the cursor in the same line, next to the end of the [Link]()displays the result and then throws the
cursortothenextline.
10)WhathappensifStringargs[]isnotwritteninmain()method?
Ans).Whenmain()methodiswrittenwithoutStringargs[]as:
Publicstaticvoidmain()
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%2
2/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
The code will compile but JVM cannot run the code because it cannot recognize the main( ) as the method from
[Link]()methodwithstring
typearrayasparameter.
11)Whatisthedifferencebetweenfloatanddouble?
Ans).Floatcanrepresentupto7digitsaccuratelyafterdecimalpoint,whereasdoublecanrepresentupto15digits
accuratelyafterdecimalpoint.
12)WhatisaUnicodesystem?
Ans).Unicodesystemisanencodingstandardthatprovidesauniquenumberforeverycharacter,nomatterwhatthe
platform,program,orlanguageis.Unicodeuses2bytestorepresentasinglecharacter.
13)Howarepositiveandnegativenumbersrepresentedinternally?
Ans). Positive numbers are represented in binary using 1s complement notation and negative numbers are
representedbyusing2scomplementnotation.
14)Whatisthedifferencebetween>>and>>>?
Ans).Bothbitwiserightshiftoperator(>>)andbitwisezerofillrightshiftoperator(>>>)areusedtoshiftthe
bits towards right. The difference is that >> will protect the sign bit whereas the >>> operator will not protect the
signbit.Italwaysfills0inthesignbit.
15)Whatarecontrolstatements?
Ans). Control statements are the statements which alter the flow of execution and provide better control to the
[Link].
16)OutofdoWhileandwhilewhichloopisefficient?
Ans).Inado..whileloop,thestatementsareexecutedwithouttestingthecondition,[Link]
[Link]
[Link],[Link]
[Link],whileloopismoveefficientthando..whileloop.
17)Whatisacollection?
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%2
3/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans).[Link]
andjava.util_classes(stack,LinkedList,Vector,etc).
18)WhygotostatementsarenotavailableinJava?
Ans).[Link],ifseveralgotostatements
are used, the programmer would be perplexed while understanding the flow from where to where the control is
jumping.
19)[Link](0)?
Ans).[Link](0)isusedinanymethodtocomeof
theprogram.
20)[Link](0)[Link](1)?
Ans).[Link](0) terminates the program normally. Whereas [Link](1) terminates the program because of
someerrorencounteredintheprogram.
21)[Link],[Link]?
Ans).[Link]
[Link]
[Link],whichbydefaultrepresentsstandardinputdevice,i.e.,
keyboard.
22)Onwhichmemory,arraysarecreatedinJava?
Ans).[Link](
variables,array,objectetc.)iscreatedondynamicmemoryonly.
23)Canyoucallthemain()methodofaclassfromanotherclass?
Ans).Yes,wecancallthemain()[Link]().Atthetimeof
callingthemain()method,weshouldpassastringtypearraytoit.
24)IsStringaclassordatatype?
Ans).[Link],[Link]
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%2
4/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Stringasadatatypealso.
25)Canwecallaclassasadatatype?
Ans).Yes,[Link].
26)Whatisobjectreference?
Ans).[Link]
accessthemembersoftheobject.
27) What is difference between == and equals( ) while comparing [Link] one is
reliable?
Ans).= = operator compares the references of the sting objects. It does not compare the contents of the objects.
equals()[Link],equals()methodshouldbeusedasityields
thecorrectresult.
28)Whatisastringconstantpool?
Ans).[Link]
iscreateddirectly,usingassignmentoperatoras:Strings1=Hello,thenitisstoredinstringconstantpool.
29)Explainthedifferencebetweenthefollowingtwostatements:
[Link]=Hello
[Link]=newString(Hello)
Ans).Inthefirststatement,[Link]
case,[Link],
then it creates another reference to it. If the same object is not available, then it creates another object with the
contentHelloandstoresitintothestringconstantpool.
In the second statement, new operator is used to create the string object in this case, JVM always creates a new
objectwithoutlookinginthestringconstantpool.
30)WhatisthedifferencebetweenStringandStringBufferclasses?
Ans).[Link]
mutable,[Link]
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%2
5/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
[Link].
31)Arethereanyotherclasseswhoseobjectsareimmutalbe?
Ans). Yes, classes like Character, Byte, Integer, Float, Double, Long..called wrapper classes are created as
[Link],BigInteger,BigDecimalarealsoimmutable.
32)WhatisthedifferencebetweenStringBufferandStringBuilderclasses?
Ans). StringBuffer class is synchronized and StringBuilder is not. When the programmer wants to use several
threads, he should use StringBuffer as it gives reliable results . If only one thread is used. StringBuilder is
preferred,asitimprovesexecutiontime.
33)Whatisobjectorientedapproach?
Ans).Object oriented programming approach is a programming methodology to design computer programs using
classesandobjects.
34)Whatisthedifferencebetweenaclassandanobject?
Ans). A class is a model for creating objects and does not exist physically. An object is any thing that exists
[Link].
35)Whatisencapsulation?
Ans).Encapsulationisamechanismwherethedata(varialbes)andthecode(methods)thatactonthedatawillbind
[Link],ifwetakeaclass,[Link],classisbindingthem
[Link].
36)Whatisabstraction?
Ans).Hidingtheunnecessarydatafromtheuserandexposeonlyneededdataisofinteresttotheuser.
[Link],radiator,mechanicalandelectrical
[Link](driver)shouldknowhowtodrivethecaranddoesnotrequireanyknowledgeof
these parts. For example driver is never bothered about how the engine is designed and the internal parts of the
[Link],thecarmanufacturershidethesepartsfromthedriverinaseparatepanel,generallyatthefront.
Exampleinjava:
1
ClassBank{
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%2
6/26
1/11/2015
2
3
4
5
6
7
8
9
10
11
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Privateintaccno;
PrivateStringname;
Privatefloatbalance;
Privatefloatprofit;
Privatefloatloan;
Publicvoiddesplay_to_clerk(){
[Link](Accno=+accno);
[Link](Name=+name);
[Link](Balance=+balance);
}
37)WhatisInheritance?
Ans).Itcreatesnewclassesfromexistingclasses,sothatthenewclasseswillacquireallthefeaturesoftheexisting
classesiscalledinheritance.(or)Acquiringtheallpropertiesfrombaseclasstochildclass.
38)WhatisPolymorphism?
Ans). The word Polymorphism came from two Greek words poly meaning many and morphs meaning
[Link],[Link],wecanuse
a single variable to refer to objects of different types and thus, using that variable we can call the methods of the
[Link].
39) What is the difference between object oriented programming launguages and object
basedprogramminglanguages?
Ans). Object oriented programming languages follow all the features of Object Oriented Programming
System(OOPS).Smalltalk,Simula67,C++,JavaareexamplesforOOPSlanguages.
ObjectbasedprogramminglanguagesfollowallthefeaturesofOOPSexceptInheritance.
For example, JavaScript and VBScript will come under object based programming
languages.
40)Whatishashcode?
Ans).[Link]
calledreferencenumberwhichiscreatedbasedonthelocationoftheobjectinmemory,andisuniqueforallobjects,
exceptforStringobjects.
41)Howcanyoufindthehashcodeofanobject?
Ans).ThehashCode()[Link].
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%2
7/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
42)Canyoudeclareaclassasprivate?
Ans).No, if we declare a class as private, then it is not available to java compiler and hence a compile time error
occurs,butinnerclassescanbedeclaredasprivate.
43)Whenisaconstructorcalled,beforeoraftercreatingtheobject?
Ans).[Link]
[Link],objectcreationiscompleted
theconstructorexecutionisalsocompleted.
44)Whatisthedifferencebetweendefaultconstructorandparameterizedconstructor?
Defaultconstructor
Parameterconstructor
Whendataisnotpassedatthetimeof
creating an object, default constructor
iscalled.
45)Whatisthedifferencebetweenaconstructorandamethod?
Constructors
Methods
Amethodisusedforanygeneralpurpose
processingorcalculations.
46)Whatisconstructoroverloading?
Ans). Writing two or more constructors with the same name but with difference in the parameters is called
[Link].
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%2
8/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
47)Whatareinstancemethods?
Ans).[Link]
,[Link]().
Ex:
48)Whatarestaticmethods?
Ans).Static methods are the methods which do not act upon the instance variables of a class. Static methods are
declaredasstatic.
49)Whatisthedifferencebetweeninstancevariablesandclassvariables(staticvariables)?
Ans).1. An Instance variable is a variable whose separate copy is available to each object. A class variable is a
variablewhosesinglecopyinmemoryissharedbyallobjects.
[Link].
50)WhyinstanceVariablesarenotavailabletostaticmethods?
Ans). After executing static methods, JVM creates the objects. So the instance variables of the objects are not
availabletostaticmethods.
51)IsitpossibletocompileandrunaJavaprogramwithoutwritingmain()method?
Ans).Yes,itispossiblebyusingastaticblockintheJavaprogram.
52)HowareobjectsarepassedtomethodsinJava?
Ans).Premitivedatatypes,objects,evenobjectreferenceseverythingispassedtomethodsusingpassbyvalue
[Link].
53)Whatarefactorymethods?
Ans).A factory method is a method that creates and returns an object to the class to which it belongs. A single
factorymethodreplacesseveralconstructorsintheclassbyacceptingdifferentoptionsfromtheuser,whilecreating
theobject.
54)InhowmanywayscanyoucreateanobjectinJava?
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%2
9/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans).TherearefourwaysofcreatingobjectsinJava:
[Link]
Employeeobj=newEmployee()
Here,wearecreatingEmployeeclassobjectobjusingnewoperator.
[Link]:
NumberFormatobj=[Link]()
Here,wearecreatingNumberFormatobjectusingthefactorymethodgetNumberInstance()
[Link]()[Link],as:
(a) First, store the class name Employee as a string into an object. For this purpose, factory metod
forName()oftheclassClasswillbeuseful:
Classc=[Link](Employee)
[Link].
(b) Next, create another object to the class whose name is in the object c. For this purpose , we need
newInstance()methodoftheclassClassas:
Employeeobj=(Employee)[Link]()
[Link],[Link]
iscalledcloning.
Employeeobj1=newEmployee()
Employeeobj2=(Employee)[Link]()
Earlier,[Link]()methodofObjectclassisusedtoclone
[Link].
55)Whatisobjectgraph?
Ans).Objectgraphisagraphshowingrelationshipbetweendifferentobjectsinmemory.
56)Whatisanonymousinnerclass?
Ans).Itisaninnerclasswhosenameisnotwrittenintheouterclassandforwhichonlyoneobjectiscreated.
57)WhatisInheritance?
Ans).Derivingnewclassesfromexistingclassessuchthatthenewclassesacquireallthefeaturesofexistingclasses
iscalledinheritance.
58)Whysuperclassmembersareavailabletosubclass?
Ans).Because,thesubclassobjectcontainsacopyofsuperclassobject.
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
10/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
59)Whatistheadvantageofinheritance?
Ans).In inheritance a programmer reuses the super class code without rewriting it, in creation of sub classes So,
[Link],theprogrammersproductivityisincreased.
60)WhymultipleinheritanceisnotavailableinJava?
Ans).MultipleinheritanceisnotavailableinJavaforthefollowingreasons:
[Link].
[Link].
[Link].
61)Howmanytypesofinheritancearethere?
Ans). There are two types of inheritances single and multiple. All other types are mere combinations of these
[Link],Javasupportsonlysingleinheritance.
62)Whatiscoercion?
Ans).Coercionistheautomaticconversionbetweendifferentdatatypesdonebythecompiler.
63)Whatisconversion?
Ans).Conversionisanexplicitchangeinthedatatypespecifiedbytheoperator.
64)Whatismethodsignature?
Ans).Methodsignaturerepresentsthemethodnamealongwithmethodparmeters.
65)Whatismethodoverloading?
Ans). Writing two or more methods in the same class in such a way that each mehtod has same name but with
differentmethodsignaturesiscalledmethodoverloading.
66)Whatismethodoverriding?
Ans). Writing two or more methods in super and sub classes such that the methods have same name and same
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
11/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
signatureiscalledmethodoverriding.
MethodOverriding
Writing two or more methods with the same
name and same signatures is called method
overriding.
Method overriding is done in super and sub
classes.
In method overriding method return type should
alsobesame.
JVM decides which method is called depending
onthedatatype(class)oftheobjectusedtocall
themethod.
Methodoverridingisdonewhentheprogrammer
wants
to
provide
a
different
implementation(body)forthesamefeature.
[Link]
class method overrides(replaces) the super class
method.
68)Canyouoverrideprivatemethods?
Ans).No,privatemethodsarenotavailableinthesubclasses,sotheycannotbeoverriden.
69)Canwetakeprivatemethodsandfinalmethodsassame?
Ans).[Link]
theycannotbeoverridden,Butfinalmethodsarevisibletosubclasses,privatemethodsarenot.
(takenfromcommentsbyBHS).
70)Whatisfinal?
Ans).finalkeywordisusedintwoways:
Itisusedtodeclareconstantsas:
FinaldoublePI=3.14159//PIisconstant
Itisusedtopreventinheritanceas:
FinalclassA//subclasstoAcannotbecreated.
71)Whatisthedifferencebetweendynamicpolymorphismandstaticpolymorphism?
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
12/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans). Dynamic polymorphism is the polymorphism existed at runtime. Here, Java compiler does not understand
which method is called at compilation time. Only JVM decides which method is called at runtime. Method
overloadingandmethodoverridingusinginstancemethodsaretheexamplesfordynamicpolymorphism.
Static polymorphism is the polymorphism exhibited at compile time. Here, Java compiler knows which method is
called. Method overloading and method overriding using static methods method overriding using private or final
methodsareexamplesforstaticpolymorphism.
72)Whatisdifferencebetweenprimitivedatatypesandadvanceddatatypes?
Ans).[Link]
not available to handle the primitive data types. In case of advanced data types, methods are available to perform
variousoperations.
73)Whatisimplicitcasting?
Ans).Automatic casting done by the Java compiler internally is called implicit casting . Implicit casting is done to
convertyalowerdatatypeintoahigherdatatype.
74)Whatisexplicitcasting?
Ans).The cating done by the programmer is called explicit cating. Explicit casting is compulsory while converting
fromahigherdatatypetoalowerdatatype.
75)Whatisgeneralizationandspecialization?
Ans). Generalization ia a phenomenon wher a sub class is prompted to a super class, and hence becomes more
[Link]
[Link].
76)Whatiswideningandnarrowing?
Ans).Convertinglowerdatatypeintoahigherdatatypeiscalledwideningandconvertingahigherdatatypeintoa
lower type is called narrowing. Widening is safe and hence even if the programmer does not use cast operator, the
Java compiler does not flag any error. Narrowing is unsafe and hence the programmer should explicitly use cast
operatorinnarrowing.
77)Whichmethodisusedincloning?
Ans).clone()methodofObjectclassisusedincloning.
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
13/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
78)Whatdoyoucalltheinterfacewithoutanymembers?
Ans).[Link]
a special purpose. For example, Clonable([Link]) and Serializable([Link]) are two marking interfaces. Clonable
interface indicates that a particular class objects are cloneable while Serializable interface indicates that a particular
classobjectsareserializable.
79)Whatisabstractmethod?
Ans).[Link]
toperformdifferencetasksdependingontheobjectcallingit.
80)Whatisabstractclass?
Ans).Anabstractclassisaclassthatcontains0ormoreabstractmethods.
81)Howcanyouforceyourprogrammerstoimplementonlythefeaturesofyourclass?
Ans).Bywritinganabstractclassoraninterface.
82)Canyoudeclareaclassasabstractandfinalalso?
Ans).No,[Link]
[Link],botharequitecontradictoryandcannotbeusedforthesameclass.
83)Whatisaninterface?
Ans).Aninterfaceisaspecificationofmethodprototypes,Allthemethodsoftheinterface
arepublicandabstract.
84)Whythemethodsofinterfacearepublicandabstractbydefault?
Ans).Interface methods are public since they should be available to third party vendors to provide implementation.
Theyareabstractbecausetheirimplementationisleftforthirdpartyvendors.
85)Canyouimplementoneinterfacefromanother?
Ans).No,[Link]
interface,sincenoneofthemethodsoftheinterfacecanhavebody.
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
14/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
86)Canyouwriteaclasswithinaninterfae?
Ans).Yes,itispossibletowriteaclasswithinaninterface.
87)Explainaboutinterfaces?
Ans).*Aninterfaceisaspecificationofmethodprototypes,beforeweproceedfurthur,written
intheinterfacewithoutmehtodbodies.
*Aninterfacewillhave0ormoreabstractmethodswhichareallpublicandabstractbydefault.
* An interface can have variables which are public static and final by default. This means all the variables of the
interfaceareconstants.
88)Whatisthedifferencebetweenanabstractclassandaninterface?
Abstractclass
Interface
89)Aprogrammeriswritingthefollowingstatementsinaprogram:
[Link].*
[Link].*
Shouldhewriteboththestatementsinhisprogramorthefirstonwisenough?
Ans). event is a sub package of [Link] package. But, when a package is imported, its sub packages are not
[Link],foreverypackageorsubpackage,aseparateimportstatementshouldbe
[Link],
thenheshouldboththeprecedingstatementsinhisprogram.
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
15/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
90)Howcanyoucallthegarbagecollector?
Ans).Wecancall garbage collector of JVM to delete any unused variables and unreferenced objects from memory
using gc( ) method. This gc( ) method appears in both Runtime and System classes of [Link] package. For
example,wecancallitas:
[Link]()
[Link]().gc()
91)Whatisthedifferencebetweenthefollowingtwostatements.
[Link]
[Link].*
Ans).Instatement1,onlytheAdditionclassofthepackagepackisimportedintotheprogramandinstatement2,all
theclassesandinterfacesofthepackagepackareavailabletotheprogram.
If a programmer wants to import only one class of a package say BufferedReader of [Link] package, we can
[Link]
93)WhatisCLASSPATH?
Ans) . The CLASSPATH is an environment variable that tells the Java compiler where to look for class files to
[Link](JavaArchive)[Link].
94)WhatisaJARfile?
Ans)AJavaArchivefile(JAR)[Link],audiofiles,image
[Link].
95)Whatisthescopeofdefaultacessspecifier?
Ans). Default members are available within the same package, but not outside of the package. So their scope is
packagescope.
96)Whathappensifmain()methodiswrittenwithoutStringargs[]?
Ans).ThecodecompilesbutJVMcannotrunit,asitcannotseethemain()methodwithStringargs[].
97).Whatarecheckedexceptions?
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
16/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans).[Link]
exceptionsthatarecheckedbytheJVMarecalleduncheckedexceptions.
98).WhatisThrowable?
Ans).ThrowableisaclassthatrepresentsallerrorsandexceptionswhichmayoccurinJava.
99).Whichisthesuperclassforallexceptions?
Ans).ExceptionisthesuperclassofallexceptionsinJava.
100).Whatisthedifferencebetweenanexceptionandanerror?
Ans). An exception is an error which can be handled. It means when an exception happens, the programmer can do
[Link],ithappensandtheprogrammercannot
doanything.
101).Whatisthedifferencebetweenthrowsandthrow?
Ans). throws clause is used when the programmer does not want to handle the exception and throw it out of a
[Link] is used when the programmer wants to throw an exception explicitly and wants to handle it
[Link],throwsandthrowarecontracictory.
102).Isitpossibletorethrowexceptions?
Ans).Yes,wecanrethrowanexceptionfromcatchblocktoanotherclasswhereitcanbehandled.
103).Whydoweneedwrapperclasses?
[Link]
oobjectsandthisisneededonInternettomommunicatebetweentwoapplications.
[Link].
104).Whichofthewrapperclassescontainsonlyoneconstructor?(or)Whichofthewrapper
classesdoesnotcontainaconstructorwithStringasparameter?
Ans).Character.
105).Whatisunboxing?
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
17/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans).Convertinganobjectintoitscorrespondingprimitivedatatypeiscalledunboxing.
106).WhathappensifastringlikeHelloispassedtoparseInt()method?
Ans). Ideally a string with an integer value should be passed to parseInt ( ) method. So, on parsing Hello, an
exception called NumberFormatException occurs since the parseInt( ) method cannot convert the given string
Hellointoanintegervalue.
107).Whatisacollectionframework?
Ans).[Link]
[Link].
108).Doesacollectionobjectstorecopiesofotherobjectsortheirreferences?
Ans).ACollectionobjectstoresreferencesofotherobjects.
109).Canyoustoreaprimitivedatatypeintoacollection?
Ans).No,Collectionsstoreonlyobjects.
110).WhatisthedifferencebetweenIteratorandListIterator?
Ans).[Link]
only in forward direction. But Listener can retrieve the elements in forward and backward direction also. So
ListIteratorispreferredtoIterator.
111).WhatisthedifferencebetweenIteratorandEnumeration?
Ans).[Link]
Enumeration methods are difficult to remember. Also Iterator has an option to remove elements from the collection
[Link],IteratorispreferredtoEnumeration.
112).WhatisthedifferencebetweenaStackandLinkedList?
Ans). 1. A Stack is generally used for the purpose of evaluation of expression. A LinkedList is used to store and
retrievedata.
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
18/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
2. Insertion and deletion of elements only from the top of the Stack is possible. Insertion and deletion of elements
fromanywhereispossibleincaseofaLinkedList.
113).WhatisthedifferencebetweenArrayListandVector?
ArrayList
Vector
114).CanyousynchronizetheArrayListobject?
Ans).
Yes,
we
can
use
synchronizedList(
method
to
synchronize
the
ArrayList,
as:[Link](newArrayList())
115).WhatistheloadfactorforaHashMaporHashtable?
Ans).0.75.
116).WhatisthedifferencebetweenHashMapandHashtable?
Ans).
HashMap
HashMapobjectisnotsynchronizedbydefault.
In case of a single thread, using HashMap is
fasterthantheHashtable.
Hashtable
Hashtableobjectissynchronizedbydefault.
In case of multiple threads, using Hashtable is
advisable, with a single thread, Hashtable
becomesslow.
HashMap allows null keys and null values to be Hashtabledoesnotallownullkeysorvalues.
stored.
Iterator in the HashMap is failfast. This means Enumeration for the Hashtable is not failfast.
Iterator will produce exeception if concurrent Thismeansevenifconcurrentupdationsaredone
updatesaremadetotheHashMap.
to Hashtable, there will not be any incorrect
resultsproducedbytheEnumeration.
117).CanyoumakeHashMapsynchronized?
Ans). Yes, we can make HashMap object synchronized using synchronizedMap( ) method as shown here:
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
19/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
[Link](newHashMap())
118).WhatisthedifferencebetweenaSetandaList?
Ans).
Set
List
ASet represents a collection of elements. Order A List represents ordered collection of
oftheelementsmaychangeintheSet.
[Link] preserves the order of elements in
whichtheyareentered.
Setwillnotallowduplicatevaluestobestored.
Listwillallowduplicatevalues.
Accessing elements by their index (position Accessingelementsbyindexispossibleinlists.
number)isnotpossibleincaseofSets.
Setswillnotallownullelements.
Listsallownullelementstobestored.
119).[Link]?
Ans).[Link]
As:
[Link](Thisisnayanimuralidhar)
[Link](Thisisanerror)
120).Whatistheadvantageofstreamconcept..?
Ans). Streams are mainly useful to move data from one place to another place. This concept can be used to receive
datafromaninputdeviceandsenddatatoanoutputdevice.
121).Whatisthedefaultbuffersizeusedbyanybufferedclass?
Ans).512bytes.
122).Whatisserialization?
Ans).[Link]
[Link].
123).Whattypeofvariablescannotbeserialized?
Ans).Staticandtransientvariablescannotbeserialized.
Once the objects are stored into a file, they can be later retrieved and used as and when [Link] is called de
serialization.
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
20/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
124).WhatisIPaddress?
Ans). An IP address is a unique identification number allocated to every computer on a network or Internet. IP
addresscontainssomebyteswhichidentifythenetworkandtheactualcomputerinsidethenetwork.
125).WhatisDNS?
Ans).DomainNamingServiceisaserviceonInternetthatmapstheIPaddresswithcorrespondingwebsitenames.
126).Whatisasocket?
Ans).Asocketisapointofconnecitonbetweenaserverandaclientonanetwork.
127).Whatisportnumber?
Ans).Portnumberiaa2bytenumberwhichisusedtoidentifyasocketuniquely.
128).WhichthreadalwaysrunsinaJavaprogrambydefault?
Ans).[Link]:
1).Singletasking2).Multitasking.
129).Whythreadsarecalledlightweight?
Ans). Threads are lightweight because they utilize minimum resources of the system. This means they take less
memoryandlessprocessortime.
130).Whatisthedifferencebetweensingletaskingandmultitasking?
Ans). Executing only one job at a time is called single tasking. Executing several jobs at a time is called multi
[Link],theprocessortimeiswasted,butinmultitasking,wecanutilizetheprocessortimeinan
optimumway.
131).HowcanyoustopathreadinJava?
Ans).Firstofall,[Link]
[Link]()methodandifitis
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
21/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
true,thethreadexecutesreturnstatementandthenstops.
132).WhatisthedifferencebetweenextendsThreadandimplementsRunnable?Which
oneisadvatageous?
Ans). extends Thread and implements Runnable both are functionally same. But when we write extends Thread,
thereisnoscopetoextendanotherclass,asmultipleinheritanceisnotsupportedinJava.
ClassMyclassextendsThread,AnotherClass//invalid
IfwewriteimplementsRunnable,thenstillthereisscopetoextendanotherclass.
classMyclassextendsAnotherClassimplementsRunnable//valid
This is definitely advantageous when the programmer wants to use threads and also wants to access the features of
anotherclass.
133).Whichmethodisexecutedbythethreadbydefault?
Ans).publicvoidrun()method.
134).WhatisThreadsynchronization?
Ans). When a thread is already acting on an object, preventing any other thread from acting on the same object is
called Thread synchronization or Thread safe The object on which the threads are synchronized is called
[Link](in
multithreading).
135).Whatisthedifferencebetweensynchronizedblockandsynchronizedkeyword?
Ans). Synchronized block is useful to synchronized a block of statements. Synchronized keyword is useful to
synchronizeanentiremethod.
138).WhatisThreaddeadlock?
Ans).[Link]
thread is also waiting for the first thread to release the first object, both the threads will continue waiting forever.
ThisiscalledThreaddeadlock.
139).Whatisthedifferencebetweenthesleep()andwait()methods?
Ans).Boththesleep()andwait()[Link]()
isexecutedinsideasynchronizedblock,[Link]()methodisexecuted,itbreaksthe
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
22/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
synchronizedblock,sothattheobjectlockisremovedanditisavailable.
Generally,sleep()[Link]()isusedinconnectionwithnotify()
ornotifyAll()mehtodsintheradcommunication.
140).Whatisthedefaultpriorityofathread?
Ans).Whenathreadiscreated,bydefaultitsprioritywillbe5.
141).Whatisdemonthread?
Ans). A daemon thread is a thread is a thread that executes continuously. Daemon threads are service providers for
[Link].
142).Whatisthreadlifecycle?
Ans). A thread is created using new Thread( ) statement and is executed by start( ) method. The thread enters
runnablestateandwhensleep()orwait()methodsareusedorwhenthethreadisblockedonI/O,itthengoesinto
not runnable state. From not runnable state, the thread comes back to the runnable state and continues running
the statements. The thread dies when it comes out of run( ) mehtod . These state thransitions of a thread are called
lifecycleofathread.
143).Whatisthedifferencebetweenawindowandaframe?
Ans).Awindowisaframewithoutanybordersandtitle,whereasaframecontainsbordersandtitle.
144).Whatiseventdelegationmodel?
Ans).Eventdelegationmodelrepresentsthatwhenaneventisgeneratedbytheuseronacomponent,itisdelegatedto
a listener interface and the listener calls a mehtod in response to the event. Finally , the event is handled by the
method.
145).WhichmodelisusedtoprovideactionstoAWTcomponents?
Ans).Eventdelegationmodel.
146).Whatisanadapterclass?
Ans).Anadapterclassisanimplementationclassofalistenerwhichcontainsallmethodsimplementedwithempty
body. For example, WindowAdapter is an adapter class of WindowListener interface. Adapter classes reduce
overheadonprogrammingwhileworkingwithlistenerinterfaces.
147).Whatisanonymousinnerclass?
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
23/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans). Anonymous inner class is an inner class whose name is not mentioned, and for which only one object is
created.
148).Whatisthedefaultlayoutinaframe?
Ans).BorderLayout.
149).Whatisthedefaultlayoutinanapplet?
Ans).FlowLayout.
150).WhatareJavaFoundationclasses?
Ans). Java Foundation classes (JFC) represented a class library developed in pure Java which is an extension to
AWT.
151).DiscussabouttheMVCarchitectureinJFC/swing?
Ans).[Link].
View represents its appearance and controller is a mediater between the model and the [Link] represents the
separationofmodelofanobjectfromitsviewandhowitiscontrolled.
152).Whatarethevariouswindowpanesavailableinswing?
Ans).Thereare4windowpanes:Glasspane,Rootpane,Layeredpane,andContentpane.
153).Wherearethebordersavailableinswing?
Ans).[Link].
154).Whatisanapplet?
Ans).AnappletrepresentsJavabytecodeembeddedinawebpage.
155).Whatisappletlifecycle?
Ans).Anappletisbornwithinit()methodandstartsfunctioningwithstart()[Link],thestop()
methodiscalledandtoterminatetheappletcompletelyfrommemory,thedestroy()[Link]
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
24/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
is terminated, we should reload the HTML page again to get the applet start once again from init( ) method. This
cyclicwayofexecutingthemethodsiscalledappletlifecycle.
156).Wherearetheappletsexecuted?
Ans).Appletsareexecutedbyaprogramcalledappletenginewhichissimilartovirtualmachinethatexistsinsidethe
webbrowseratclientside.
157).WhatisHotJava?
Ans).HotJavaisthefirstappletenabledbrowserdevelopedinJavatosupportrunningofapplets.
158).WhichtagisusedtoembedanappletintoaHTMLpage?
Ans).<applet>tagisusedtoinsertanappletintoHTMLpage.
[Link]
[Link]:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<applet
codebase=codebaseURL
archive=archiveList
code=appletFile...or...object=serializedApplet
alt=alternateText
name=appletInstanceName
width=pixels
height=pixels
align=alignment
vspace=pixels
hspace=pixels
legacy_lifestyle=boolean>
<paramname=appletAttribute1value=value1>
<paramname=appletAttribute2value=value2>
alternateHTML
159).Whatisagenerictype?
Ans).[Link].
160).Whaiiserasure?
Ans).CreatingnongenericversionofagenerictypebytheJavacompileriscallederasure.
161).Whatisautoboxing?
Ans).Autoboxingreferstocreatingobjectsandstoringprimitivedatatypesautomaticallybythecompiler.
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
25/26
1/11/2015
164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
162).WhatisJDBC?
Ans).JDBC(JavaDatabaseConnectivity)isanAPIthatisusefultowriteJavaprogramstoconnecttoanydatabase,
retreivethedatafromthedatabaseandutilizethedatainaJavaprogram.
163).Whatisadatabasedriver?
Ans). A database driver is a set ofclasses and interfaces, written according to JDBC API to communicate with a
database.
164).Howcanyouregisteradriver?
Ans).Toregisteradatabasedriver,wecanfollowoneofthe4options:
Bycreatinganobjecttodriverclass
[Link]()method
[Link]()method
ByusingSystemclassgetProperty()method.
data:text/htmlcharset=utf8,%3Ch3%20class%3D%22posttitle%22%20style%3D%22margin%3A%200px%200px%2010px%3B%20padding%3A%200px%
26/26