164 Java Interview Questions by Nageswara Rao - JAVAbyNATARAJ
164 Java Interview Questions by Nageswara Rao - JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
JAVAbyNATARAJ
[Link],Ameerpeta,Hyderabad.
Home CoreJava Jdbc Servlets Jsp Struts Hibernate Download ContactUs
SEARCHTHISBLOG
Search
164JavaInterviewQuestionsbyNageswara
Rao SUBSCRIBEVIAEMAIL
Back to Top
[Link] 1/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
Ifyouarealreadyattendedanyinterviewsonjavayoumighthavefaced
[Link]
queries.
1)Whypointersareeliminatedfromjava? POPULARPOSTS
Ans)
DurgaSoft SCJP Notes Part-I
[Link]. Download
[Link],forexample,whenweaddtwopointers,theprogram
crashersimmediately. Back to Top
DurgaSoft OCJP(SCJP) Notes Part-II Download
[Link] 2/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
[Link],harmfulprogramslikeVirusandotherhackingprograms
JavaSynchronizedblockandmethodindetail.. ClickHere
[Link],pointershavebeeneliminatedfromjava.
2)Whatisthedifferencebetweenafunctionandamethod?
Core Java notes by [Link] from
Ans).[Link]
Durgasoft
we have methods. This means whenever a function is written in java, it should be written inside
[Link]++,wecanwritethefunctionsinsideaswellasoutsidetheclass.
SoinC++,theyarecalledmemberfunctionsandnotmethods.
Advaced Java Notes by [Link]
from Ameerpeta
3)WhichpartofJVMwillallocatethememoryforajavaprogram?
Ans). Class loader subsystem of JVM will allocate the necessary memory needed by the java
program.
164 Java Interview Questions by
4). which algorithm is used by garbage collector to remove the unused Nageswara Rao
variablesorobjectsfrommemory?
5).Howcanyoucallthegarbagecollector?
Download Spring material from
Ans).Garbage collector is automatically invoked when the program is being run. It can be also DurgaSoft
calledbycallinggc()methodofRuntimeclassorSystemclassinJava.
6)WhatisJITCompiler?
Web Services Notes by Nataraj sir
from Sathya Technologies
Ans).JITcompileristhepartofJVMwhichincreasesthespeedofexecutionofaJavaprogram.
7)WhatisanAPIdocument?
Spring notes by [Link] from Sathya
Back to Top
Technologies
[Link] 3/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans).[Link],a
JavaSynchronizedblockandmethodindetail.. ClickHere
product, or a technology. API document is helpful for the user to understand how to use the
softwareortechnology.
Ans).#include directive makes the compiler go to the C/C++ standard library and copy the code
from the header files into the program. As a result, the program size increases, thus wasting
memoryandprocessorstime.
import statement makes the JVM go to the Java standard library, execute the code there , and
[Link],nocodeiscopiedandhencenowasteofmemoryor
[Link]#include.
9)Whatisthedifferencebetweenprint()andprintln()method?
Ans).Both methods are used to display the results on the monitor. print() method displays the BLOGARCHIVE
resultandthenretainsthecursorinthesameline,[Link]()displays
2016 (2)
theresultandthenthrowsthecursortothenextline.
2015 (6)
2014 (37)
10)WhathappensifStringargs[]isnotwritteninmain()method?
2013 (18)
2011 (86)
Publicstaticvoidmain() 2010 (17)
2009 (17)
ThecodewillcompilebutJVMcannotrunthecodebecauseitcannotrecognizethemain()asthe
December (1)
[Link]
November (1)
formain()methodwithstringtypearrayasparameter.
August (1)
[Link] 4/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
May (8)
12)WhatisaUnicodesystem?
Ans).Unicodesystemisanencodingstandardthatprovidesauniquenumberforeverycharacter,
nomatterwhattheplatform,program,orlanguageis.Unicodeuses2bytestorepresentasingle
character.
13)Howarepositiveandnegativenumbersrepresentedinternally?
Ans). Positive numbers are represented in binary using 1s complement notation and negative
numbersarerepresentedbyusing2scomplementnotation.
14)Whatisthedifferencebetween>>and>>>?
Ans).Bothbitwiserightshiftoperator(>>)andbitwisezerofillrightshiftoperator(>>>)are
[Link]>>willprotectthesignbitwhereasthe
>>>operatorwillnotprotectthesignbit.Italwaysfills0inthesignbit. LABELS
ActionServlet (1) Advantages (1) AdvJavaBooks (7) Ajax
(1) AOP (1) Architecture (2) ArrayList (1) Arrays (4)
15)Whatarecontrolstatements? Atlassian (2) Basic Java Programs (1) Basic JavaPrograms
(1) BufferedReader (2) ClassNotes (2) Coding Standards
Ans).Control statements are the statements which alter the flow of execution and provide better (1) Collections (20) Con guration (3)
Ans) . Goto statements lead to confusion for a programmer. Especially in a large program, if
several goto statements are used, the programmer would be perplexed while understanding the GOOGLE+FOLLOWERS
flowfromwheretowherethecontrolisjumping. MuralidharNayani
Addtocircles
19)[Link](0)?
Ans).[Link](0)isusedinany
286havemeincircles Viewall
methodtocomeoftheprogram.
20)[Link](0)[Link](1)?
Ans). [Link](0) terminates the program normally. Whereas [Link](1) terminates the
programbecauseofsomeerrorencounteredintheprogram.
21)[Link],[Link]?
Ans).[Link]
[Link]
whereas [Link] is used to display error messages and [Link] represents InputStream
object,whichbydefaultrepresentsstandardinputdevice,i.e.,keyboard.
Back to Top
22)Onwhichmemory,arraysarecreatedinJava?
[Link] 6/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
Ans).[Link]
Javaeverything(variables,array,objectetc.)iscreatedondynamicmemoryonly.
23)Canyoucallthemain()methodofaclassfromanotherclass?
Ans).Yes,wecancallthemain()[Link]()
.Atthetimeofcallingthemain()method,weshouldpassastringtypearraytoit.
24)IsStringaclassordatatype?
Ans).String is a class in [Link] package. But in Java, all classes are also considered as data
[Link].
25)Canwecallaclassasadatatype?
Ans).Yes,[Link].
26)Whatisobjectreference?
Ans).Object reference is a unique hexadecimal number representing the memory address of the
[Link].
Ans).==[Link]
of the objects. equals ( ) method compares the contents. While comparing the strings, equals( )
methodshouldbeusedasityieldsthecorrectresult.
[Link] 7/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans). Sring constant pool is a separate block of memory where the string objects are held by
JavaSynchronizedblockandmethodindetail.. ClickHere
[Link],usingassignmentoperatoras:Strings1=Hello,thenit
isstoredinstringconstantpool.
29)Explainthedifferencebetweenthefollowingtwostatements:
[Link]=Hello
[Link]=newString(Hello)
Ans).In the first statement, assignment operator is used to assign the string literal to the String
[Link],JVMfirstofallcheckswhetherthesameobjectisalreadyavailableinthe
[Link],[Link]
available, then it creates another object with the content Hello and stores it into the string
constantpool.
Inthesecondstatement,newoperatorisusedtocreatethestringobjectinthiscase,JVMalways
createsanewobjectwithoutlookinginthestringconstantpool.
30)WhatisthedifferencebetweenStringandStringBufferclasses?
Ans). String class objects are immutable and hence their contents cannot be modified.
StringBuffer class objects are mutable, so they can be modified. Moreover the methods that
[Link]
inStringBufferclass.
31)Arethereanyotherclasseswhoseobjectsareimmutalbe?
Ans).Yes,classeslikeCharacter,Byte,Integer,Float,Double,Long..calledwrapperclassesare
[Link],BigInteger,BigDecimalarealsoimmutable.
32)WhatisthedifferencebetweenStringBufferandStringBuilderclasses?
[Link] 8/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
[Link],asitimprovesexecutiontime.
JavaSynchronizedblockandmethodindetail.. ClickHere
33)Whatisobjectorientedapproach?
Ans).Objectorientedprogrammingapproachisaprogrammingmethodologytodesigncomputer
programsusingclassesandobjects.
34)Whatisthedifferencebetweenaclassandanobject?
Ans).[Link]
[Link].
35)Whatisencapsulation?
Ans).Encapsulation is a mechanism where the data(varialbes) and the code(methods) that act on
[Link],ifwetakeaclass,wewritethevariablesandmethodsinsidethe
[Link],[Link].
36)Whatisabstraction?
Ans).Hidingtheunnecessarydatafromtheuserandexposeonlyneededdataisofinteresttothe
user.
A good example for abstraction is a car. Any car will have some parts like engine, radiator,
mechanical and electrical equipment etc. The user of the ca r (driver) should know how to drive
the car and does not require any knowledge of these parts. For example driver is never bothered
about how the engine is designed and the internal parts of the engine. This is why, the car
manufacturershidethesepartsfromthedriverinaseparatepanel,generallyatthefront.
Exampleinjava:
1 ClassBank{ ?
2 Privateintaccno; Back to Top
3 PrivateStringname;
4 Privatefloatbalance;
5 Privatefloatprofit;
[Link] 9/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
5 Privatefloatprofit;
6 Privatefloatloan; JavaSynchronizedblockandmethodindetail.. ClickHere
7 Publicvoiddesplay_to_clerk(){
8 [Link](Accno=+accno);
9 [Link](Name=+name);
10 [Link](Balance=+balance);
11 }
12 }
37)WhatisInheritance?
Ans). It creates new classes from existing classes, so that the new classes will acquire all the
features of the existing classes is called inheritance. (or) Acquiring the all properties from base
classtochildclass.
38)WhatisPolymorphism?
Ans). The word Polymorphism came from two Greek words poly meaning many and
[Link],polymorphismrepresentstheabilitytoassumeseveraldifferent
[Link],wecanuseasinglevariabletorefertoobjectsofdifferenttypesandthus,
using that variable we can call the methods of the different objects. Thus a method call can
performdifferenttasksdependingonthetypeoftheobject.
39)Whatisthedifferencebetweenobjectorientedprogramminglaunguages
andobjectbasedprogramminglanguages?
Ans). Object oriented programming languages follow all the features of Object Oriented
ProgrammingSystem(OOPS).Smalltalk,Simula67,C++,JavaareexamplesforOOPSlanguages.
ObjectbasedprogramminglanguagesfollowallthefeaturesofOOPSexcept
Inheritance. For example, JavaScript and VBScript will come under object
basedprogramminglanguages.
40)Whatishashcode?
Back to Top
[Link] 10/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans).[Link]
JavaSynchronizedblockandmethodindetail.. ClickHere
number is also called reference number which is created based on the location of the object in
memory,andisuniqueforallobjects,exceptforStringobjects.
41)Howcanyoufindthehashcodeofanobject?
Ans).The hashCode( ) method of Object class in [Link] useful to find the hash
codeofanobject.
42)Canyoudeclareaclassasprivate?
Ans).No, if we declare a class as private, then it is not available to java compiler and hence a
compiletimeerroroccurs,butinnerclassescanbedeclaredasprivate.
43)Whenisaconstructorcalled,beforeoraftercreatingtheobject?
Ans). A Constructor is called concurrently when the object creation is going on. JVM first
allocates memory for the object and then executes the constructor to initialize the instance
[Link],objectcreationiscompletedtheconstructorexecutionisalsocompleted.
Defaultconstructor Parameterconstructor
[Link] 11/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
45)Whatisthedifferencebetweenaconstructorandamethod?
JavaSynchronizedblockandmethodindetail.. ClickHere
Constructors Methods
46)Whatisconstructoroverloading?
Ans).Writingtwoormoreconstructorswiththesamenamebutwithdifferenceintheparameters
[Link].
47)Whatareinstancemethods?
Ans).Instancemethodsare the methods which act on the instance variables of the class. To call
theinstancemethods,[Link]().
Ex:
1 doublex=[Link](); ?
48)Whatarestaticmethods?
Ans). Static methods are the methods which do not act upon the instance variables of a class.
Staticmethodsaredeclaredasstatic.
49) What is the difference between instance variables and class Back to Top
variables(staticvariables)?
[Link] 12/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
Ans).[Link]
variableisavariablewhosesinglecopyinmemoryissharedbyallobjects.
2. Instance variables are created in the objects on heap memory. Class variables are stored on
methodarea.
50)WhyinstanceVariablesarenotavailabletostaticmethods?
Ans).After executing static methods, JVM creates the objects. So the instance variables of the
objectsarenotavailabletostaticmethods.
51)IsitpossibletocompileandrunaJavaprogramwithoutwritingmain()
method?
Ans).Yes,itispossiblebyusingastaticblockintheJavaprogram.
52)HowareobjectsarepassedtomethodsinJava?
Ans). Premitive data types, objects, even object references every thing is passed to methods
[Link]
methods.
53)Whatarefactorymethods?
Ans). A factory method is a method that creates and returns an object to the class to which it
[Link]
optionsfromtheuser,whilecreatingtheobject.
54)InhowmanywayscanyoucreateanobjectinJava?
[Link] 13/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
55)Whatisobjectgraph?
Ans).Objectgraphisagraphshowingrelationshipbetweendifferentobjectsinmemory.
56)Whatisanonymousinnerclass?
Ans).Itisaninnerclasswhosenameisnotwrittenintheouterclassandforwhichonlyoneobject
iscreated.
Back to Top
57)WhatisInheritance?
[Link] 14/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
Ans).Derivingnewclassesfromexistingclassessuchthatthenewclassesacquireallthefeatures
ofexistingclassesiscalledinheritance.
58)Whysuperclassmembersareavailabletosubclass?
Ans).Because,thesubclassobjectcontainsacopyofsuperclassobject.
59)Whatistheadvantageofinheritance?
Ans).In inheritance a programmer reuses the super class code without rewriting it, in creation of
subclassesSo,[Link],theprogrammersproductivityis
increased.
60)WhymultipleinheritanceisnotavailableinJava?
Ans).MultipleinheritanceisnotavailableinJavaforthefollowingreasons:
[Link].
[Link].
[Link].
61)Howmanytypesofinheritancearethere?
Ans). There are two types of inheritances single and multiple. All other types are mere
[Link],Javasupportsonlysingleinheritance.
62)Whatiscoercion?
Ans).Coercionistheautomaticconversionbetweendifferentdatatypesdonebythecompiler.
Back to Top
63)Whatisconversion?
[Link] 15/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
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
namebutwithdifferentmethodsignaturesiscalledmethodoverloading.
66)Whatismethodoverriding?
Ans). Writing two or more methods in super and sub classes such that the methods have same
nameandsamesignatureiscalledmethodoverriding.
MethodOverloading MethodOverriding
Writing two or more methods with the same Writing two or more methods with the same
name but with different signatures is called name and same signatures is called method
methodoverloading. overriding.
Methodoverloadingisdoneinthesameclass. Method overriding is done in super and sub
classes.
Inmethodoverloading,methodreturntypecan In method overriding method return type
besameordifferent. shouldalsobesame.
JVM decides which method is called JVM decides which method is called
depending on the difference in the method dependingonthedatatype(class)oftheobject
signatures. usedtocallthemethod. Back to Top
Method overloading is done when the Method overriding is done when the
[Link] 16/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
68)Canyouoverrideprivatemethods?
Ans).No,privatemethodsarenotavailableinthesubclasses,sotheycannotbeoverriden.
69)Canwetakeprivatemethodsandfinalmethodsassame?
Ans).[Link]
similarity is that they cannot be overridden, But final methods are visible to subclasses, private
methodsarenot.
(takenfromcommentsbyBHS).
70)Whatisfinal?
Ans).finalkeywordisusedintwoways:
Itisusedtodeclareconstantsas:
FinaldoublePI=3.14159//PIisconstant
Itisusedtopreventinheritanceas:
FinalclassA//subclasstoAcannotbecreated.
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 overloading and method overriding using instance methods are the Back to Top
examplesfordynamicpolymorphism.
[Link] 17/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Static polymorphism is the polymorphism exhibited at compile time. Here, Java compiler knows
JavaSynchronizedblockandmethodindetail.. ClickHere
which method is called. Method overloading and method overriding using static methods method
overridingusingprivateorfinalmethodsareexamplesforstaticpolymorphism.
72)Whatisdifferencebetweenprimitivedatatypesandadvanceddatatypes?
Ans).[Link].
Also methods are not available to handle the primitive data types. In case of advanced data types,
methodsareavailabletoperformvariousoperations.
73)Whatisimplicitcasting?
Ans).Automatic casting done by the Java compiler internally is called implicit casting . Implicit
castingisdonetoconvertyalowerdatatypeintoahigherdatatype.
74)Whatisexplicitcasting?
Ans).The cating done by the programmer is called explicit cating. Explicit casting is compulsory
whileconvertingfromahigherdatatypetoalowerdatatype.
75)Whatisgeneralizationandspecialization?
Ans).Generalization ia a phenomenon wher a sub class is prompted to a super class, and hence
[Link]
where a super class is narrowed down to a sub class. Specialization needs narrowing or down
casting.
76)Whatiswideningandnarrowing?
Ans).Convertinglowerdatatypeintoahigherdatatypeiscalledwideningandconvertingahigher
[Link] Back to Top
[Link] 18/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
does not use cast operator, the Java compiler does not flag any error. Narrowing is unsafe and
JavaSynchronizedblockandmethodindetail.. ClickHere
hencetheprogrammershouldexplicitlyusecastoperatorinnarrowing.
77)Whichmethodisusedincloning?
Ans).clone()methodofObjectclassisusedincloning.
78)Whatdoyoucalltheinterfacewithoutanymembers?
Ans).[Link]
the class objects for a special purpose. For example, Clonable([Link]) and Serializable([Link])
[Link]
whileSerializableinterfaceindicatesthataparticularclassobjectsareserializable.
79)Whatisabstractmethod?
Ans).An abstract method is a method without method body. An abstract method is written when
thesamemethodhastoperformdifferencetasksdependingontheobjectcallingit.
80)Whatisabstractclass?
Ans).Anabstractclassisaclassthatcontains0ormoreabstractmethods.
81) How can you force your programmers to implement only the features of
yourclass?
Ans).Bywritinganabstractclassoraninterface.
82)Canyoudeclareaclassasabstractandfinalalso?
[Link] 19/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
83)Whatisaninterface?
Ans).Aninterfaceisaspecificationofmethodprototypes,Allthemethodsof
theinterfacearepublicandabstract.
84)Whythemethodsofinterfacearepublicandabstractbydefault?
Ans).Interfacemethodsarepublicsincetheyshouldbeavailabletothirdpartyvendorstoprovide
[Link].
85)Canyouimplementoneinterfacefromanother?
Ans).No,[Link]
doneagaininaninterface,sincenoneofthemethodsoftheinterfacecanhavebody.
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
variablesoftheinterfaceareconstants.
88)Whatisthedifferencebetweenanabstractclassandaninterface?
Abstractclass Interface
Back to Top
An abstract class is written when there are Aninterfaceiswrittenwhenallthefeaturesare
some common features shared by all the implementeddifferentlyindifferentobjects.
[Link] 20/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
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 automatically imported into a program. So, for every package or sub package, a
separate import statement should be written. Hence if the programmer wants the classes and
interfaces of both the [Link] and [Link] packages, then he should both the preceding
statementsinhisprogram.
90)Howcanyoucallthegarbagecollector?
Ans).WecancallgarbagecollectorofJVMtodeleteanyunusedvariablesandunreferencedobjects
frommemoryusinggc()[Link]()methodappearsinbothRuntimeandSystemclasses
[Link],wecancallitas:
[Link]() Back to Top
[Link]().gc()
[Link] 21/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
91)Whatisthedifferencebetweenthefollowingtwostatements.
[Link]
[Link].*
Ans).Instatement1,onlytheAdditionclassofthepackagepackisimportedintotheprogramand
instatement2,alltheclassesandinterfacesofthepackagepackareavailabletotheprogram.
If a programmer wants to import only one class of a package say BufferedReader of [Link]
package,[Link]
93)WhatisCLASSPATH?
Ans).TheCLASSPATHisanenvironmentvariablethattellstheJavacompilerwheretolookfor
class files to import. CLASSPATH is generally set to a directory or a JAR(Java Archive)file. Set
theClasspathafterinstallingjava.
94)WhatisaJARfile?
Ans) A Java Archive file (JAR) is a file that contains compressed version of several .class files,
audio files, image files or directories. JAR file is useful to bundle up several files related to a
projectandusethemeasily.
95)Whatisthescopeofdefaultacessspecifier?
Ans). Default members are available within the same package, but not outside of the package. So
theirscopeispackagescope.
96)Whathappensifmain()methodiswrittenwithoutStringargs[]?
Ans). The code compiles but JVM cannot run it, as it cannot see the main( ) method with String Back to Top
args[].
[Link] 22/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
97).Whatarecheckedexceptions?
Ans).TheexceptionsthatarecheckedatcompilationtimebytheJavacompilerarecalledchecked
[Link].
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
[Link],
ithappensandtheprogrammercannotdoanything.
101).Whatisthedifferencebetweenthrowsandthrow?
Ans).throwsclauseisusedwhentheprogrammerdoesnotwanttohandletheexceptionandthrow
it out of a method. throw clause is used when the programmer wants to throw an exception
[Link],throwsandthrowarecontracictory.
102).Isitpossibletorethrowexceptions?
Ans).Yes,wecanrethrowanexceptionfromcatchblocktoanotherclasswhereitcanbehandled.
[Link] 23/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
104).Whichofthewrapperclassescontainsonlyoneconstructor?(or)Which
ofthewrapperclassesdoesnotcontainaconstructorwithStringasparameter
?
Ans).Character.
105).Whatisunboxing?
Ans).Convertinganobjectintoitscorrespondingprimitivedatatypeiscalledunboxing.
106).WhathappensifastringlikeHelloispassedtoparseInt()method?
Ans).IdeallyastringwithanintegervalueshouldbepassedtoparseInt()[Link],onparsing
Hello,anexceptioncalledNumberFormatExceptionoccurssincetheparseInt()methodcannot
convertthegivenstringHellointoanintegervalue.
107).Whatisacollectionframework?
Ans).[Link]
[Link].
108).Doesacollectionobjectstorecopiesofotherobjectsortheirreferences?
Ans).ACollectionobjectstoresreferencesofotherobjects.
[Link] 24/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
110).WhatisthedifferencebetweenIteratorandListIterator?
Ans).[Link]
[Link]
[Link].
111).WhatisthedifferencebetweenIteratorandEnumeration?
Ans).[Link]
easy to follow and Enumeration methods are difficult to remember. Also Iterator has an option to
[Link],Iteratorispreferred
toEnumeration.
112).WhatisthedifferencebetweenaStackandLinkedList?
Ans). 1. A Stack is generally used for the purpose of evaluation of expression. A LinkedList is
usedtostoreandretrievedata.
2. Insertion and deletion of elements only from the top of the Stack is possible. Insertion and
deletionofelementsfromanywhereispossibleincaseofaLinkedList.
113).WhatisthedifferencebetweenArrayListandVector?
ArrayList Vector
ArrayListobjectisnotsynchronizedbydefault Vectorobjectissynchronizedbydefault.
Incase of a single thread, using ArrayList is In case of multiple threads, using Vector is
fasterthantheVector. advisable. With a single thread, Vector
becomesslow. Back to Top
ArrayList increases its size every time by 50 Vector increases its size every time by
[Link] 25/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
percent(half). doublingit.
JavaSynchronizedblockandmethodindetail.. ClickHere
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 Hashtable
HashMap object is not synchronized by Hashtableobjectissynchronizedbydefault.
default.
In case of a single thread, using HashMap is Incaseofmultiplethreads,usingHashtableis
fasterthantheHashtable. advisable, with a single thread, Hashtable
becomesslow.
HashMap allows null keys and null values to Hashtabledoesnotallownullkeysorvalues.
bestored.
Iterator in the HashMap is failfast. This EnumerationfortheHashtableis not failfast.
means Iterator will produce exeception if This means even if concurrent updations are
concurrentupdatesaremadetotheHashMap. done to Hashtable, there will not be any
incorrectresultsproducedbytheEnumeration.
117).CanyoumakeHashMapsynchronized?
Ans).Yes,wecanmakeHashMapobjectsynchronizedusingsynchronizedMap()methodasshown
here:[Link](newHashMap()) Back to Top
[Link] 26/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
118).WhatisthedifferencebetweenaSetandaList?
JavaSynchronizedblockandmethodindetail.. ClickHere
Ans).
Set List
A Set represents a collection of elements. A List represents ordered collection of
OrderoftheelementsmaychangeintheSet. [Link] preserves the order of elements
inwhichtheyareentered.
Set will not allow duplicate values to be Listwillallowduplicatevalues.
stored.
Accessing elements by their index (position Accessing elements by index is possible in
number)isnotpossibleincaseofSets. lists.
Setswillnotallownullelements. Listsallownullelementstobestored.
119).[Link]?
Ans). Both are used to display messages on the monitor. [Link] is used to display normal
messages
As:
[Link](Thisisnayanimuralidhar)
[Link](Thisisanerror)
120).Whatistheadvantageofstreamconcept..?
Ans).[Link]
usedtoreceivedatafromaninputdeviceandsenddatatoanoutputdevice.
121).Whatisthedefaultbuffersizeusedbyanybufferedclass?
Ans).512bytes.
[Link] 27/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans).[Link]
JavaSynchronizedblockandmethodindetail.. ClickHere
[Link].
123).Whattypeofvariablescannotbeserialized?
Ans).Staticandtransientvariablescannotbeserialized.
Oncetheobjectsarestoredintoafile,[Link]
iscalleddeserialization.
124).WhatisIPaddress?
Ans).AnIPaddressisauniqueidentificationnumberallocatedtoeverycomputeronanetworkor
[Link]
thenetwork.
125).WhatisDNS?
Ans).DomainNamingServiceisaserviceonInternetthatmapstheIPaddresswithcorresponding
websitenames.
126).Whatisasocket?
Ans).Asocketisapointofconnecitonbetweenaserverandaclientonanetwork.
127).Whatisportnumber?
Ans).Portnumberiaa2bytenumberwhichisusedtoidentifyasocketuniquely.
128).WhichthreadalwaysrunsinaJavaprogrambydefault?
Back to Top
[Link] 28/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans). main thread. A thread represents execution of statements. The way the statements are
JavaSynchronizedblockandmethodindetail.. ClickHere
executedisoftwotypes:1).Singletasking2).Multitasking.
129).Whythreadsarecalledlightweight?
Ans).[Link]
theytakelessmemoryandlessprocessortime.
130).Whatisthedifferencebetweensingletaskingandmultitasking?
Ans).[Link]
called multi tasking. In single tasking, the processor time is wasted, but in multi tasking, we can
utilizetheprocessortimeinanoptimumway.
131).HowcanyoustopathreadinJava?
Ans).Firstofall,[Link]
wants to stop the thread. We should store trueinto the variable. The status of the variable is
checkedintherun()methodandifitistrue,thethreadexecutesreturnstatementandthenstops.
Ans). extends Thread and implements Runnable both are functionally same. But when we write
extendsThread,thereisnoscopetoextendanotherclass,asmultipleinheritanceisnotsupported
inJava.
ClassMyclassextendsThread,AnotherClass//invalid
IfwewriteimplementsRunnable,thenstillthereisscopetoextendanotherclass.
classMyclassextendsAnotherClassimplementsRunnable//valid
Thisisdefinitelyadvantageouswhentheprogrammerwantstousethreadsandalsowantstoaccess
thefeaturesofanotherclass. Back to Top
[Link] 29/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
133).Whichmethodisexecutedbythethreadbydefault?
JavaSynchronizedblockandmethodindetail.. ClickHere
Ans).publicvoidrun()method.
134).WhatisThreadsynchronization?
Ans).Whenathreadisalreadyactingonanobject,preventinganyotherthreadfromactingonthe
sameobjectiscalledThreadsynchronizationorThreadsafeTheobjectonwhichthethreadsare
synchronized is called synchronized object. Thread synchronization is recommended when
multiplethreadsareusedonthesameobject(inmultithreading).
Ans).[Link]
usefultosynchronizeanentiremethod.
138).WhatisThreaddeadlock?
Ans).Whenathreadhaslockedanobjectandwaitingforanotherobjecttobereleasedbyanother
[Link] the other thread is also waiting for the first thread to release the first object, both the
[Link].
139).Whatisthedifferencebetweenthesleep()andwait()methods?
Ans).Boththesleep()andwait()methodsareusedtosuspendathreadexecutionforaspecified
time. When sleep( ) is executed inside a synchronized block, the object is still under lock. When
wait()methodisexecuted,itbreaksthesynchronizedblock,sothattheobjectlockisremovedand
itisavailable.
Generally, sleep( ) is used for making a thread to wait for some time. But wait( ) is used in
connectionwithnotify()ornotifyAll()mehtodsintheradcommunication. Back to Top
[Link] 30/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
140).Whatisthedefaultpriorityofathread?
JavaSynchronizedblockandmethodindetail.. ClickHere
Ans).Whenathreadiscreated,bydefaultitsprioritywillbe5.
141).Whatisdemonthread?
Ans). A daemon thread is a thread is a thread that executes continuously. Daemon threads are
[Link].
142).Whatisthreadlifecycle?
Ans). A thread is created using new Thread( ) statement and is executed by start( ) method. The
threadentersrunnablestateandwhensleep()orwait()methodsareusedorwhenthethreadis
blockedonI/O,[Link],thethreadcomes
back to the runnable state and continues running the statements. The thread dies when it comes
outofrun()[Link].
143).Whatisthedifferencebetweenawindowandaframe?
Ans). A window is a frame without any borders and title, whereas a frame contains borders and
title.
144).Whatiseventdelegationmodel?
Ans). Event delegation model represents that when an event is generated by the user on a
component,itisdelegatedtoalistenerinterfaceandthelistenercallsamehtodinresponsetothe
[Link],theeventishandledbythemethod.
145).WhichmodelisusedtoprovideactionstoAWTcomponents?
Ans).Eventdelegationmodel.
146).Whatisanadapterclass?
Back to Top
[Link] 31/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans). An adapter class is an implementation class of a listener which contains all methods
JavaSynchronizedblockandmethodindetail.. ClickHere
implemented with empty body. For example, WindowAdapter is an adapter class of
[Link] classes reduce overhead on programming while working with
listenerinterfaces.
147).Whatisanonymousinnerclass?
Ans). Anonymous inner class is an inner class whose name is not mentioned, and for which only
oneobjectiscreated.
148).Whatisthedefaultlayoutinaframe?
Ans).BorderLayout.
149).Whatisthedefaultlayoutinanapplet?
Ans).FlowLayout.
150).WhatareJavaFoundationclasses?
Ans).JavaFoundationclasses(JFC)representedaclasslibrarydevelopedinpureJavawhichisan
extensiontoAWT.
151).DiscussabouttheMVCarchitectureinJFC/swing?
Ans).[Link]
of the component. View represents its appearance and controller is a mediater between the model
and the [Link] represents the separation of model of an object from its view and how it is
controlled.
[Link] 32/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Ans).Thereare4windowpanes:Glasspane,Rootpane,Layeredpane,andContentpane.
JavaSynchronizedblockandmethodindetail.. ClickHere
153).Wherearethebordersavailableinswing?
Ans).[Link].
154).Whatisanapplet?
Ans).AnappletrepresentsJavabytecodeembeddedinawebpage.
155).Whatisappletlifecycle?
Ans).Anappletisbornwithinit()methodandstartsfunctioningwithstart()[Link]
applet, the stop( ) method is called and to terminate the applet completely from memory, the
destroy()[Link],weshouldreloadtheHTMLpageagain
togettheappletstartonceagainfrominit()[Link]
calledappletlifecycle.
156).Wherearetheappletsexecuted?
Ans). Applets are executed by a program called applet engine which is similar to virtual machine
thatexistsinsidethewebbrowseratclientside.
157).WhatisHotJava?
Ans).HotJavaisthefirstappletenabledbrowserdevelopedinJavatosupportrunningofapplets.
158).WhichtagisusedtoembedanappletintoaHTMLpage?
Ans).<applet>tagisusedtoinsertanappletintoHTMLpage.
[Link].
[Link]: Back to Top
1 <applet ?
2 codebase=codebaseURL
[Link] 33/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
2 codebase=codebaseURL
3 archive=archiveList JavaSynchronizedblockandmethodindetail.. ClickHere
4 code=appletFile...or...object=serializedApplet
5 alt=alternateText
6 name=appletInstanceName
7 width=pixels
8 height=pixels
9 align=alignment
10 vspace=pixels
11 hspace=pixels
12 legacy_lifestyle=boolean>
13 <paramname=appletAttribute1value=value1>
14 <paramname=appletAttribute2value=value2>
15 alternateHTML
16 </applet>
159).Whatisagenerictype?
Ans).[Link].
160).Whaiiserasure?
Ans).CreatingnongenericversionofagenerictypebytheJavacompileriscallederasure.
161).Whatisautoboxing?
Ans). Auto boxing refers to creating objects and storing primitive data types automatically by the
compiler.
162).WhatisJDBC?
Ans). JDBC (Java Database Connectivity) is an API that is useful to write Java programs to
connecttoanydatabase,retreivethedatafromthedatabaseandutilizethedatainaJavaprogram.
163).Whatisadatabasedriver?
Back to Top
Ans). A database driver is a set of classes and interfaces, written according to JDBC API to
communicatewithadatabase.
[Link] 34/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
164).Howcanyouregisteradriver?
Ans).Toregisteradatabasedriver,wecanfollowoneofthe4options:
Bycreatinganobjecttodriverclass
[Link]()method
[Link]()method
ByusingSystemclassgetProperty()method.
YoucandownloadalltheseinterviewquestionsinasinglepdffileJava
[Link].
ReferenceBooks:
CoreJAVA:AnIntegratedApproach1Edition
CoreJava:AdvancedFeatures(Volume2)8Edition
CoreJavaServerFaces3Edition
PostedbyMuralidharNayaniatFriday,August14,20096Comments
Labels:CoreJava,InterviewQuestions
6Comments JAVAbyNATARAJ
1 Login
Jointhediscussion
[Link] 35/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JustgoogleditandIfoundfollowingresult
JavaSynchronizedblockandmethodindetail.. ClickHere
TakeyournormalListobject
PassthatListliobjecttoSet[Linenumber22]=>SofinallywehaveSetobject
inourhand,justpassthiscurrentSetobjectasargumenttoArrayList,sowe
gotnewListobjectli2withoutduplicate
ButifyouwouldliketopreservetheorderofdatauseLinkedHashSetrather
HashSet
packagejava4s
[Link]
[Link]
[Link]
seemore
1 Reply Share
HIBalaji,[Link]
[Link]..
Reply Share
patil3yearsago
sirifacedfollowingquestionininterview
1)listacceptstheduplicatevaluesthenhowmakelistbehavelikeSet([Link]
shouldnotbeacceptduplicate.)
2)SetnotacceptduplicatevaluesthenhowmakeSetbehavelikeList([Link]
shouldbeaccepttheduplicate)
Reply Share
Back to Top
Mdhar GeekDude >patil 3yearsago
HiPatil,sorryforthedelay.
1),TomakeListtonottoacceptduplicatesweshouldoverrideequals
[Link] 36/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
1),TomakeListtonottoacceptduplicatesweshouldoverrideequals
JavaSynchronizedblockandmethodindetail.. ClickHere
andhashCodemethodsandyouhavetocompareeachelementbefore
youinsertintoListobject.
2).TomakeSettoallowduplicates,weshouldnotoverridetheequals
andhashCodemethodsanddon'tcomparethesetobjects.
ihopethiswillgiveyouclarity.
Reply Share
BHS3yearsago
Q.67Methodoverloadingcanbedoneinsameclassaswellassubclass.
Also,sinceJava1.5thethereturntypeofoverriddenmethodcanbesameor
[Link]
methodcanreturnanobjectofthesametypeastheclass.
Q.69iswrong...[Link]
similarityisthattheycannotbeoverriden,Butfinalmethodsarevisibleto
subclasses,privatemethodsarenot.
Q.111IteratorsarefailfastwhereasEnumerationarefailsafe.
Reply Share
Thanksforyourvaluablepoints..TheAnswerisupdatedbyyourname.
Reply Share
ALSOONJAVABYNATARAJ
Whypublicstaticvoidmain(String HowtoIterateorTraverseaMapin
args[]) Java
4comments3yearsago 1comment3yearsago
JagannathKaleVerynice...! EyalGolanIfyouuseSONAR,it
wouldwarnyouofusingkeySet
[Link]'sbest
Back to Top
Variableargumentorvarargsin [Link]
Java SathyaTechnologies
[Link] 37/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Java SathyaTechnologies
2comments3yearsago 2comments4yearsago
JavaSynchronizedblockandmethodindetail.. ClickHere
MdharyouareWelcome..:) NVPRASADRockStaryouonlysir
injavaentireameerpet.
[Link] BasicStrutsLoginApplication
DurgaSoftSCJPNotesPartIDownload
WebDevelopmentTips,Tutorials&Books [Link]
What are the Different types of DurgaSoft OCJP(SCJP) Notes PartII
ABOUTAUTHOR
FormBeansinStruts? Download
MuralidharNayani How ActionServlet acting as a
Hi this is Muralidhar, i am FrontController Core Java notes by [Link] from
living in Chennai. I have Strutsconfigurationfile Durgasoft
been working in Java and Struts [Link] in
JEE technologies. I like to share the java Advaced Java Notes by [Link] from
Detail
programs and materials from different Ameerpeta
StrutsDispatchActionExampleApplication
institutesandfreeeBookstodownload.
Struts LookupDispatchAction Example 164 Java Interview Questions by
Viewmycompleteprofile Application
NageswaraRao
SimpleStrutsprogramUsingTiles
Simple Application using DispatchAction SpringAOP&[Link]
andTilesinStruts
Back to Top
[Link].
[Link] 38/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
JavaSynchronizedblockandmethodindetail.. ClickHere
Back to Top
[Link] 39/39