100% found this document useful (1 vote)
624 views39 pages

164 Java Interview Questions by Nageswara Rao - JAVAbyNATARAJ

java interview

Uploaded by

muralikrishna221
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
624 views39 pages

164 Java Interview Questions by Nageswara Rao - JAVAbyNATARAJ

java interview

Uploaded by

muralikrishna221
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

JavaSynchronizedblockandmethodindetail.. ClickHere

JAVAbyNATARAJ
LearnCoreJavaandadvancedconceptsinsimplesteps.ThisblogismaintainedbyNatarazsirstudentsfromDurgaSoftandSathyaTech,Ameerpeta,Hyderabad.
Home CoreJava Jdbc Servlets Jsp Struts Hibernate Download ContactUs

SEARCHTHISBLOG

Search
164JavaInterviewQuestionsbyNageswara
Rao SUBSCRIBEVIAEMAIL

>>FRIDAY,AUGUST14,2009 Enter your email address:


Subscribe
Tweet Like 100 41
Delivered by FeedBurner
Dr.R.NageswaraRaohasgivensomeoftheJavainterviewquestionsinhis
CoreJavaIntegratedApproachbook.Thesearethequestionsfrequently
askedinJavainterviews.GothroughttheseQuestionsthiswouldbehelpful
toyou..

Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 1/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

JavaSynchronizedblockandmethodindetail.. ClickHere

Ifyouarealreadyattendedanyinterviewsonjavayoumighthavefaced
mostofthequestionsgivenbelow.Pleaseleaveacommentifyouhaveany
queries.
1)Whypointersareeliminatedfromjava? POPULARPOSTS

Ans)
DurgaSoft SCJP Notes Part-I
1.Pointersleadtoconfusionforaprogrammer. Download

2.Pointersmaycrashaprogrameasily,forexample,whenweaddtwopointers,theprogram
crashersimmediately. Back to Top
DurgaSoft OCJP(SCJP) Notes Part-II Download

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 2/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

3.Pointersbreaksecurity.Usingpointers,harmfulprogramslikeVirusandotherhackingprograms
JavaSynchronizedblockandmethodindetail.. ClickHere
canbedeveloped.Becauseoftheabovereasons,pointershavebeeneliminatedfromjava.

2)Whatisthedifferencebetweenafunctionandamethod?
Core Java notes by Mr.Ratan from
Ans).Amethodisafunctionthatiswritteninaclass.Wedonothavefunctionsinjavainstead
Durgasoft
we have methods. This means whenever a function is written in java, it should be written inside
theclassonly.ButifwetakeC++,wecanwritethefunctionsinsideaswellasoutsidetheclass.
SoinC++,theyarecalledmemberfunctionsandnotmethods.
Advaced Java Notes by Mr.Nataraj
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?

Ans).Garbagecollectorusesmanyalgorithmsbutthemostcommonlyusedalgorithmismarkand Spring AOP & MVC notes by


sweep. Mr.Sekhar sir

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 Mr.Nataraz from Sathya
Back to Top
Technologies

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 3/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

Ans).AnAPIdocumentisa.htmlfilethatcontainsdescriptionofallthefeaturesofasoftwar,a
JavaSynchronizedblockandmethodindetail.. ClickHere
product, or a technology. API document is helpful for the user to understand how to use the
softwareortechnology.

8)Whatisthedifferencebetween#includeandimportstatement? What is lazy loading in Hibernate?

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
substitutetheresultintotheprogram.Here,nocodeiscopiedandhencenowasteofmemoryor
processorstime.soimportisanefficientmechanismthan#include.

9)Whatisthedifferencebetweenprint()andprintln()method?

Ans).Both methods are used to display the results on the monitor. print() method displays the BLOGARCHIVE
resultandthenretainsthecursorinthesameline,nexttotheendoftheresult.println()displays
2016 (2)
theresultandthenthrowsthecursortothenextline.
2015 (6)

2014 (37)
10)WhathappensifStringargs[]isnotwritteninmain()method?
2013 (18)

Ans).Whenmain()methodiswrittenwithoutStringargs[]as: 2012 (29)

2011 (86)
Publicstaticvoidmain() 2010 (17)

2009 (17)
ThecodewillcompilebutJVMcannotrunthecodebecauseitcannotrecognizethemain()asthe
December (1)
methodfromwhereitshouldstartexecutionoftheJavaprogram.RememberJVMalwayslooks
November (1)
formain()methodwithstringtypearrayasparameter.
August (1)

11)Whatisthedifferencebetweenfloatanddouble? 164 Java Interview Questions by Back to Top


Nageswara Rao

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 4/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

Ans). Float can represent up to 7 digitsJavaSynchronizedblockandmethodindetail..


accurately after decimal point, where as double can July (1)
ClickHere
representupto15digitsaccuratelyafterdecimalpoint. June (5)

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
usedtoshiftthebitstowardsright.Thedifferenceisthat>>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)

controltotheprogrammerontheflowofexecution.Theyareusefultowritebetterandcomplex ConnectionPooling (1) CoreJava (67)


CoreJavaBooks (10) CSV File (1) CVS (2) DAO (1)
programs. Database (1) DataStructure (1) Decorative (1)
Designpatterns (6) Developer (1) Differences (2)
Downloads (55) DurgaSir Notes (2)
16)OutofdoWhileandwhilewhichloopisefficient?
DurgaSoft (6) eBooks (42) Eclipse (1)
Examples (5) Exceptions (1) File I/O Operations (1) File
Ans).Inado..whileloop,thestatementsareexecutedwithouttestingthecondition,thefirsttime. Operations (2) FishEye (1) Frameworks (6) Generics
From the second time only the condition is observed. This means that the programmer does not (2) HashMap (2) HeadFirst (5) Hibernate (16)
HibernateBooks (3) How To (2) Html (2) Html5 (1)
havecontrolrightfromthebeginningofitsexecution.Inawhileloop,theconditionistestedfirst Back IO
Installations (1) Interview Questions (13) to Top
Package (14) IOC (1) j2ee (7) java (32) Java 5
Features (4) Java Programs (2) Java Standards (1) java.io

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html jdbc 5/39


2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

andthenonly the statements are executed.JavaSynchronizedblockandmethodindetail..


This means it provides better control right from the (1) java.util (1) JavaBeans (1) JavaScript (1) JavaTips (1) jdbc
ClickHere
(13) JIRA (1) jQuery (1) JS (1) Jsp (7) JSTL (2) KVR Sir (1)
beginning.Hence,whileloopismoveefficientthando..whileloop. List (1) Maven (1) MS Access (2) mvc (7) MyEclipse (4)
Nataraz Sir Notes (4) Normalization (1) OCJP (6) Oracle
(1) Others (1) Prepared Statement (1) Products (1)
17)Whatisacollection? programs (6) Projects (1) Promotions (1) RealTime_Tips
(4) Re ection (1) RegEx (1) SathyaTech (1) Scanner (2)
scjp (5) Sekhar sir Notes (6) Server (1) Servlets (9)
Ans). A collection represents a group of elements like integer values or objects. Examples for Settings (1) Spring (6) SQL (1) Statements (2) Static
Import (1) Streams (1) Strings (3) Struts 1.2 (29)
collectionsarearraysandjava.util_classes(stack,LinkedList,Vector,etc). Struts2 (1) StrutsBooks (2) Synchronization (1)
Synchronized (1) Threads (3) Tomcat (3) Tools (1) Util
pack (5) Var-Args (2) weblogic (3) WebServices (3)
18)WhygotostatementsarenotavailableinJava? WSAD (2) XML (1)

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)WhatisthedifferencebetweenreturnandSystem.exit(0)?

Ans).Returnstatementisusedinsideamethodtocomeoutofit.System.exit(0)isusedinany
286havemeincircles Viewall
methodtocomeoftheprogram.

20)WhatisthedifferencebetweenSystem.out.exit(0)andSystem.exit(1)?

Ans). System.exit(0) terminates the program normally. Whereas System.exit(1) terminates the
programbecauseofsomeerrorencounteredintheprogram.

21)WhatisthedifferencebetweenSystem.out,System.errandSystem.in?

Ans).System.outandSystem.errbothrepresentthemonitorbydefaultandhencecanbeusedto
senddataorresultstothemonitor.ButSystem.outisusedtodisplaynormalmessagesandresults
whereas System.err is used to display error messages and System.in represents InputStream
object,whichbydefaultrepresentsstandardinputdevice,i.e.,keyboard.
Back to Top
22)Onwhichmemory,arraysarecreatedinJava?

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 6/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

JavaSynchronizedblockandmethodindetail.. ClickHere
Ans).ArraysarecreatedondynamicmemorybyJVM.Thereisnoquestionofstaticmemoryin
Javaeverything(variables,array,objectetc.)iscreatedondynamicmemoryonly.

23)Canyoucallthemain()methodofaclassfromanotherclass?

Ans).Yes,wecancallthemain()methodofaclassfromanotherclassusingClassname.main()
.Atthetimeofcallingthemain()method,weshouldpassastringtypearraytoit.
24)IsStringaclassordatatype?

Ans).String is a class in java.lang package. But in Java, all classes are also considered as data
types.SowecantakeStringasadatatypealso.

25)Canwecallaclassasadatatype?

Ans).Yes,aclassisalsocalleduserdefineddatatype.Thisisbecauseausecandreateaclass.

26)Whatisobjectreference?

Ans).Object reference is a unique hexadecimal number representing the memory address of the
object.Itisusefultoaccessthemembersoftheobject.

27) What is difference between == and equals( ) while comparing


strings.whichoneisreliable?

Ans).==operatorcomparesthereferencesofthestingobjects.Itdoesnotcomparethecontents
of the objects. equals ( ) method compares the contents. While comparing the strings, equals( )
methodshouldbeusedasityieldsthecorrectresult.

28)Whatisastringconstantpool? Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 7/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

Ans). Sring constant pool is a separate block of memory where the string objects are held by
JavaSynchronizedblockandmethodindetail.. ClickHere
JVM.Ifastingobjectiscreateddirectly,usingassignmentoperatoras:Strings1=Hello,thenit
isstoredinstringconstantpool.

29)Explainthedifferencebetweenthefollowingtwostatements:
1.Strings=Hello
2.Strings=newString(Hello)

Ans).In the first statement, assignment operator is used to assign the string literal to the String
variables.Inthiscase,JVMfirstofallcheckswhetherthesameobjectisalreadyavailableinthe
stringconstantpol.Ifitisavailable,thenitcreatesanotherreferencetoit.Ifthesameobjectisnot
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
directlymanipulatedataoftheobjectarenotavailableinStringclass.Suchmethodsareavailable
inStringBufferclass.

31)Arethereanyotherclasseswhoseobjectsareimmutalbe?

Ans).Yes,classeslikeCharacter,Byte,Integer,Float,Double,Long..calledwrapperclassesare
createdasimmutable.ClasseslikeClass,BigInteger,BigDecimalarealsoimmutable.

32)WhatisthedifferencebetweenStringBufferandStringBuilderclasses?

Ans).StringBufferclassissynchronizedandStringBuilderisnot.Whentheprogrammerwantsto Back to Top


useseveralthreads,heshoulduseStringBufferasitgivesreliableresults.Ifonlyonethreadis

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 8/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

used.StringBuilderispreferred,asitimprovesexecutiontime.
JavaSynchronizedblockandmethodindetail.. ClickHere

33)Whatisobjectorientedapproach?

Ans).Objectorientedprogrammingapproachisaprogrammingmethodologytodesigncomputer
programsusingclassesandobjects.

34)Whatisthedifferencebetweenaclassandanobject?

Ans).Aclassisamodelforcreatingobjectsanddoesnotexistphysically.Anobjectisanything
thatexistsphysically.Boththeclassesandobjectscontainvariablesandmethods.

35)Whatisencapsulation?

Ans).Encapsulation is a mechanism where the data(varialbes) and the code(methods) that act on
thedatawillbindtogether.Forex,ifwetakeaclass,wewritethevariablesandmethodsinsidethe
class.Thus,classisbindingthemtogether.Soclassisanexampleforencapsultion.

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;
http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 9/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
5 Privatefloatprofit;
6 Privatefloatloan; JavaSynchronizedblockandmethodindetail.. ClickHere
7 Publicvoiddesplay_to_clerk(){
8 System.out.println(Accno=+accno);
9 System.out.println(Name=+name);
10 System.out.println(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
morphsmeaningforms.Thus,polymorphismrepresentstheabilitytoassumeseveraldifferent
forms.Inprogramming,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

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 10/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

Ans).HashcodeisuniqueidentificationnumberallotedtotheobjectsbytheJVM.Thishashcode
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 java.lang.packageis 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
variables.Bythetime,objectcreationiscompletedtheconstructorexecutionisalsocompleted.

44) What is the difference between default constructor and parameterized


constructor?

Defaultconstructor Parameterconstructor

Defaultconstructorisusefultoinitializeall Parameterized constructor is useful to


objectswithsamedata. initializeeachobjectwithdifferentdata.
Default constructor does not have any Parameterized constructor will have 1 or
parameters. moreparameters
When data is not passed at the time of Whendataispassedat the time of creating
creating an object, default constructor is an object parameterized constructor is
Back to Top
called. called.

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 11/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

45)Whatisthedifferencebetweenaconstructorandamethod?
JavaSynchronizedblockandmethodindetail.. ClickHere

Constructors Methods

Aconstructorisusedtoinitializetheinstance A method is used for any general purpose


variablesofaclass. processingorcalculations.
A constructors name and class name should Amethodsnameandclassnamecanbesame
besame. ordifferent.
Aconstructoriscalledatthetimeofcreating A method can be called after creating the
object. object.
Aconstructoriscalledonlyonceperobject. A method can be called several times on the
object.

46)Whatisconstructoroverloading?

Ans).Writingtwoormoreconstructorswiththesamenamebutwithdifferenceintheparameters
iscalledconstructoroverloading.Suchconstructorsareusefultoperformdifferenttasks.

47)Whatareinstancemethods?

Ans).Instancemethodsare the methods which act on the instance variables of the class. To call
theinstancemethods,weshouldusetheformobjectname.methodname().
Ex:

1 doublex=obj.sum(); ?

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)?

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 12/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

JavaSynchronizedblockandmethodindetail.. ClickHere
Ans).1.AnInstancevariableisavariablewhoseseparatecopyisavailabletoeachobject.Aclass
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
usingpassbyvalueorcallbyvalueconcept.Thismeanstheirbitbybitcopyispassestothe
methods.

53)Whatarefactorymethods?

Ans). A factory method is a method that creates and returns an object to the class to which it
belongs.Asinglefactorymethodreplacesseveralconstructorsintheclassbyacceptingdifferent
optionsfromtheuser,whilecreatingtheobject.

54)InhowmanywayscanyoucreateanobjectinJava?

Ans).TherearefourwaysofcreatingobjectsinJava: Back to Top


1.Usingnewoperator

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 13/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

Employeeobj=newEmployee() JavaSynchronizedblockandmethodindetail.. ClickHere


Here,wearecreatingEmployeeclassobjectobjusingnewoperator.
2.Usingfactorymethods:
NumberFormatobj=NumberFormat.getNumberInstance()
Here,wearecreatingNumberFormatobjectusingthefactorymethodgetNumberInstance(
)
3.UsingnewInstance()method.Hereweshouldfollowtowsteps,as:
(a) First, store the class name Employee as a string into an object. For this purpose,
factorymetodforName()oftheclassClasswillbeuseful:
Classc=Class.forName(Employee)
WeshouldnotethatthereisaclasswiththenameClassinjava.langpackage.
(b)Next,createanotherobjecttotheclasswhosenameisintheobjectc.Forthispurpose,
weneednewInstance()methodoftheclassClassas:
Employeeobj=(Employee)c.newInstance()
4.Bycloninganalreadyavailableobject,wecancreateanotherobject.Creatingexactcopyof
anexistingobjectiscalledcloning.
Employeeobj1=newEmployee()
Employeeobj2=(Employee)obj1.clone()
Earlier, we created obj2 by cloning the Employee object obj1.clone( ) method of Object
class is used to clone object.We should note that there is a class by the name Object in
java.langpackage.

55)Whatisobjectgraph?

Ans).Objectgraphisagraphshowingrelationshipbetweendifferentobjectsinmemory.

56)Whatisanonymousinnerclass?

Ans).Itisaninnerclasswhosenameisnotwrittenintheouterclassandforwhichonlyoneobject
iscreated.
Back to Top
57)WhatisInheritance?

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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,developingtheclassesbecomesveryeasy.Hence,theprogrammersproductivityis
increased.

60)WhymultipleinheritanceisnotavailableinJava?

Ans).MultipleinheritanceisnotavailableinJavaforthefollowingreasons:

1.ItleadstoconfusionforaJavaprogram.
2.Theprogrammercanachievemultipleinheritancebyusinginterfaces.
3.Theprogrammercanachievemultipleinheritancebyrepeatedlyusingsingleinheritance.

61)Howmanytypesofinheritancearethere?

Ans). There are two types of inheritances single and multiple. All other types are mere
combinationsofthesetwo.However,Javasupportsonlysingleinheritance.

62)Whatiscoercion?

Ans).Coercionistheautomaticconversionbetweendifferentdatatypesdonebythecompiler.
Back to Top
63)Whatisconversion?

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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.

67) What is the difference between method overloading and


methodoverriding?

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

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 16/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

programmer wants to extend the already programmer wants to provide a different


JavaSynchronizedblockandmethodindetail.. ClickHere
availablefeatures. implementation(body)forthesamefeature.
Method overloading is code refinement. Same Method overriding is code replacement. The
methodisrefinedtoperformadifferenttask. subclassmethodoverrides(replaces)thesuper
classmethod.

68)Canyouoverrideprivatemethods?

Ans).No,privatemethodsarenotavailableinthesubclasses,sotheycannotbeoverriden.

69)Canwetakeprivatemethodsandfinalmethodsassame?

Ans).NO.Bothmethodsaredifferent.Afinalmethodisnotthesameasaprivatemethod.Theonly
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.

71) What is the difference between dynamic polymorphism and static


polymorphism?

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.

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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).Primitivedatatypesrepresentsinglevalues.Advanceddatatypesrepresentagroupofvalues.
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
becomesmoregeneral.Generalizationneedswideningorupcasting.Specializationisphenomenon
where a super class is narrowed down to a sub class. Specialization needs narrowing or down
casting.

76)Whatiswideningandnarrowing?

Ans).Convertinglowerdatatypeintoahigherdatatypeiscalledwideningandconvertingahigher
datatypeintoalowertypeiscallednarrowing.Wideningissafeandhenceeveniftheprogrammer Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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).Aninterfacewithoutanymembersiscalledmarkinginterfaceortagginginterface.Itmarks
the class objects for a special purpose. For example, Clonable(java.lang) and Serializable(java.io)
aretwomarkinginterfaces.Clonableinterfaceindicatesthataparticularclassobjectsarecloneable
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?

Ans).No,abstractclassneedssubclasses.finalkeywordrepresentssubclasseswhichcannot Back to Top


becreated.So,botharequitecontradictoryandcannotbeusedforthesameclass.

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 19/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

JavaSynchronizedblockandmethodindetail.. ClickHere
83)Whatisaninterface?

Ans).Aninterfaceisaspecificationofmethodprototypes,Allthemethodsof
theinterfacearepublicandabstract.

84)Whythemethodsofinterfacearepublicandabstractbydefault?
Ans).Interfacemethodsarepublicsincetheyshouldbeavailabletothirdpartyvendorstoprovide
implementation.Theyareabstractbecausetheirimplementationisleftforthirdpartyvendors.

85)Canyouimplementoneinterfacefromanother?

Ans).No,wecantimplementinganinterfacemeanswritingbodyforthemethods.Thiscannotbe
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.

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 20/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

objects. JavaSynchronizedblockandmethodindetail.. ClickHere


Whenanabstractclassiswritten,itistheduty An interface is written when the programmer
oftheprogrammertoprovidesubclassestoit. wants to leave the implementation to the third
partyvendors.
An abstract class contains some abstract Aninterfacecontainsonlyabstractmethods.
methodsandalsosomeconcretemethods.
An abstract class contain instance variables Aninterfacecannotcontaininstancevariables.
also. Itcontainsonlyconstants.
All the abstract methods of the abstract class All the (abstract) methods of the interface
shouldbeimplementedinitssubclasses. should be implemented in its implementation
classes.
Abstract class is declared by using the Interface is declared using the keyword
keywordabstract. interface.

89)Aprogrammeriswritingthefollowingstatementsinaprogram:
1.importjava.awt.*
2.importjava.awt.event.*
Shouldhewriteboththestatementsinhisprogramorthefirstonwisenough?

Ans). event is a sub package of java.awt 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 java.awt and java.awt.event packages, then he should both the preceding
statementsinhisprogram.

90)Howcanyoucallthegarbagecollector?

Ans).WecancallgarbagecollectorofJVMtodeleteanyunusedvariablesandunreferencedobjects
frommemoryusinggc()method.Thisgc()methodappearsinbothRuntimeandSystemclasses
ofjava.langpackage.Forexample,wecancallitas:
System.gc() Back to Top

Runtime.getRuntime().gc()

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 21/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

JavaSynchronizedblockandmethodindetail.. ClickHere
91)Whatisthedifferencebetweenthefollowingtwostatements.

1.importpack.Addition
2.importpack.*

Ans).Instatement1,onlytheAdditionclassofthepackagepackisimportedintotheprogramand
instatement2,alltheclassesandinterfacesofthepackagepackareavailabletotheprogram.
If a programmer wants to import only one class of a package say BufferedReader of java.io
package,wecanwriteimportjava.io.BufferedReader

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[].

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 22/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

JavaSynchronizedblockandmethodindetail.. ClickHere
97).Whatarecheckedexceptions?

Ans).TheexceptionsthatarecheckedatcompilationtimebytheJavacompilerarecalledchecked
exceptions.TheexceptionsthatarecheckedbytheJVMarecalleduncheckedexceptions.

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
programmercandosomethingtoavoidanyharm.Butanerrorisanerrorwhichcannotbehandled,
ithappensandtheprogrammercannotdoanything.

101).Whatisthedifferencebetweenthrowsandthrow?

Ans).throwsclauseisusedwhentheprogrammerdoesnotwanttohandletheexceptionandthrow
it out of a method. throw clause is used when the programmer wants to throw an exception
explicitlyandwantstohandleitusingcatchblock.Hence,throwsandthrowarecontracictory.

102).Isitpossibletorethrowexceptions?

Ans).Yes,wecanrethrowanexceptionfromcatchblocktoanotherclasswhereitcanbehandled.

103).Whydoweneedwrapperclasses? Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 23/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

1.Theyconvertprimitivedatatypesint JavaSynchronizedblockandmethodindetail.. ClickHere


oobjectsandthisisneededonInternettomommunicatebetweentwoapplications.
2.Theclassesinjava.utilpackagehandleonlyobjectsandhencewrapperclasseshelpinthiscase
also.

104).Whichofthewrapperclassescontainsonlyoneconstructor?(or)Which
ofthewrapperclassesdoesnotcontainaconstructorwithStringasparameter
?

Ans).Character.

105).Whatisunboxing?

Ans).Convertinganobjectintoitscorrespondingprimitivedatatypeiscalledunboxing.

106).WhathappensifastringlikeHelloispassedtoparseInt()method?

Ans).IdeallyastringwithanintegervalueshouldbepassedtoparseInt()method.So,onparsing
Hello,anexceptioncalledNumberFormatExceptionoccurssincetheparseInt()methodcannot
convertthegivenstringHellointoanintegervalue.

107).Whatisacollectionframework?

Ans).Acollectionframeworkisaclasslibrarytohandlegroupsofobjects.Collectionframework
isimplementedinjava.util.package.

108).Doesacollectionobjectstorecopiesofotherobjectsortheirreferences?

Ans).ACollectionobjectstoresreferencesofotherobjects.

109).Canyoustoreaprimitivedatatypeintoacollection? Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 24/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

Ans).No,Collectionsstoreonlyobjects. JavaSynchronizedblockandmethodindetail.. ClickHere

110).WhatisthedifferencebetweenIteratorandListIterator?

Ans).Bothareusefultoretreiveelementsfromacollection.Iteratorcanretrievetheelements
onlyinforwarddirection.ButListenercanretrievetheelementsinforwardandbackwarddirection
also.SoListIteratorispreferredtoIterator.

111).WhatisthedifferencebetweenIteratorandEnumeration?

Ans).Bothareusefultoretreiveelementsfromacollection.Iteratorhasmethodswhosenamesare
easy to follow and Enumeration methods are difficult to remember. Also Iterator has an option to
removeelementsfromthecollectionwhichisnotavailableinEnumeration.So,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

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 25/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

percent(half). doublingit.
JavaSynchronizedblockandmethodindetail.. ClickHere

114).CanyousynchronizetheArrayListobject?

Ans). Yes, we can use synchronizedList( ) method to synchronize the ArrayList, as:
Collections.synchronizedList(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:Collections.synchronizedMap(newHashMap()) Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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. elements.List 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).WhatisthedifferencebetweenSystem.outandSystem.err?

Ans). Both are used to display messages on the monitor. System.out is used to display normal
messages
As:
System.out.println(Thisisnayanimuralidhar)
System.err.println(Thisisanerror)

120).Whatistheadvantageofstreamconcept..?

Ans).Streamsaremainlyusefultomovedatafromoneplacetoanotherplace.Thisconceptcanbe
usedtoreceivedatafromaninputdeviceandsenddatatoanoutputdevice.

121).Whatisthedefaultbuffersizeusedbyanybufferedclass?

Ans).512bytes.

122).Whatisserialization? Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 27/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

Ans).Serializationistheprocessofstoringobjectcontentsintoafile.Theclasswhoseobjectsare
JavaSynchronizedblockandmethodindetail.. ClickHere
storedinthefileshouldimplementserializableinterfaceofjava.io.package.

123).Whattypeofvariablescannotbeserialized?

Ans).Staticandtransientvariablescannotbeserialized.

Oncetheobjectsarestoredintoafile,theycanbelaterretrievedandusedasandwhenneeded.This
iscalleddeserialization.

124).WhatisIPaddress?

Ans).AnIPaddressisauniqueidentificationnumberallocatedtoeverycomputeronanetworkor
Internet.IPaddresscontainssomebyteswhichidentifythenetworkandtheactualcomputerinside
thenetwork.

125).WhatisDNS?

Ans).DomainNamingServiceisaserviceonInternetthatmapstheIPaddresswithcorresponding
websitenames.

126).Whatisasocket?

Ans).Asocketisapointofconnecitonbetweenaserverandaclientonanetwork.

127).Whatisportnumber?

Ans).Portnumberiaa2bytenumberwhichisusedtoidentifyasocketuniquely.

128).WhichthreadalwaysrunsinaJavaprogrambydefault?
Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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).Threadsarelightweightbecausetheyutilizeminimumresourcesofthesystem.Thismeans
theytakelessmemoryandlessprocessortime.

130).Whatisthedifferencebetweensingletaskingandmultitasking?

Ans).Executingonlyonejobatatimeiscalledsingletasking.Executingseveraljobsatatimeis
called multi tasking. In single tasking, the processor time is wasted, but in multi tasking, we can
utilizetheprocessortimeinanoptimumway.

131).HowcanyoustopathreadinJava?

Ans).Firstofall,weshouldcreateabooleantypevariablewhichstoresfalse.Whentheuser
wants to stop the thread. We should store trueinto the variable. The status of the variable is
checkedintherun()methodandifitistrue,thethreadexecutesreturnstatementandthenstops.

132). What is the difference between extends Thread and implements


Runnable?Whichoneisadvatageous?

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

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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).

135). What is the difference between synchronized block and synchronized


keyword?

Ans).Synchronizedblockisusefultosynchronizedablockofstatements.Synchronizedkeywordis
usefultosynchronizeanentiremethod.

138).WhatisThreaddeadlock?

Ans).Whenathreadhaslockedanobjectandwaitingforanotherobjecttobereleasedbyanother
thread.and the other thread is also waiting for the first thread to release the first object, both the
threadswillcontinuewaitingforever.ThisiscalledThreaddeadlock.

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

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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
serviceprovidersforotherthreadsorobjects.Itgenerallyprovidesabackgroundprocssing.

142).Whatisthreadlifecycle?

Ans). A thread is created using new Thread( ) statement and is executed by start( ) method. The
threadentersrunnablestateandwhensleep()orwait()methodsareusedorwhenthethreadis
blockedonI/O,itthengoesintonotrunnablestate.Fromnotrunnablestate,thethreadcomes
back to the runnable state and continues running the statements. The thread dies when it comes
outofrun()mehtod.Thesestatethransitionsofathreadarecalledlifecycleofathread.

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
event.Finally,theeventishandledbythemethod.

145).WhichmodelisusedtoprovideactionstoAWTcomponents?
Ans).Eventdelegationmodel.

146).Whatisanadapterclass?
Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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
WindowListenerinterface.Adapter 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).ModelViewControllerisamodelusedinswingcomponents.Modelrepresentsthedata
of the component. View represents its appearance and controller is a mediater between the model
and the view.MVC represents the separation of model of an object from its view and how it is
controlled.

152).Whatarethevariouswindowpanesavailableinswing? Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 32/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

Ans).Thereare4windowpanes:Glasspane,Rootpane,Layeredpane,andContentpane.
JavaSynchronizedblockandmethodindetail.. ClickHere

153).Wherearethebordersavailableinswing?

Ans).AllbordersareavailableinBorderFactoryclassinjavax.swing.borderpackage.

154).Whatisanapplet?

Ans).AnappletrepresentsJavabytecodeembeddedinawebpage.

155).Whatisappletlifecycle?

Ans).Anappletisbornwithinit()methodandstartsfunctioningwithstart()method.Tostopthe
applet, the stop( ) method is called and to terminate the applet completely from memory, the
destroy()methodiscalled.Oncetheappletisterminated,weshouldreloadtheHTMLpageagain
togettheappletstartonceagainfrominit()method.Thiscyclicwayofexecutingthemethodsis
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.
Thefollowingisthesyntaxfortheapplettag.Requiredattributesareinbold.
Optionalattributesareinregulartypeface.Valuesyouspecifyareinitalics: Back to Top

1 <applet ?

2 codebase=codebaseURL
http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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).Agenerictyperepresentsaclassoraninterfacethatistypesafe.Itcanactonanydatatype.

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.
http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 34/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

JavaSynchronizedblockandmethodindetail.. ClickHere
164).Howcanyouregisteradriver?

Ans).Toregisteradatabasedriver,wecanfollowoneofthe4options:
Bycreatinganobjecttodriverclass
BysendingdriverclassobjecttoDriverManager.registerDriver()method
BysendingthedriverclassnametoClass.forName()method
ByusingSystemclassgetProperty()method.

YoucandownloadalltheseinterviewquestionsinasinglepdffileJava
IntervewQuestionsbyNageswaraRao.GotothislinkandDownload.

ReferenceBooks:

CoreJAVA:AnIntegratedApproach1Edition

CoreJava:AdvancedFeatures(Volume2)8Edition

CoreJavaServerFaces3Edition

PostedbyMuralidharNayaniatFriday,August14,20096Comments
Labels:CoreJava,InterviewQuestions

6Comments JAVAbyNATARAJ
1 Login

Recommend Share SortbyBest

Jointhediscussion

Balaji3yearsago Back to Top


Hi

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 35/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

JustgoogleditandIfoundfollowingresult
JavaSynchronizedblockandmethodindetail.. ClickHere

TakeyournormalListobject

PassthatListliobjecttoSet[Linenumber22]=>SofinallywehaveSetobject
inourhand,justpassthiscurrentSetobjectasargumenttoArrayList,sowe
gotnewListobjectli2withoutduplicate

ButifyouwouldliketopreservetheorderofdatauseLinkedHashSetrather
HashSet

packagejava4s

importjava.util.ArrayList

importjava.util.HashSet

importjava.util.Iterator

seemore

1 Reply Share

Mdhar GeekDude >Balaji 3yearsago

HIBalaji,yesyouareright.LinkedHashSetpreservestheorderof
insertionandwhileiteration.Thanksforyourpointsgivenhere..
Reply Share

patil3yearsago
sirifacedfollowingquestionininterview
1)listacceptstheduplicatevaluesthenhowmakelistbehavelikeSet(i.elist
shouldnotbeacceptduplicate.)
2)SetnotacceptduplicatevaluesthenhowmakeSetbehavelikeList(i.Set
shouldbeaccepttheduplicate)
Reply Share
Back to Top
Mdhar GeekDude >patil 3yearsago

HiPatil,sorryforthedelay.
1),TomakeListtonottoacceptduplicatesweshouldoverrideequals
http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 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
oftheSubclasstype.Perfectexampleforthisistheclonemethod.Theclone
methodcanreturnanobjectofthesametypeastheclass.

Q.69iswrong...Afinalmethodisnotthesameasaprivatemethod.Theonly
similarityisthattheycannotbeoverriden,Butfinalmethodsarevisibleto
subclasses,privatemethodsarenot.

Q.111IteratorsarefailfastwhereasEnumerationarefailsafe.
Reply Share

Mdhar GeekDude >BHS 3yearsago

Thanksforyourvaluablepoints..TheAnswerisupdatedbyyourname.
Reply Share

ALSOONJAVABYNATARAJ

Whypublicstaticvoidmain(String HowtoIterateorTraverseaMapin
args[]) Java
4comments3yearsago 1comment3yearsago
JagannathKaleVerynice...! EyalGolanIfyouuseSONAR,it
wouldwarnyouofusingkeySet
insteadofentrySet.It'sbest
Back to Top
Variableargumentorvarargsin SpringnotesbyMr.Natarazfrom
Java SathyaTechnologies
http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 37/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ
Java SathyaTechnologies
2comments3yearsago 2comments4yearsago
JavaSynchronizedblockandmethodindetail.. ClickHere
MdharyouareWelcome..:) NVPRASADRockStaryouonlysir
injavaentireameerpet.

Subscribe d AddDisqustoyoursiteAddDisqusAdd Privacy

NewerPost Home OlderPost

FRIENDSLINKS STRUTSPOSTS POPULARPOSTS

javac.in BasicStrutsLoginApplication
DurgaSoftSCJPNotesPartIDownload
WebDevelopmentTips,Tutorials&Books strutsconfig.xmlinDetail
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 Mr.Ratan from
living in Chennai. I have Strutsconfigurationfile Durgasoft
been working in Java and Struts ApplicationResource.properties in
JEE technologies. I like to share the java Advaced Java Notes by Mr.Nataraj 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&MVCnotesbyMr.Sekharsir
andTilesinStruts

Back to Top
javabynataraj.blogspot.comfrom20092014.Allrightsreserved.

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 38/39
2017524 164JavaInterviewQuestionsbyNageswaraRao|JAVAbyNATARAJ

JavaSynchronizedblockandmethodindetail.. ClickHere

Back to Top

http://javabynataraj.blogspot.in/2009/08/javainterviewquestions.html 39/39

You might also like