Anda di halaman 1dari 20

JavaSynchronizedblockandmethodindetail..

ClickHere

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

Adsby Google JavaPDF JavaNotes CoreJava


SEARCHTHISBLOG

Search
164JavaInterviewQuestionsbyNageswara
Rao SUBSCRIBEVIAEMAIL

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


Subscribe
Tweet Like 100 41
Delivered by FeedBurner
Dr.R.NageswaraRaohasgivensome
oftheJavainterviewquestionsin
hisCoreJavaIntegratedApproach
book.Thesearethequestions
frequentlyaskedinJava
interviews.Gothroughtthese
Questionsthiswouldbehelpfulto JavabynataraJ
2,765likes
you..

LikePage Share

Bethefirstofyourfriendstolikethis

Ifyouarealreadyattendedanyinterviewsonjavayoumighthavefaced
mostofthequestionsgivenbelow.Pleaseleaveacommentifyouhaveany
queries.
1)Whypointersareeliminatedfromjava?
Ans)

1.Pointersleadtoconfusionforaprogrammer.

2.Pointersmaycrashaprogrameasily,forexample,whenweaddtwopointers,theprogram
crashersimmediately. POPULARPOSTS

3.Pointersbreaksecurity.Usingpointers,harmfulprogramslikeVirusandotherhackingprograms DurgaSoft SCJP Notes Part-I


canbedeveloped.Becauseoftheabovereasons,pointershavebeeneliminatedfromjava. Download

2)Whatisthedifferencebetweenafunctionandamethod?

DurgaSoft OCJP(SCJP) Notes Part-II


Ans).Amethodisafunctionthatiswritteninaclass.Wedonothavefunctionsinjavainstead
Download
we have methods. This means whenever a function is written in java, it should be written inside
theclassonly.ButifwetakeC++,wecanwritethefunctionsinsideaswellasoutsidetheclass.
Back to Top
SoinC++,theyarecalledmemberfunctionsandnotmethods.
Core Java notes by Mr.Ratan from Durgasoft
3)WhichpartofJVMwillallocatethememoryforajavaprogram?
JavaSynchronizedblockandmethodindetail.. ClickHere
Ans). Class loader subsystem of JVM will allocate the necessary memory needed by the java
program.

4). which algorithm is used by garbage collector to remove the unused Advaced Java Notes by Mr.Nataraj
variablesorobjectsfrommemory? from Ameerpeta

Ans).Garbagecollectorusesmanyalgorithmsbutthemostcommonlyusedalgorithmismarkand
sweep.
164 Java Interview Questions by
Nageswara Rao
5).Howcanyoucallthegarbagecollector?

Ans).Garbage collector is automatically invoked when the program is being run. It can be also
Download Spring material from
calledbycallinggc()methodofRuntimeclassorSystemclassinJava.
DurgaSoft

6)WhatisJITCompiler?

Ans).JITcompileristhepartofJVMwhichincreasesthespeedofexecutionofaJavaprogram. Spring AOP & MVC notes by


Mr.Sekhar sir

7)WhatisanAPIdocument?

Ans).AnAPIdocumentisa.htmlfilethatcontainsdescriptionofallthefeaturesofasoftwar,a Core Java notes by KVR from


product, or a technology. API document is helpful for the user to understand how to use the Sathya Technologies
softwareortechnology.

8)Whatisthedifferencebetween#includeandimportstatement? Spring notes by Mr.Nataraz from


Sathya Technologies
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.
Web Services Notes by Nataraj sir
from Sathya Technologies
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? Adsby Google Adsby Google

Ans).Both methods are used to display the results on the monitor. print() method displays the ProgramJava JavaBooks
resultandthenretainsthecursorinthesameline,nexttotheendoftheresult.println()displays JavaBooks PDFPDF
theresultandthenthrowsthecursortothenextline.

10)WhathappensifStringargs[]isnotwritteninmain()method?
BLOGARCHIVE

2016 (2)
Ans).Whenmain()methodiswrittenwithoutStringargs[]as:
2015 (6)

Publicstaticvoidmain() 2014 (37)

2013 (18)
ThecodewillcompilebutJVMcannotrunthecodebecauseitcannotrecognizethemain()asthe 2012 (29)
methodfromwhereitshouldstartexecutionoftheJavaprogram.RememberJVMalwayslooks
2011 (86)
formain()methodwithstringtypearrayasparameter.
2010 (17)

2009 (17)
11)Whatisthedifferencebetweenfloatanddouble?
December (1)

Ans). Float can represent up to 7 digits accurately after decimal point, where as double can November (1)
representupto15digitsaccuratelyafterdecimalpoint. August (1)

164 Java Interview Questions by


12)WhatisaUnicodesystem? Nageswara Rao

July (1)
Ans).Unicodesystemisanencodingstandardthatprovidesauniquenumberforeverycharacter,
June (5)
nomatterwhattheplatform,program,orlanguageis.Unicodeuses2bytestorepresentasingle
May (8)
character.
Back to Top

13)Howarepositiveandnegativenumbersrepresentedinternally?
JavaSynchronizedblockandmethodindetail.. ClickHere
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.

15)Whatarecontrolstatements?

Ans).Control statements are the statements which alter the flow of execution and provide better
controltotheprogrammerontheflowofexecution.Theyareusefultowritebetterandcomplex
LABELS
programs.
ActionServlet (1) Advantages (1) AdvJavaBooks (7) Ajax
(1) AOP (1) Architecture (2) ArrayList (1) Arrays (4)
Atlassian (2) Basic Java Programs (1) Basic JavaPrograms
16)OutofdoWhileandwhilewhichloopisefficient? (1) BufferedReader (2) ClassNotes (2) Coding Standards
(1) Collections (20) Con guration (3)

Ans).Inado..whileloop,thestatementsareexecutedwithouttestingthecondition,thefirsttime. ConnectionPooling (1) CoreJava (67)


CoreJavaBooks (10) CSV File (1) CVS (2) DAO (1)
From the second time only the condition is observed. This means that the programmer does not Database (1) DataStructure (1) Decorative (1)
havecontrolrightfromthebeginningofitsexecution.Inawhileloop,theconditionistestedfirst Designpatterns (6) Developer (1) Differences (2)

andthenonly the statements are executed. This means it provides better control right from the Downloads (55) DurgaSir Notes (2)

beginning.Hence,whileloopismoveefficientthando..whileloop. DurgaSoft (6) eBooks (42) Eclipse (1)


Examples (5) Exceptions (1) File I/O Operations (1) File
Operations (2) FishEye (1) Frameworks (6) Generics
17)Whatisacollection? (2) HashMap (2) HeadFirst (5) Hibernate (16)
HibernateBooks (3) How To (2) Html (2) Html5 (1)
Installations (1) Interview Questions (13) IO
Ans). A collection represents a group of elements like integer values or objects. Examples for Package (14) IOC (1) j2ee (7) java (32) Java 5
collectionsarearraysandjava.util_classes(stack,LinkedList,Vector,etc). Features (4) Java Programs (2) Java Standards (1) java.io
(1) java.util (1) JavaBeans (1) JavaScript (1) JavaTips (1) jdbc
(13) JIRA (1) jQuery (1) JS (1) Jsp (7) JSTL (2) KVR Sir (1)
List (1) Maven (1) MS Access (2) mvc (7) MyEclipse (4)
18)WhygotostatementsarenotavailableinJava? Nataraz Sir Notes (4) Normalization (1) OCJP (6) Oracle
(1) Others (1) Prepared Statement (1) Products (1)
programs (6) Projects (1) Promotions (1) RealTime_Tips
Ans) . Goto statements lead to confusion for a programmer. Especially in a large program, if (4) Re ection (1) RegEx (1) SathyaTech (1) Scanner (2)
several goto statements are used, the programmer would be perplexed while understanding the scjp (5) Sekhar sir Notes (6) Server (1) Servlets (9)
Settings (1) Spring (6) SQL (1) Statements (2) Static
flowfromwheretowherethecontrolisjumping. Import (1) Streams (1) Strings (3) Struts 1.2 (29)
Struts2 (1) StrutsBooks (2) Synchronization (1)
Synchronized (1) Threads (3) Tomcat (3) Tools (1) Util
19)WhatisthedifferencebetweenreturnandSystem.exit(0)? pack (5) Var-Args (2) weblogic (3) WebServices (3)
WSAD (2) XML (1)

Ans).Returnstatementisusedinsideamethodtocomeoutofit.System.exit(0)isusedinany
methodtocomeoftheprogram.
GOOGLE+FOLLOWERS
MuralidharNayani
20)WhatisthedifferencebetweenSystem.out.exit(0)andSystem.exit(1)?
Addtocircles

Ans). System.exit(0) terminates the program normally. Whereas System.exit(1) terminates the
programbecauseofsomeerrorencounteredintheprogram.
287havemeincircles Viewall
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.

22)Onwhichmemory,arraysarecreatedinJava?

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

23)Canyoucallthemain()methodofaclassfromanotherclass?

Ans).Yes,wecancallthemain()methodofaclassfromanotherclassusingClassname.main()
.Atthetimeofcallingthemain()method,weshouldpassastringtypearraytoit.
Back to Top
24)IsStringaclassordatatype?
Ans).String is a class in java.lang package. But in Java, all classes are also considered as data
JavaSynchronizedblockandmethodindetail.. ClickHere
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?

Ans). Sring constant pool is a separate block of memory where the string objects are held by
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
useseveralthreads,heshoulduseStringBufferasitgivesreliableresults.Ifonlyonethreadis
used.StringBuilderispreferred,asitimprovesexecutiontime.

33)Whatisobjectorientedapproach?

Ans).Objectorientedprogrammingapproachisaprogrammingmethodologytodesigncomputer
programsusingclassesandobjects.

Back to Top
34)Whatisthedifferencebetweenaclassandanobject?
Ans).Aclassisamodelforcreatingobjectsanddoesnotexistphysically.Anobjectisanything
JavaSynchronizedblockandmethodindetail.. ClickHere
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;
3 PrivateStringname;
4 Privatefloatbalance;
5 Privatefloatprofit;
6 Privatefloatloan;
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?

Ans).HashcodeisuniqueidentificationnumberallotedtotheobjectsbytheJVM.Thishashcode
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 Back to Top

codeofanobject.
JavaSynchronizedblockandmethodindetail.. ClickHere
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
called. called.

45)Whatisthedifferencebetweenaconstructorandamethod?

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


variables(staticvariables)?

Ans).1.AnInstancevariableisavariablewhoseseparatecopyisavailabletoeachobject.Aclass
variableisavariablewhosesinglecopyinmemoryissharedbyallobjects.
2. Instance variables are created in the objects on heap memory. Class variables are stored on
methodarea. Back to Top
50)WhyinstanceVariablesarenotavailabletostaticmethods?
JavaSynchronizedblockandmethodindetail.. ClickHere

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:
1.Usingnewoperator
Employeeobj=newEmployee()
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.

57)WhatisInheritance?

Ans).Derivingnewclassesfromexistingclassessuchthatthenewclassesacquireallthefeatures
ofexistingclassesiscalledinheritance.
Back to Top

58)Whysuperclassmembersareavailabletosubclass?
JavaSynchronizedblockandmethodindetail.. ClickHere
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.

63)Whatisconversion?

Ans).Conversionisanexplicitchangeinthedatatypespecifiedbytheoperator.

64)Whatismethodsignature?

Ans).Methodsignaturerepresentsthemethodnamealongwithmethodparmeters.

65)Whatismethodoverloading?

Ans).Writing two or more methods in the same class in such a way that each mehtod has same
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.
Method overloading is done when the Method overriding is done when the
programmer wants to extend the already programmer wants to provide a different
availablefeatures. implementation(body)forthesamefeature.
Back to Top
Method overloading is code refinement. Same Method overriding is code replacement. The
methodisrefinedtoperformadifferenttask. subclassmethodoverrides(replaces)thesuper
JavaSynchronizedblockandmethodindetail.. ClickHere
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
examplesfordynamicpolymorphism.
Static polymorphism is the polymorphism exhibited at compile time. Here, Java compiler knows
which method is called. Method overloading and method overriding using static methods method
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
does not use cast operator, the Java compiler does not flag any error. Narrowing is unsafe and
Back to Top
hencetheprogrammershouldexplicitlyusecastoperatorinnarrowing.
77)Whichmethodisusedincloning?
JavaSynchronizedblockandmethodindetail.. ClickHere

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
becreated.So,botharequitecontradictoryandcannotbeusedforthesameclass.

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

An abstract class is written when there are Aninterfaceiswrittenwhenallthefeaturesare


some common features shared by all the implementeddifferentlyindifferentobjects. Back to Top
objects.
Whenanabstractclassiswritten,itistheduty An interface is written when the programmer
JavaSynchronizedblockandmethodindetail.. ClickHere
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()
Runtime.getRuntime().gc()

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[]?
Back to Top
Ans). The code compiles but JVM cannot run it, as it cannot see the main( ) method with String
JavaSynchronizedblockandmethodindetail.. ClickHere
args[].

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?

1.Theyconvertprimitivedatatypesint
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?
Back to Top

Ans).ACollectionobjectstoresreferencesofotherobjects.
JavaSynchronizedblockandmethodindetail.. ClickHere
109).Canyoustoreaprimitivedatatypeintoacollection?

Ans).No,Collectionsstoreonlyobjects.

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.
ArrayList increases its size every time by 50 Vector increases its size every time by
percent(half). doublingit.

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. Back to Top
117).CanyoumakeHashMapsynchronized?
JavaSynchronizedblockandmethodindetail.. ClickHere

Ans).Yes,wecanmakeHashMapobjectsynchronizedusingsynchronizedMap()methodasshown
here:Collections.synchronizedMap(newHashMap())

118).WhatisthedifferencebetweenaSetandaList?

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?

Ans).Serializationistheprocessofstoringobjectcontentsintoafile.Theclasswhoseobjectsare
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.
Back to Top
127).Whatisportnumber? JavaSynchronizedblockandmethodindetail.. ClickHere

Ans).Portnumberiaa2bytenumberwhichisusedtoidentifyasocketuniquely.

128).WhichthreadalwaysrunsinaJavaprogrambydefault?

Ans). main thread. A thread represents execution of statements. The way the statements are
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.

133).Whichmethodisexecutedbythethreadbydefault?

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.
Back to Top

139).Whatisthedifferencebetweenthesleep()andwait()methods?
JavaSynchronizedblockandmethodindetail.. ClickHere
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.

140).Whatisthedefaultpriorityofathread?

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?

Ans). An adapter class is an implementation class of a listener which contains all methods
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.
Back to Top

151).DiscussabouttheMVCarchitectureinJFC/swing?
JavaSynchronizedblockandmethodindetail.. ClickHere
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?

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

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:

1 <applet ?
2 codebase=codebaseURL
3 archive=archiveList
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 Back to Top

compiler.
JavaSynchronizedblockandmethodindetail.. ClickHere
162).WhatisJDBC?

Ans). JDBC (Java Database Connectivity) is an API that is useful to write Java programs to
connecttoanydatabase,retreivethedatafromthedatabaseandutilizethedatainaJavaprogram.

163).Whatisadatabasedriver?

Ans). A database driver is a set of classes and interfaces, written according to JDBC API to
communicatewithadatabase.

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

Youmightalsolike:

JavaPackages HibernateInterview WhatisReflection JSPTagLibraries


andinterface Questionsand andHowitWorks inBreif
Answers5 inJava

Linkwithin

PostedbyMuralidharNayaniatFriday,August14,20096Comments
Labels:CoreJava,InterviewQuestions

6Comments JAVAbyNATARAJ Login

SortbyBest
Recommend Share

Jointhediscussion

Balaji3yearsago
Hi

JustgoogleditandIfoundfollowingresult

TakeyournormalListobject

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

ButifyouwouldliketopreservetheorderofdatauseLinkedHashSetrather
HashSet Back to Top

packagejava4s
JavaSynchronizedblockandmethodindetail.. ClickHere
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

Mdhar GeekDude >patil 3yearsago

HiPatil,sorryforthedelay.
1),TomakeListtonottoacceptduplicatesweshouldoverrideequals
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

StaticImportinJavawithan HowtoIterateorTraverseaMapin
Example Java
1comment2yearsago 1comment3yearsago
Jumbodium Informativeshare. EyalGolanIfyouuseSONAR,it
Likedthepost.Thankuforthe wouldwarnyouofusingkeySet
share. insteadofentrySet.It'sbest

ListofGuidelinestofollowJava Variableargumentorvarargsin
Developer Java
2comments3yearsago 2comments3yearsago
AffitySolutionsThanksforyour MdharyouareWelcome..:)
ideas.Youcanalsofindthedetails
onAffitySolutions,attheJava

Subscribe d AddDisqustoyoursiteAddDisqusAdd Privacy


Back to Top

NewerPost Home OlderPost


JavaSynchronizedblockandmethodindetail.. ClickHere

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 DownloadSpringmaterialfromDurgaSoft
andTilesinStruts

javabynataraj.blogspot.comfrom20092014.Allrightsreserved.

Back to Top