Anda di halaman 1dari 101

Java Interview Questions

Question: What is the difference between an Interface and an Abstract class?



Question:
What is the purpose of garbage collection in Java, and when is it used?
Question:
Describe synchronization in respect to ultithreading!
Question: "#plain different way of using thread?
Question:
What are pass by reference and passby value?
Question:
What is $ash%ap and %ap?
Question:
Difference between $ash%ap and $ash&able?
Question: Difference between 'ector and Array(ist?
Question:
Difference between )wing and Awt?
Question:
What is the difference between a constructor and a ethod?
Question:
What is an Iterator?
Question:
)tate the significance of public, private, protected, default odifiers both singly
and in cobination and state the effect of pac*age relationships on declared
ites +ualified by these odifiers!
Question: What is an abstract class?
Question: What is static in ,ava?
Question: What is final?
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance ethods that ipleent a default behavior! An
Interface can only declare constants and instance ethods, but cannot ipleent default
behavior and all ethods are iplicitly abstract! An interface has all public ebers and
no ipleentation! An abstract class is a class which ay have the usual flavors of class
ebers -private, protected, etc!., but has soe abstract ethods!
!
TOP
Q: What is the purpose of garbage collection in Java, and when is it used?
A: &he purpose of garbage collection is to identify and discard ob,ects that are no longer
needed by a progra so that their resources can be reclaied and reused! A Java ob,ect
is sub,ect to garbage collection when it becoes unreachable to the progra in which it
is used!

TOP
Q: escribe s!nchroni"ation in respect to #ultithreading$
A: With respect to ultithreading, synchronization is the capability to control the access of
ultiple threads to shared resources! Without synchonization, it is possible for one thread
to odify a shared variable while another thread is in the process of using or updating
sae shared variable! &his usually leads to significant errors!

TOP
Q: %&plain different wa! of using thread?
A: &he thread could be ipleented by using runnable interface or by inheriting fro the
&hread class! &he forer is ore advantageous, /cause when you are going for ultiple
inheritance!!the only interface can help!

TOP
Q: What are pass b! reference and passb! value?
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value
means passing a copy of the value to be passed.

TOP
Q: What is 'ash(ap and (ap?
A: %ap is Interface and $ashap is class that ipleents that!

TOP
Q: ifference between 'ash(ap and 'ashTable?
A: &he $ash%ap class is roughly e+uivalent to $ashtable, e#cept that it is unsynchronized
and perits nulls! -$ash%ap allows null values as *ey and value whereas $ashtable
doesnt allow.! $ash%ap does not guarantee that the order of the ap will reain
constant over tie! $ash%ap is unsynchronized and $ashtable is synchronized.

TOP
Q: ifference between )ector and Arra!*ist?
A: 'ector is synchronized whereas arraylist is not!

TOP
Q: ifference between +wing and Awt?
A: AW& are heavy0weight coponenets! )wings are light0weight coponents! $ence swing
wor*s faster than AW&!

TOP
Q: What is the difference between a constructor and a #ethod?
A: A constructor is a eber function of a class that is used to create ob,ects of that class!
It has the sae nae as the class itself, has no return type, and is invo*ed using the
new operator!
A ethod is an ordinary eber function of a class! It has its own nae, a return type
-which ay be void., and is invo*ed using the dot operator!

TOP
Q: What is an Iterator?
A: )oe of the collection classes provide traversal of their contents via a ,ava!util!Iterator
interface! &his interface allows you to wal* through a collection of ob,ects, operating on
each ob,ect in turn! 1eeber when using Iterators that they contain a snapshot of the
collection at the tie the Iterator was obtained2 generally it is not advisable to odify
the collection itself while traversing an Iterator!

TOP
Q: +tate the significance of public, private, protected, default #odifiers both singl!
and in co#bination and state the effect of pac,age relationships on declared
ite#s -ualified b! these #odifiers$
A: public : 3ublic class is visible in other pac*ages, field is visible everywhere -class ust
be public too.
private : 3rivate variables or ethods ay be used only by an instance of the sae
class that declares the variable or ethod, A private feature ay only be accessed by the
class that owns the feature!
protected : Is available to all classes in the sae pac*age and also available to all
subclasses of the class that owns the protected feature!&his access is provided even to
subclasses that reside in a different pac*age fro the class that owns the protected
feature!
default :What you get by default ie, without any access odifier -ie, public private or
protected.!It eans that it is visible to all within a particular pac*age.

TOP
Q: What is an abstract class?
A: Abstract class ust be e#tended4subclassed -to be useful.! It serves as a teplate! A
class that is abstract ay not be instantiated -ie, you ay not call its constructor.,
abstract class ay contain static data! Any class with an abstract ethod is autoatically
abstract itself, and ust be declared as such!
A class ay be declared abstract even if it has no abstract ethods! &his prevents it
fro being instantiated!

TOP
Q: What is static in .ava?
A: )tatic eans one per class, not one for each ob,ect no atter how any instance of a
class ight e#ist! &his eans that you can use the without creating an instance of a
class!)tatic ethods are iplicitly final, because overriding is done based on the type of
the ob,ect, and static ethods are attached to a class, not an ob,ect! A static ethod in a
superclass can be shadowed by another static ethod in a subclass, as long as the
original ethod was not declared final! $owever, you can/t override a static ethod with
a nonstatic ethod! In other words, you can/t change a static ethod into an instance
ethod in a subclass!

TOP
Q: What is final?
A: A final class can/t be e#tended ie!, final class ay not be subclassed! A final ethod can/t
be overridden when its class is inherited! 5ou can/t change value of a final variable -is a
constant.!
Java Interview Questions
Question: What if the ain ethod is declared as private?
Question:
What if the static odifier is reoved fro the signature of the ain ethod?
Question: What if I write static public void instead of public static void?
Question:
What if I do not provide the )tring array as the arguent to the ethod?
Question: What is the first arguent of the )tring array in ain ethod?
Question: If I do not provide any arguents on the coand line, then the )tring array of
%ain ethod will be epty or null?
Question: $ow can one prove that the array is not null but epty using one line of code?
Question: What environent variables do I need to set on y achine in order to be able
to run Java progras?
Question: 6an an application have ultiple classes having ain ethod?
Question: 6an I have ultiple ain ethods in the sae class?
Question: Do I need to iport ,ava!lang pac*age any tie? Why ?
Question: 6an I iport sae pac*age4class twice? Will the J'% load the pac*age twice at
runtie?
Question: What are 6hec*ed and 7n6hec*ed "#ception?
Question: What is 8verriding?
Question: What are different types of inner classes?
Q: What if the #ain #ethod is declared as private?
A: &he progra copiles properly but at runtie it will give 9%ain ethod not public!9
essage!

: 1eceived fro )andesh )adhale; TOP
Q: What if the static #odifier is re#oved fro# the signature of the #ain #ethod?
A: 3rogra copiles! <ut at runtie throws an error 9=o)uch%ethod"rror9!

: 1eceived fro )andesh )adhale; TOP
Q: What if I write static public void instead of public static void?
A: 3rogra copiles and runs properly!

: 1eceived fro )andesh )adhale; TOP
Q: What if I do not provide the +tring arra! as the argu#ent to the #ethod?
A: 3rogra copiles but throws a runtie error 9=o)uch%ethod"rror9!

: 1eceived fro )andesh )adhale; TOP
Q: What is the first argu#ent of the +tring arra! in #ain #ethod?
A: &he )tring array is epty! It does not have any eleent! &his is unli*e 646>> where the
first eleent by default is the progra nae!

: 1eceived fro )andesh )adhale; TOP
Q: If I do not provide an! argu#ents on the co##and line, then the +tring arra! of
(ain #ethod will be e#pt! or null?
A: It is epty! <ut not null!

: 1eceived fro )andesh )adhale; TOP
Q: 'ow can one prove that the arra! is not null but e#pt! using one line of code?
A: 3rint args!length! It will print ?! &hat eans it is epty! <ut if it would have been null
then it would have thrown a =ull3ointer"#ception on attepting to print args!length!

: 1eceived fro )andesh )adhale; TOP
Q: What environ#ent variables do I need to set on #! #achine in order to be able
to run Java progra#s?
A: 6(A))3A&$ and 3A&$ are the two variables!

: 1eceived fro )andesh )adhale; TOP
Q: /an an application have #ultiple classes having #ain #ethod?
A: 5es it is possible! While starting the application we ention the class nae to be run! &he
J'% will loo* for the %ain ethod only in the class whose nae you have entioned!
$ence there is not conflict aongst the ultiple classes having ain ethod!

: 1eceived fro )andesh )adhale; TOP
Q: /an I have #ultiple #ain #ethods in the sa#e class?
A: =o the progra fails to copile! &he copiler says that the ain ethod is already
defined in the class!

: 1eceived fro )andesh )adhale; TOP
Q: o I need to i#port .ava$lang pac,age an! ti#e? Wh! ?
A: =o! It is by default loaded internally by the J'%!

: 1eceived fro )andesh )adhale; TOP
Q: /an I i#port sa#e pac,age0class twice? Will the J)( load the pac,age twice at
runti#e?
A: 8ne can iport the sae pac*age or sae class ultiple ties! =either copiler nor J'%
coplains abt it! And the J'% will internally load the class only once no atter how any
ties you iport the sae class!

: 1eceived fro )andesh )adhale; TOP
Q: What are /hec,ed and 1n/hec,ed %&ception?
A: A chec*ed e#ception is soe subclass of "#ception -or "#ception itself., e#cluding class
1untie"#ception and its subclasses!
%a*ing an e#ception chec*ed forces client prograers to deal with the possibility that
the e#ception will be thrown! eg, I8"#ception thrown by ,ava!io!@ileInput)trea/s read-.
ethodA
7nchec*ed e#ceptions are 1untie"#ception and any of its subclasses! 6lass "rror and
its subclasses also are unchec*ed! With an unchec*ed e#ception, however, the copiler
doesn/t force client prograers either to catch the
e#ception or declare it in a throws clause! In fact, client prograers ay not even
*now that the e#ception could be thrown! eg, )tringInde#8ut8f<ounds"#ception thrown
by )tring/s charAt-. ethodA 6hec*ed e#ceptions ust be caught at copile tie!
1untie e#ceptions do not need to be! "rrors often cannot be!

TOP
Q: What is Overriding?
A: When a class defines a ethod using the sae nae, return type, and arguents as a
ethod in its superclass, the ethod in the class overrides the ethod in the superclass!
When the ethod is invo*ed for an ob,ect of the class, it is the new definition of the
ethod that is called, and not the ethod definition fro superclass! %ethods ay be
overridden to be ore public, not ore private!

TOP
Q: What are different t!pes of inner classes?
A: Nested top-level classes, Member classes, Local classes, Anonymous classes
Nested top-level classes0 If you declare a class within a class and specify the static
odifier, the copiler treats the class ,ust li*e any other top0level class!
Any class outside the declaring class accesses the nested class with the declaring class
nae acting siilarly to a pac*age! eg, outer!inner! &op0level inner classes iplicitly
have access only to static variables!&here can also be inner interfaces! All of these are of
the nested top0level variety!
Member classes 0 %eber inner classes are ,ust li*e other eber ethods and
eber variables and access to the eber class is restricted, ,ust li*e ethods and
variables! &his eans a public eber class acts siilarly to a nested top0level class!
&he priary difference between eber classes and nested top0level classes is that
eber classes have access to the specific instance of the enclosing class!
Local classes 0 (ocal classes are li*e local variables, specific to a bloc* of code! &heir
visibility is only within the bloc* of their declaration! In order for the class to be useful
beyond the declaration bloc*, it would need to ipleent a
ore publicly available interface!<ecause local classes are not ebers, the odifiers
public, protected, private, and static are not usable!
Anonymous classes 0 Anonyous inner classes e#tend local inner classes one level
further! As anonyous classes have no nae, you cannot provide a constructor!


Java Interview Questions
Question: Are the iports chec*ed for validity at copile tie? e!g! will the code containing
an iport such as ,ava!lang!A<6D copile?
Question: Does iporting a pac*age iports the subpac*ages as well? e!g! Does iporting
co!%y&est!B also iport co!%y&est!7nit&ests!B?
Question: What is the difference between declaring a variable and defining a variable?
Question: What is the default value of an ob,ect reference declared as an instance variable?

Question: 6an a top level class be private or protected?
Question: What type of paraeter passing does Java support?
Question: 3riitive data types are passed by reference or pass by value?
Question: 8b,ects are passed by value or by reference?
Question: What is serialization?
Question: $ow do I serialize an ob,ect to a file?
Question: Which ethods of )erializable interface should I ipleent?
Question: $ow can I custoize the seralization process? i!e! how can one have a control
over the serialization process?
Question: What is the coon usage of serialization?
Question: What is "#ternalizable interface?
Question: When you serialize an ob,ect, what happens to the ob,ect references included in
the ob,ect?
Question: What one should ta*e care of while serializing the ob,ect?
Question: What happens to the static fields of a class during serialization?

Q: Are the i#ports chec,ed for validit! at co#pile ti#e? e$g$ will the code
containing an i#port such as .ava$lang$A2/ co#pile?
A: 5es the iports are chec*ed for the seantic validity at copile tie! &he code
containing above line of iport will not copile! It will throw an error saying,can not
resolve sybol
sybol : class A<6D
location: pac*age io
iport ,ava!io!A<6D2

: 1eceived fro )andesh )adhale; TOP
Q: oes i#porting a pac,age i#ports the subpac,ages as well? e$g$ oes i#porting
co#$(!Test$3 also i#port co#$(!Test$1nitTests$3?
A: =o you will have to iport the subpac*ages e#plicitly! Iporting co!%y&est!B will
iport classes in the pac*age %y&est only! It will not iport any class in any of it/s
subpac*age!

: 1eceived fro )andesh )adhale; TOP
Q: What is the difference between declaring a variable and defining a variable?
A: In declaration we ,ust ention the type of the variable and it/s nae! We do not initialize
it! <ut defining eans declaration > initialization!
e!g )tring s2 is ,ust a declaration while )tring s C new )tring -9abcd9.2 8r )tring s C
9abcd92 are both definitions!

: 1eceived fro )andesh )adhale; TOP
Q: What is the default value of an ob.ect reference declared as an instance
variable?
A: null unless we define it e#plicitly!

: 1eceived fro )andesh )adhale; TOP
Q: /an a top level class be private or protected?
A: =o! A top level class can not be private or protected! It can have either 9public9 or no
odifier! If it does not have a odifier it is supposed to have a default access!If a top
level class is declared as private the copiler will coplain that the 9odifier private is
not allowed here9! &his eans that a top level class can not be private! )ae is the case
with protected!

: 1eceived fro )andesh )adhale; TOP
Q: What t!pe of para#eter passing does Java support?
A: In Java the arguents are always passed by value !

: 7pdate fro "*i and Jyothish 'enu; TOP
Q: Pri#itive data t!pes are passed b! reference or pass b! value?
A: 3riitive data types are passed by value!

: 1eceived fro )andesh )adhale; TOP
Q: Ob.ects are passed b! value or b! reference?
A: Java only supports pass by value! With ob,ects, the ob,ect reference itself is passed by
value and so both the original reference and paraeter copy both refer to the sae
ob,ect !

: 7pdate fro "*i and Jyothish 'enu; TOP
Q: What is seriali"ation?
A: )erialization is a echanis by which you can save the state of an ob,ect by converting
it to a byte strea!

: 1eceived fro )andesh )adhale; TOP
Q: 'ow do I seriali"e an ob.ect to a file?
A: &he class whose instances are to be serialized should ipleent an interface )erializable!
&hen you pass the instance to the 8b,ect8utput)trea which is connected to a
fileoutputstrea! &his will save the ob,ect to a file!

: 1eceived fro )andesh )adhale; TOP
Q: Which #ethods of +eriali"able interface should I i#ple#ent?
A: &he serializable interface is an epty interface, it does not contain any ethods! )o we
do not ipleent any ethods!

: 1eceived fro )andesh )adhale; TOP
Q: 'ow can I custo#i"e the serali"ation process? i$e$ how can one have a control
over the seriali"ation process?
A: 5es it is possible to have control over serialization process! &he class should ipleent
"#ternalizable interface! &his interface contains two ethods naely read"#ternal and
write"#ternal! 5ou should ipleent these ethods and write the logic for custoizing
the serialization process!

: 1eceived fro )andesh )adhale; TOP
Q: What is the co##on usage of seriali"ation?
A: Whenever an ob,ect is to be sent over the networ*, ob,ects need to be serialized!
%oreover if the state of an ob,ect is to be saved, ob,ects need to be serilazed!

: 1eceived fro )andesh )adhale; TOP
Q: What is %&ternali"able interface?
A: "#ternalizable is an interface which contains two ethods read"#ternal and
write"#ternal! &hese ethods give you a control over the serialization echanis! &hus
if your class ipleents this interface, you can custoize the serialization process by
ipleenting these ethods!

: 1eceived fro )andesh )adhale; TOP
Q: When !ou seriali"e an ob.ect, what happens to the ob.ect references included in
the ob.ect?
A: &he serialization echanis generates an ob,ect graph for serialization! &hus it
deterines whether the included ob,ect references are serializable or not! &his is a
recursive process! &hus when an ob,ect is serialized, all the included ob,ects are also
serialized alongwith the original obect!

: 1eceived fro )andesh )adhale; TOP
Q: What one should ta,e care of while seriali"ing the ob.ect?
A: 8ne should a*e sure that all the included ob,ects are also serializable! If any of the
ob,ects is not serializable then it throws a =ot)erializable"#ception!

: 1eceived fro )andesh )adhale; TOP
Q: What happens to the static fields of a class during seriali"ation?
A: &here are three e#ceptions in which serialization doesnot necessarily read and write to
the strea! &hese are
D! )erialization ignores static fields, because they are not part of ay particular state state!
E! <ase class fields are only hendled if the base class itself is serializable!
F! &ransient fields!
Java Interview Questions
Question:Does Java provide any construct to find out the size of an ob,ect?
Question:Give a siplest way to find out the tie a ethod ta*es for e#ecution without
using any profiling tool?
Question:What are wrapper classes?
Question:
Why do we need wrapper classes?
Question:What are chec*ed e#ceptions?
Question:What are runtie e#ceptions?
Question:What is the difference between error and an e#ception??
Question:$ow to create custo e#ceptions?
Question:If I want an ob,ect of y class to be thrown as an e#ception ob,ect, what should I
do?
Question:If y class already e#tends fro soe other class what should I do if I want an
instance of y class to be thrown as an e#ception ob,ect?
Question:$ow does an e#ception pereate through the code?
Question:What are the different ways to handle e#ceptions?
Question:What is the basic difference between the E approaches to e#ception handling!!!DH
try catch bloc* and EH specifying the candidate e#ceptions in the throws clause?
When should you use which approach?
Question:Is it necessary that each try bloc* ust be followed by a catch bloc* ?
Question:If I write return at the end of the try bloc*, will the finally bloc* still e#ecute ?
Question:If I write )yste!e#it -?.2 at the end of the try bloc*, will the finally bloc* still
e#ecute?

Q: oes Java provide an! construct to find out the si"e of an ob.ect?
A: =o there is not sizeof operator in Java! )o there is not direct way to deterine the size of
an ob,ect directly in Java!

: 1eceived fro )andesh )adhale; TOP
Q: 4ive a si#plest wa! to find out the ti#e a #ethod ta,es for e&ecution without
using an! profiling tool?
A: 1ead the syste tie ,ust before the ethod is invo*ed and iediately after ethod
returns! &a*e the tie difference, which will give you the tie ta*en by a ethod for
e#ecution!
To put it in code!!!
long start C )yste!current&ie%illis -.2
ethod -.2
long end C )yste!current&ie%illis -.2
)yste!out!println -9&ie ta*en for e#ecution is 9 > -end 0 start..2
1eeber that if the tie ta*en for e#ecution is too sall, it ight show that it is ta*ing
zero illiseconds for e#ecution! &ry it on a ethod which is big enough, in the sense the
one which is doing considerable aout of processing!

: 1eceived fro )andesh )adhale; TOP
Q: What are wrapper classes?
A: Java provides specialized classes corresponding to each of the priitive data types!
&hese are called wrapper classes! &hey are e!g! Integer, 6haracter, Double etc!

: 1eceived fro )andesh )adhale; TOP
Q: Wh! do we need wrapper classes?
A: It is soeties easier to deal with priitives as ob,ects! %oreover ost of the collection
classes store ob,ects and not priitive data types! And also the wrapper classes provide
any utility ethods also! <ecause of these resons we need wrapper classes! And since
we create instances of these classes we can store the in any of the collection classes
and pass the around as a collection! Also we can pass the around as ethod
paraeters where a ethod e#pects an ob,ect!

: 1eceived fro )andesh )adhale; TOP
Q: What are chec,ed e&ceptions?
A: 6hec*ed e#ception are those which the Java copiler forces you to catch! e!g!
I8"#ception are chec*ed "#ceptions!

: 1eceived fro )andesh )adhale; TOP
Q: What are runti#e e&ceptions?
A: 1untie e#ceptions are those e#ceptions that are thrown at runtie because of either
wrong input data or because of wrong business logic etc! &hese are not chec*ed by the
copiler at copile tie!

: 1eceived fro )andesh )adhale; TOP
Q: What is the difference between error and an e&ception?
A: An error is an irrecoverable condition occurring at runtie! )uch as 8ut8f%eory error!
&hese J'% errors and you can not repair the at runtie! While e#ceptions are
conditions that occur because of bad input etc! e!g! @ile=ot@ound"#ception will be thrown
if the specified file does not e#ist! 8r a =ull3ointer"#ception will ta*e place if you try
using a null reference! In ost of the cases it is possible to recover fro an e#ception
-probably by giving user a feedbac* for entering proper values etc!.!

: 1eceived fro )andesh )adhale; TOP
Q: 'ow to create custo# e&ceptions?
A: 5our class should e#tend class "#ception, or soe ore specific type thereof!

: 1eceived fro )andesh )adhale; TOP
Q: If I want an ob.ect of #! class to be thrown as an e&ception ob.ect, what should
I do?
A: &he class should e#tend fro "#ception class! 8r you can e#tend your class fro soe
ore precise e#ception type also!

: 1eceived fro )andesh )adhale; TOP
Q: If #! class alread! e&tends fro# so#e other class what should I do if I want an
instance of #! class to be thrown as an e&ception ob.ect?
A: 8ne can not do anytihng in this scenarion! <ecause Java does not allow ultiple
inheritance and does not provide any e#ception interface as well!

: 1eceived fro )andesh )adhale; TOP
Q: 'ow does an e&ception per#eate through the code?
A: An unhandled e#ception oves up the ethod stac* in search of a atching When an
e#ception is thrown fro a code which is wrapped in a try bloc* followed by one or ore
catch bloc*s, a search is ade for atching catch bloc*! If a atching type is found then
that bloc* will be invo*ed! If a atching type is not found then the e#ception oves up
the ethod stac* and reaches the caller ethod! )ae procedure is repeated if the caller
ethod is included in a try catch bloc*! &his process continues until a catch bloc*
handling the appropriate type of e#ception is found! If it does not find such a bloc* then
finally the progra terinates!

: 1eceived fro )andesh )adhale; TOP
Q: What are the different wa!s to handle e&ceptions?
A: &here are two ways to handle e#ceptions,
D! <y wrapping the desired code in a try bloc* followed by a catch bloc* to catch the
e#ceptions! and
E! (ist the desired e#ceptions in the throws clause of the ethod and let the caller of the
ethod hadle those e#ceptions!

: 1eceived fro )andesh )adhale; TOP
Q: What is the basic difference between the 5 approaches to e&ception handling$
67 tr! catch bloc, and
57 specif!ing the candidate e&ceptions in the throws clause?
When should !ou use which approach?
A: In the first approach as a prograer of the ethod, you urself are dealing with the
e#ception! &his is fine if you are in a best position to decide should be done in case of an
e#ception! Whereas if it is not the responsibility of the ethod to deal with it/s own
e#ceptions, then do not use this approach! In this case use the second approach! In the
second approach we are forcing the caller of the ethod to catch the e#ceptions, that the
ethod is li*ely to throw! &his is often the approach library creators use! &hey list the
e#ception in the throws clause and we ust catch the! 5ou will find the sae approach
throughout the ,ava libraries we use!

: 1eceived fro )andesh )adhale; TOP
Q: Is it necessar! that each tr! bloc, #ust be followed b! a catch bloc,?
A: It is not necessary that each try bloc* ust be followed by a catch bloc*! It should be
followed by either a catch bloc* 81 a finally bloc*! And whatever e#ceptions are li*ely to
be thrown should be declared in the throws clause of the ethod!

: 1eceived fro )andesh )adhale; TOP
Q: If I write return at the end of the tr! bloc,, will the finall! bloc, still e&ecute?
A: 5es even if you write return as the last stateent in the try bloc* and no e#ception
occurs, the finally bloc* will e#ecute! &he finally bloc* will e#ecute and then the control
return!

: 1eceived fro )andesh )adhale; TOP
Q: If I write +!ste#$e&it 89:; at the end of the tr! bloc,, will the finall! bloc, still
e&ecute?
A: =o in this case the finally bloc* will not e#ecute because when you say )yste!e#it -?.2
the control iediately goes out of the progra, and thus finally never e#ecutes!
Java Interview Questions
Question:$ow are 8bserver and 8bservable used?
Question:
What is synchronization and why is it iportant?
Question:$ow does Java handle integer overflows and underflows?
Question:Does garbage collection guarantee that a progra will not run out of
eory?
Question:What is the difference between preeptive scheduling and tie slicing?
Question:When a thread is created and started, what is its initial state?
Question:What is the purpose of finalization?
Question:What is the (ocale class?
Question:What is the difference between a while stateent and a do stateent?
Question:What is the difference between static and non0static variables?
Question:$ow are this-. and super-. used with constructors?
Question:What are synchronized ethods and synchronized stateents?
Question:What is daeon thread and which ethod is used to create the daeon thread?
Question:6an applets counicate with each other?
Question:What are the steps in the JD<6 connection?
Question:$ow does a try stateent deterine which catch clause should be used to handle
an e#ception?


Q: 'ow are Observer and Observable used?
A: 8b,ects that subclass the 8bservable class aintain a list of observers! When an
8bservable ob,ect is updated it invo*es the update-. ethod of each of its observers to
notify the observers that it has changed state! &he 8bserver interface is ipleented by
ob,ects that observe 8bservable ob,ects!

:1eceived fro 'en*ateswara %ana; TOP
Q: What is s!nchroni"ation and wh! is it i#portant?
A: With respect to ultithreading, synchronization is the capability to control
the access of ultiple threads to shared resources! Without synchronization, it is possible
for one thread to odify a shared ob,ect while another thread is in the process of using
or updating that ob,ect/s value! &his often leads to significant errors!

: 1eceived fro 'en*ateswara %ana; TOP
Q: 'ow does Java handle integer overflows and underflows?
A: It uses those low order bytes of the result that can fit into the size of the type allowed by
the operation!

: 1eceived fro 'en*ateswara %ana; TOP
Q: oes garbage collection guarantee that a progra# will not run out of #e#or!?
A: Garbage collection does not guarantee that a progra will not run out of eory! It is
possible for progras to use up eory resources faster than they are garbage
collected! It is also possible for progras to create ob,ects that are not sub,ect to
garbage collection
!

: 1eceived fro 'en*ateswara %ana; TOP
Q: What is the difference between pree#ptive scheduling and ti#e slicing?
A: 7nder preeptive scheduling, the highest priority tas* e#ecutes until it enters the waiting
or dead states or a higher priority tas* coes into e#istence! 7nder tie slicing, a tas*
e#ecutes for a predefined slice of tie and then reenters the pool of ready tas*s! &he
scheduler then deterines which tas* should e#ecute ne#t, based on priority and other
factors!

: 1eceived fro 'en*ateswara %ana; TOP
Q: When a thread is created and started, what is its initial state?
A: A thread is in the ready state after it has been created and started!

: 1eceived fro 'en*ateswara %ana; TOP
Q: What is the purpose of finali"ation?
A: &he purpose of finalization is to give an unreachable ob,ect the opportunity to perfor
any cleanup processing before the ob,ect is garbage collected!

: 1eceived fro 'en*ateswara %ana; TOP
Q: What is the *ocale class?
A: &he (ocale class is used to tailor progra output to the conventions of a particular
geographic, political, or cultural region!

: 1eceived fro 'en*ateswara %ana; TOP
Q: What is the difference between a while state#ent and a do state#ent?
A: A while stateent chec*s at the beginning of a loop to see whether the ne#t loop
iteration should occur! A do stateent chec*s at the end of a loop to see whether the
ne#t iteration of a loop should occur! &he do stateent will always e#ecute the body of a
loop at least once!

: 1eceived fro 'en*ateswara %ana; TOP
Q: What is the difference between static and non<static variables?
A: A static variable is associated with the class as a whole rather than with specific instances
of a class! =on0static variables ta*e on uni+ue values with each ob,ect instance!

: 1eceived fro 'en*ateswara %ana; TOP
Q: 'ow are this8: and super8: used with constructors?
A: &his-. is used to invo*e a constructor of the sae class! super-. is used to invo*e a
superclass constructor!

: 1eceived fro 'en*ateswara %ana; TOP
Q: What are s!nchroni"ed #ethods and s!nchroni"ed state#ents?
A: )ynchronized ethods are ethods that are used to control access to an ob,ect! A thread
only e#ecutes a synchronized ethod after it has ac+uired the loc* for the ethod/s
ob,ect or class! )ynchronized stateents are siilar to synchronized ethods! A
synchronized stateent can only be e#ecuted after a thread has ac+uired the loc* for the
ob,ect or class referenced in the synchronized stateent!

: 1eceived fro 'en*ateswara %ana; TOP
Q: What is dae#on thread and which #ethod is used to create the dae#on thread?
A: Daeon thread is a low priority thread which runs interittently in the bac* ground
doing the garbage collection operation for the ,ava runtie syste! setDaeon ethod
is used to create a daeon thread!

: 1eceived fro )hipra Iara; TOP
Q: /an applets co##unicate with each other?
A: At this point in tie applets ay counicate with other applets running in the sae
virtual achine! If the applets are of the sae class, they can counicate via shared
static variables! If the applets are of different classes, then each will need a reference to
the sae class with static variables! In any case the basic idea is to pass the inforation
bac* and forth through a static variable!
An applet can also get references to all other applets on the sae page using the
getApplets-. ethod of ,ava!applet!Applet6onte#t! 8nce you get the reference to an
applet, you can counicate with it by using its public ebers!
It is conceivable to have applets in different virtual achines that tal* to a server
soewhere on the Internet and store any data that needs to be serialized there! &hen,
when another applet needs this data, it could connect to this sae server! Ipleenting
this is non0trivial!

: 1eceived fro Irishna Iuar ; TOP
Q: What are the steps in the J2/ connection?
A: While a*ing a JD<6 connection we go through the following steps :
)tep D : 1egister the database driver by using :
6lass!for=ae-J9 driver classs for that specific databaseJ9 .2
)tep E : =ow create a database connection using :
6onnection con C Driver%anager!get6onnection-url,usernae,password.2
)tep F: =ow 6reate a +uery using :
)tateent stt C 6onnection!)tateent-J9select B fro &A<(" =A%"J9.2
)tep K : "#ceute the +uery :
stt!e#ceute7pdate-.2

: 1eceived fro )hri 3ra*ash Iunwar; TOP
Q: 'ow does a tr! state#ent deter#ine which catch clause should be used to
handle an e&ception?
A: When an e#ception is thrown within the body of a try stateent, the catch clauses of the
try stateent are e#ained in the order in which they appear! &he first catch clause that
is capable of handling the e#ceptionis e#ecuted! &he reaining catch clauses are ignored!
Java Interview Questions
Question:6an an unreachable ob,ect becoe reachable again?
Question:
What ethod ust be ipleented by all threads?
Question:What are synchronized ethods and synchronized stateents?
Question:
What is "#ternalizable?
Question:What odifiers are allowed for ethods in an Interface?
Question:What are soe alternatives to inheritance?
Question:What does it ean that a ethod or field is 9static9? ?
Question:What is the difference between preeptive scheduling and tie slicing?
Question:What is the catch or declare rule for ethod declarations?


Q: /an an unreachable ob.ect beco#e reachable again?
A: An unreachable ob,ect ay becoe reachable again! &his can happen when the ob,ect/s
finalize-. ethod is invo*ed and the ob,ect perfors an operation which causes it to
becoe accessible to reachable ob,ects!

:1eceived fro 3 1a,esh; TOP
Q: What #ethod #ust be i#ple#ented b! all threads?
A: All tas*s ust ipleent the run-. ethod, whether they are a subclass of &hread or
ipleent the 1unnable interface!

: 1eceived fro 3 1a,esh; TOP
Q: What are s!nchroni"ed #ethods and s!nchroni"ed state#ents?
A: )ynchronized ethods are ethods that are used to control access to an ob,ect! A thread
only e#ecutes a synchronized ethod after it has ac+uired the loc* for the ethod/s
ob,ect or class! )ynchronized stateents are siilar to synchronized ethods! A
synchronized stateent can only be e#ecuted after a thread has ac+uired the loc* for the
ob,ect or class referenced in the synchronized stateent!

: 1eceived fro 3 1a,esh; TOP
Q: What is %&ternali"able?
A: "#ternalizable is an Interface that e#tends )erializable Interface! And sends data into
)treas in 6opressed @orat! It has two ethods, write"#ternal-8b,ect8uput out. and
read"#ternal-8b,ectInput in.

: 1eceived fro 'en*ateswara %ana; TOP
Q: What #odifiers are allowed for #ethods in an Interface?
A: 8nly public and abstract odifiers are allowed for ethods in interfaces!

: 1eceived fro 3 1a,esh; TOP
Q: What are so#e alternatives to inheritance?
A: Delegation is an alternative to inheritance! Delegation eans that you include an
instance of another class as an instance variable, and forward essages to the instance!
It is often safer than inheritance because it forces you to thin* about each essage you
forward, because the instance is of a *nown class, rather than a new class, and because
it doesn/t force you to accept all the ethods of the super class: you can provide only the
ethods that really a*e sense! 8n the other hand, it a*es you write ore code, and
it is harder to re0use -because it is not a subclass.!

: 1eceived fro 3 1a,esh; TOP
Q: What does it #ean that a #ethod or field is =static=?
A: )tatic variables and ethods are instantiated only once per class! In other words they
are class variables, not instance variables! If you change the value of a static variable in
a particular ob,ect, the value of that variable changes for all instances of that class!
)tatic ethods can be referenced with the nae of the class rather than the nae of a
particular ob,ect of the class -though that wor*s too.! &hat/s how library ethods li*e
)yste!out!println-. wor* out is a static field in the ,ava!lang!)yste class!

: 1eceived fro 3 1a,esh; TOP
Q: What is the difference between pree#ptive scheduling and ti#e slicing?
A: 7nder preeptive scheduling, the highest priority tas* e#ecutes until it enters the waiting
or dead states or a higher priority tas* coes into e#istence! 7nder tie slicing, a tas*
e#ecutes for a predefined slice of tie and then reenters the pool of ready tas*s! &he
scheduler then deterines which tas* should e#ecute ne#t, based on priority and other
factors!

: 1eceived fro 3 1a,esh; TOP
Q: What is the catch or declare rule for #ethod declarations?
A: If a chec*ed e#ception ay be thrown within the body of a ethod, the ethod ust
either catch the e#ception or declare it in its throws clause!
Java Interview Questions
Question:Is "pty !,ava file a valid source file?
Question:
6an a !,ava file contain ore than one ,ava classes?
Question:Is )tring a priitive data type in Java?
Question:
Is ain a *eyword in Java?
Question:Is ne#t a *eyword in Java?
Question:Is delete a *eyword in Java?
Question:Is e#it a *eyword in Java?
Question:What happens if you dont initialize an instance variable of any of the priitive
types in Java?
Question:What will be the initial value of an ob,ect reference which is defined as an instance
variable?
Question:What are the different scopes for Java variables?
Question:What is the default value of the local variables?
Question:$ow any ob,ects are created in the following piece of code?
%y6lass cD, cE, cF2
cD C new %y6lass -.2
cF C new %y6lass -.2
Question:6an a public class %y6lass be defined in a source file naed 5our6lass!,ava?
Question:6an ain ethod be declared final?
Question:What will be the output of the following stateent?
)yste!out!println -9D9 > F.2
Question:What will be the default values of all the eleents of an array defined as an
instance variable?


Q: Is %#pt! $.ava file a valid source file?
A: 5es, an epty !,ava file is a perfectly valid source file!

:1eceived fro )andesh )adhale; TOP
Q: /an a $.ava file contain #ore than one .ava classes?
A: 5es, a !,ava file contain ore than one ,ava classes, provided at the ost one of the is
a public class!

: 1eceived fro )andesh )adhale; TOP
Q: Is +tring a pri#itive data t!pe in Java?
A: =o )tring is not a priitive data type in Java, even though it is one of the ost
e#tensively used ob,ect! )trings in Java are instances of )tring class defined in ,ava!lang
pac*age!

: 1eceived fro )andesh )adhale; TOP
Q: Is #ain a ,e!word in Java?
A: =o, ain is not a *eyword in Java!

: 1eceived fro )andesh )adhale; TOP
Q: Is ne&t a ,e!word in Java?
A: =o, ne#t is not a *eyword!

: 1eceived fro )andesh )adhale; TOP
Q: Is delete a ,e!word in Java?
A: =o, delete is not a *eyword in Java! Java does not a*e use of e#plicit destructors the
way 6>> does!

: 1eceived fro )andesh )adhale; TOP
Q: Is e&it a ,e!word in Java?
A: =o! &o e#it a progra e#plicitly you use e#it ethod in )yste ob,ect!

: 1eceived fro )andesh )adhale; TOP
Q: What happens if !ou dont initiali"e an instance variable of an! of the pri#itive
t!pes in Java?
A: Java by default initializes it to the default value for that priitive type! &hus an int will be
initialized to ?, a boolean will be initialized to false!

: 1eceived fro )andesh )adhale; TOP
Q: What will be the initial value of an ob.ect reference which is defined as an
instance variable?
A: &he ob,ect references are all initialized to null in Java! $owever in order to do anything
useful with these references, you ust set the to a valid ob,ect, else you will get
=ull3ointer"#ceptions everywhere you try to use such default initialized references!

: 1eceived fro )andesh )adhale; TOP
Q: What are the different scopes for Java variables?
A: &he scope of a Java variable is deterined by the conte#t in which the variable is
declared! &hus a ,ava variable can have one of the three scopes at any given point in
tie!
D! Instance : 0 &hese are typical ob,ect level variables, they are initialized to default
values at the tie of creation of ob,ect, and reain accessible as long as the ob,ect
accessible!
E! (ocal : 0 &hese are the variables that are defined within a ethod! &hey reain
accessbile only during the course of ethod e#cecution! When the ethod finishes
e#ecution, these variables fall out of scope!
F! )tatic: 0 &hese are the class level variables! &hey are initialized when the class is
loaded in J'% for the first tie and reain there as long as the class reains loaded!
&hey are not tied to any particular ob,ect instance!

: 1eceived fro )andesh )adhale; TOP
Q: What is the default value of the local variables?
A: &he local variables are not initialized to any default value, neither priitives nor ob,ect
references! If you try to use these variables without initializing the e#plicitly, the ,ava
copiler will not copile the code! It will coplain abt the local varaible not being
initilized!!

: 1eceived fro )andesh )adhale; TOP
Q: 'ow #an! ob.ects are created in the following piece of code?
(!/lass c6, c5, c>;
c6 ? new (!/lass 8:;
c> ? new (!/lass 8:;
A: 8nly E ob,ects are created, cD and cF! &he reference cE is only declared and not
initialized!

: 1eceived fro )andesh )adhale; TOP
Q: /an a public class (!/lass be defined in a source file na#ed @our/lass$.ava?
A: =o the source file nae, if it contains a public class, ust be the sae as the public class
nae itself with a !,ava e#tension!

: 1eceived fro )andesh )adhale; TOP
Q: /an #ain #ethod be declared final?
A: 5es, the ain ethod can be declared final, in addition to being public static!

: 1eceived fro)andesh )adhale; TOP
Q: What will be the output of the following state#ent?
+!ste#$out$println 8=6= A >:;
A: It will print DF!

: 1eceived fro )andesh )adhale; TOP
Q: What will be the default values of all the ele#ents of an arra! defined as an
instance variable?
A: If the array is an array of priitive types, then all the eleents of the array will be
initialized to the default value corresponding to that priitive type! e!g! All the eleents
of an array of int will be initialized to ?, while that of boolean type will be initialized to
false! Whereas if the array is an array of references -of any type., all the eleents will be
initialized to null!
Question: What is transient variable?
Answer: Transient variable can't be serialize. or e!ample if a variable is declared as transient in
a "erializable class and the class is #ritten to an $b%ect"tream& the value of the variable can't be
#ritten to the stream instead #hen the class is retrieved from the $b%ect"tream the value of the
variable becomes null.
Question: 'ame the containers #hich uses Border (ayout as their default layout?
Answer: )ontainers #hich uses Border (ayout as their default are* #indo#& rame and +ialog
classes.

Question: What do you understand by "ynchronization?
Answer: "ynchronization is a process of controlling the access of shared resources by the
multiple threads in such a manner that only one thread can access one resource at a time. ,n non
synchronized multithreaded application& it is possible for one thread to modify a shared ob%ect
#hile another thread is in the process of using or updating the ob%ect's value. "ynchronization
prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void -ethod. /0 1
22 3ppropriate method4related code.
5
E.g. Synchronizing a block of code inside a function:
public myunction /01
synchronized /this0 1
22 "ynchronized code here.
5
5

Question: What is )ollection 3P,?
Answer: The )ollection 3P, is a set of classes and interfaces that support operation on
collections of ob%ects. These classes and interfaces are more fle!ible& more po#erful& and more
regular than the vectors& arrays& and hashtables if effectively replaces.
Example of classes* HashSet& HashMap& ArrayList& LinkedList& TreeSet and TreeMap.
Example of interfaces* Collection& Set& List and Map.

Question: ,s ,terator a )lass or ,nterface? What is its use?
Answer: ,terator is an interface #hich is used to step through the elements of a )ollection.

Question: What is similarities2difference bet#een an 3bstract class and ,nterface?
Answer: +ifferences are as follo#s*
,nterfaces provide a form of multiple inheritance. 3 class can e!tend only one other class.
,nterfaces are limited to public methods and constants #ith no implementation. 3bstract
classes can have a partial implementation& protected parts& static methods& etc.
3 )lass may implement several interfaces. But in case of abstract class& a class may
e!tend only one abstract class.
,nterfaces are slo# as it re6uires e!tra indirection to to find corresponding method in in
the actual class. 3bstract classes are fast.
"imilarities*
'either 3bstract classes or ,nterface can be instantiated.

Question: 7o# to define an 3bstract class?
Answer: 3 class containing abstract method is called 3bstract class. 3n 3bstract class can't be
instantiated.
8!ample of 3bstract class*
abstract class test3bstract)lass 1
protected "tring my"tring9
public "tring get-y"tring/0 1
return my"tring9
5
public abstract string any3bstractunction/09
5

Question: 7o# to define an ,nterface?
Answer: ,n :ava ,nterface defines the methods but does not implement them. ,nterface can
include constants. 3 class that implements the interfaces is bound to implement all the methods
defined in ,nterface.
8maple of ,nterface*
public interface sample,nterface 1
public void function$ne/09
public long )$'"T3'T;$'8 < .===9
5

Question: 8!plain the user defined 8!ceptions?
Answer: >ser defined 8!ceptions are the separate 8!ception classes defined by the user for
specific purposed. 3n user defined can created by simply sub4classing it to the 8!ception class.
This allo#s custom e!ceptions to be generated /using thro#0 and caught in the same #ay as
normal e!ceptions.
8!ample*
class my)ustom8!ception e!tends 8!ception 1
22 The class simply has to e!ist to be an e!ception
5

Question: 8!plain the ne# eatures of :+B) ?.= )ore 3P,?
Answer: The :+B) ?.= 3P, includes the complete :+B) 3P,& #hich includes both core and
$ptional Pac@age 3P,& and provides inductrial4strength database computing capabilities.
'e# eatures in :+B) ?.= )ore 3P,*
"crollable result sets4 using ne# methods in the Result"et interface allo#s
programmatically move the to particular ro# or to a position relative to its current
position
:+B) ?.= )ore 3P, provides the Batch >pdates functionality to the %ava applications.
:ava applications can no# use the Result"et.updateAAA methods.
'e# data types 4 interfaces mapping the "B(C data types
)ustom mapping of user4defined types />T+s0
-iscellaneous features& including performance hints& the use of character streams& full
precision for %ava.math.Big+ecimal values& additional security& and support for time
zones in date& time& and timestamp values.

Question: 8!plain garbage collection?
Answer: Darbage collection is one of the most important feature of :ava. Darbage collection is
also called automatic memory management as :V- automatically removes the unused
variables2ob%ects /value is null0 from the memory. >ser program cann't directly free the ob%ect
from memory& instead it is the %ob of the garbage collector to automatically free the ob%ects that
are no longer referenced by a program. 8very class inherits finalize( method from
!a"a.lang.#b!ect& the finalize/0 method is called by garbage collector #hen it determines no
more references to the ob%ect e!ists. ,n :ava& it is good idea to e!plicitly assign null into a
variable #hen no more in use. , :ava on calling System.gc( and $untime.gc(% :V- tries to
recycle the unused ob%ects& but there is no guarantee #hen all the ob%ects #ill garbage collected.

Question: 7o# you can force the garbage collection?
Answer: Darbage collection automatic process and can't be forced.

Question: What is $$P"?
Answer: $$P is the common abbreviation for $b%ect4$riented Programming.

Question: +escribe the principles of $$P".
Answer: There are three main principals of oops #hich are called Polymorphism& ,nheritance
and 8ncapsulation.

Question: 8!plain the 8ncapsulation principle.
Answer: 8ncapsulation is a process of binding or #rapping the data and the codes that operates
on the data into a single entity. This @eeps the data safe from outside interface and misuse. $ne
#ay to thin@ about encapsulation is as a protective #rapper that prevents code and data from
being arbitrarily accessed by other code defined outside the #rapper.

Question: 8!plain the ,nheritance principle.
Answer: ,nheritance is the process by #hich one ob%ect ac6uires the properties of another ob%ect.


Question: 8!plain the Polymorphism principle.
Answer: The meaning of Polymorphism is something li@e one name many forms. Polymorphism
enables one entity to be used as as general category for different types of actions. The specific
action is determined by the e!act nature of the situation. The concept of polymorphism can be
e!plained as Eone interface& multiple methodsE.

Question: 8!plain the different forms of Polymorphism.
Answer: rom a practical programming vie#point& polymorphism e!ists in three distinct forms
in :ava*
-ethod overloading
-ethod overriding through inheritance
-ethod overriding through the :ava interface


Question: What are 3ccess "pecifiers available in :ava?
Answer: 3ccess specifiers are @ey#ords that determines the type of access to the member of a
class. These are*
Public
Protected
Private
+efaults


Question: +escribe the #rapper classes in :ava.
Answer: Wrapper class is #rapper around a primitive data type. 3n instance of a #rapper class
contains& or #raps& a primitive value of the corresponding type.
ollo#ing table lists the primitive types and the corresponding #rapper classes*
&rimiti"e 'rapper
boolean !a"a.lang.(oolean
byte !a"a.lang.(yte
char !a"a.lang.)haracter
double !a"a.lang.*ouble
float !a"a.lang.+loat
int !a"a.lang.,nteger
long !a"a.lang.-ong
short !a"a.lang.Short
"oid !a"a.lang..oid


Question: Read the follo#ing program*
public class test 1
public static void main/"tring FG args0 1
int ! < C9
int y < .9
if /! < y0
"ystem.out.println/E'ot e6ualE09
else
"ystem.out.println/E86ualE09
5
5
What is the result?
3. The output is ?86ual?
B. The output in ?'ot 86ual?
). 3n error at E if /! < y0E causes compilation to fall.
+. The program e!ecutes but no output is sho# on console.
Answer: )
Question: #hat is the class variables ?
Answer: When #e create a number of ob%ects of the same class& then each ob%ect #ill share a
common copy of variables. That means that there is only one copy per class& no matter ho#
many ob%ects are created from it. )lass variables or static variables are declared #ith the static
@ey#ord in a class& but mind it that it should be declared outside outside a class. These variables
are stored in static memory. )lass variables are mostly used for constants& variable that never
change its initial value. "tatic variables are al#ays called by the class name. This variable is
created #hen the program starts i.e. it is created before the instance is created of class by using
ne# operator and gets destroyed #hen the programs stops. The scope of the class variable is
same a instance variable. The class variable can be defined any#here at class level #ith the
@ey#ord static. ,t initial value is same as instance variable. When the class variable is defined as
int then it's initial value is by default zero& #hen declared boolean its default value is false and
null for ob%ect references. )lass variables are associated #ith the class& rather than #ith any
ob%ect.
Question: What is the difference bet#een the instanceof and getclass& these t#o are same or
not ?
Answer: instanceof is a operator& not a function #hile get)lass is a method of %ava.lang.$b%ect
class. )onsider a condition #here #e use
if/o.get)lass/0.get'ame/0.e6uals/E%ava.lang.-athE001 5
This method only chec@s if the classname #e have passed is e6ual to %ava.lang.-ath. The class
%ava.lang.-ath is loaded by the bootstrap )lass(oader. This class is an abstract class.This class
loader is responsible for loading classes. 8very )lass ob%ect contains a reference to the
)lass(oader that defines. get)lass/0 method returns the runtime class of an ob%ect. ,t fetches the
%ava instance of the given fully 6ualified type name. The code #e have #ritten is not necessary&
because #e should not compare get)lass.get'ame/0. The reason behind it is that if the t#o
different class loaders load the same class but for the :V-& it #ill consider both classes as
different classes so& #e can't compare their names. ,t can only gives the implementing class but
can't compare a interface& but instanceof operator can.
The instanceof operator compares an ob%ect to a specified type. We can use it to test if an ob%ect
is an instance of a class& an instance of a subclass& or an instance of a class that implements a
particular interface. We should try to use instanceof operator in place of get)lass/0 method.
Remember instanceof opeator and get)lass are not same. Try this e!ample& it #ill help you to
better understand the difference bet#een the t#o.
,nterface one1
5
)lass T#o implements one 1
5
)lass Three implements one 1
5
public class Test 1
public static void main/"tring argsFG0 1
one test. < ne# T#o/09
one test? < ne# Three/09
"ystem.out.println/test. instanceof one09 22true
"ystem.out.println/test? instanceof one09 22true
"ystem.out.println/Test.get)lass/0.e6uals/test?.get)lass/0009 22false
5
5
PAPER : JAVA Sample Question Bank (Solved)
1. Consider te !ollo"in# $ode % "at is te output provided a valid !ile name is #iven on te
$ommand prompt&
import java.io.*;
class Q032{
public static void main(String args[]) tro!s "#c$ption{
%il$&nputStr$am 'in;
int c ( 0;
tr)
{
'in ( n$! %il$&nputStr$am(args[0]);
!il$ ((c ( 'in.r$ad()) *( +,)
{
S)st$m.out.print((car)c);
-
-
catc ("#c$ption $)
{
S)st$m.out.println($);
-
'in.clos$();
-
-;
'ptions :
a. .ompil$+tim$ $rror / 0ariabl$ 'in ma) not av$ b$$n initiali1$d./
b. 2un+tim$ $#c$ption / java.lang.3rra)&nd$#4ut4'5ounds"#c$ption6 0/
c. 2un7s 'in$ displa)ing t$ cont$nts o' t$ 'il$ .
d. .ompil$+tim$ $rror / 8nd$'in$d variabl$6 args/

(. )at is te output !or te !ollo"in# *
class 3{
static int i;
3(){
99i;
-
privat$ int g$t(){
r$turn 99i;
-
-;
class 5 $#t$nds 3{
5(){
i99;
-
int g$t(){
r$turn ( i 9 3);
-
-;
class Q02: $#t$nds 5{
public static void main(String ;a[]){
Q02: obj ( n$! Q02:();
3 ob<a ( n$! 3();
ob<a ( (3)obj;
S)st$m.out.println(ob<a.g$t());
-
-;
'ptions :
a. 2
b. .ompil$ $rror / =o m$tod matcing g$t() 'ound in class Q02>./
c. ?
d. =ull@oint$r"#c$ption tro!n at run+tim$ .

+. )at is te output &
class Q00>{
public static void main(String args[]){
bool$an 'lag ( 'als$;
i' ( 'lag ( tru$)
{
S)st$m.out.println(/tru$/);
-
i' ( 'lag (( 'als$)
{
S)st$m.out.println(/'als$/);
-
-
-;
'ptions :
a. tru$
b. 'als$
c. .ompil$+tim$ $rror / Q00>.java6,,6 &ncompatibl$ t)p$ 'or d$claration. .an7t conv$rt bool$an to
java.lang.5ool$an. /
d. tru$
'als$

,. )at is te output &
class 3{
3(){
S)st$m.out.print(/,/);
-
-;
class Q00? $#t$nds 3{
Q00?(){
S)st$m.out.print(/2/);
-
public static void main(String args[]){
Q00? obj ( n$! Q00?();
S)st$m.out.println(/3/);
-
-;
'ptions :
a. ,23
b. 23
c. 3
d. , A 2 A 3 $ac on a s$parat$ lin$

-. )at is te output &
class Q002{
public static void main(String args[]){
int i ( +,;
S)st$m.out.println(+, BB ,C);
-
-;
'ptions :
a. .ompil$ $rror
b. 2un+tim$ "#c$ption tro!n
c. +,
d. Do )ou $#p$ct m$ to si't t$ bits

.. Predi$t te output *
class Q00:{
public static void main(String args[]){
int i ( +,;
S)st$m.out.println((iE0)F+i6i);
-
-;
'ptions :
a. ,
b. +,
c. .ompil$ $rror
d. 2un+tim$ $rror

/. )ill te !ollo"in# $ompile & 0! 1es "at is te output &
class Q00G{
public static void main(String args[]){
S)st$m.out.println((Hat.abs(&nt$g$r.H&=<03I8")));
JJ%K& &nt$g$r.H&=<03I8" ( +2,LCL:3>L:
-
-;
'ptions :
a. 2,LCL:3>L:
b. .ompil$ "rror
c. +2,LCL:3>L:
d. =$gativ$3rra)Si1$"#c$ption tro!n at runtim$

2. )ill te !ollo"in# $ode $ompile & 0! 1es % "at is te output &
class Q0,2{
Q0,2(int i){
S)st$m.out.println(i);
tis.i ( i;
-
public static void main(String ;a[]){
Q0,2 obj ( n$! Q0,2(,0);
-
-
'ptions :
a. 0
b. ,0
c. null
d. .ompil$ $rror / Q0,2.java6,06 =o variabl$ i d$'in$d in class Q0,2. /
3. )at is te output o! tis $ode &
class Q0,,{
int i;
Q0,,(int i){
S)st$m.out.println(i);
tis.i ( i;
-
public static void main(String ;a[]){
Q0,, obj ( n$! Q0,,(,0);
S)st$m.out.println(obj.i);
-
-
'ptions :
a. ,0
,0
b. .ompil$ $rror / Q0,2.java6,>6 0ariabl$ i ma) not av$ b$$n initiali1$d. /
c. 0
,0
d. ,0
0
14. )at is te output !or tis pie$e &
class M$st{
static bool$an 'lag;
public static void main(String args[]){
i' ( 'lag )
{
S)st$m.out.println('lag);
-
-
-;
'ptions :
a. .ompil$r $rror A bool$an 'lag 6 variabl$ 'lag ma) not av$ b$$n initiali1$d
b. .ompil$r $rror A S)st$m.out.println ( 'lag ) 6 can7t conv$rt bool$an to String
c. tru$
d. 'als$
$. .ompil$s N runs 'in$ !it no output g$n$rat$d

Ans"ers :
1. a
2. 5
3. a
4. a
5. $
6. a
7. $
8. d
9. a
10. e
PAPER : JAVA Sample Question Bank (Solved)
1. )at is te output "en 6est41 $lass is run &
class 3{
3(){
JJsom$ initiali1ation
-
void do<som$ting(){
S)st$m.out.println(/&7m in 3/);
-
-;
class 5 $#t$nds 3{
5(){
JJsom$ initiali1ation
-
void do<som$ting(){
S)st$m.out.println(/&7m in 5/);
-
-;
class M$st0,{
public static void main(String args[]){
3 a ( n$! 5();
a.do<som$ting();
-
-;
'ptions :
a. &7m in 3
b. &7m in 5
c. .ompil$r $rror A 3 a ( n$! 5 ( ) 6 "#plicit cast n$$d$d to conv$rt 3 to 5
d. .lass.ast"#c$ption tro!n at runtim$

(. )at is te output !or te !ollo"in# $ode &
class Q0,L{
public String g$t(int i){
r$turn null;
-
public static void main(String ;a[]){
S)st$m.out.println((n$! Q0,L()).g$t(,));
-
-;
'ptions :
a. 0
b. =ull@oint$r"#c$ption at run+tim$
c. .ompil$ $rror
d. null

+.)at is te output &
class Q0,:{
static 4bj$ct obj;
static String g$t(){
r$turn null;
-
public static void main(String args[]){
S)st$m.out.println((Q0,:.g$t()) (( (Q0,:.obj));
-
-;
'ptions :
a. .ompil$ $rror
b. 2un+tim$ $rror
c. tru$
d. 'als$

,. )at is te output &
class Q0,?{
public String g$t(int i){
r$turn null;
-
public static void main(String ;a[]){
Q0,? obj ( n$! Q0,?();
4bj$ct i ( obj.g$t(,0);
S)st$m.out.println(i.toString());
-
-;
'ptions :
a. null
b. =ull@oint$r"#c$ption at run+tim$
c. .ompil$ $rror
d. 0

-.)at is te output &
class Q0,3{
int i;
Q0,3(int i){
S)st$m.out.println(i);
-
public static void main(String ;a[]){
Q0,3 obj ( n$! Q0,3(,0);
S)st$m.out.println(obj.i);
-
-
'ptions :
a. ,0
,0
b. .ompil$ $rror A S)st$m.out.println ( obj.i ) 6 variabl$ i ma) not av$ b$$n initiali1$d
c. 0
,0
d. ,0
0

.. )at is te output &
class M$st02{
public String '$tc(){
r$turn null;
-
public static void main(String args[]){
M$st02 obj ( n$! M$st02();
String str ( obj.'$tc();
S)st$m.out.println((str9//).toString());
-
-;
'ptions :
a. null
b. .ompil$r $rror A can7t invo;$ a m$tod on null
c. =ull@oint$r"#c$ption tro!n at runtim$
d. .lass.ast"#c$ption tro!n at runtim$

/. )at is te output &
class Q022{
public static void main(String ;a[]){
!il$('als$){
S)st$m.out.println(/Or$at/);
-
-
-;
'ptions :
a. 2un7s !it no output
b. 2un+tim$ $rror / Stat$m$nt not r$ac$d./
c. Or$at
d. .ompil$r $rror A S)st$m.out.println ( /Or$at/) 6 stat$m$nt not r$ac$d

2. )at is te output &
class 3{
static int i;
privat$ int g$t(){
r$turn ,;
-
-;
class 5 $#t$nds 3{
privat$ int g$t(){
r$turn 2;
-
-;
class Q02C $#t$nds 5{
public static void main(String ;a[]){
Q02C obj ( n$! Q02C();
S)st$m.out.println(obj.g$t());
-
-;
'ptions :
a. 2
b. .ompil$ $rror A S)st$m.out.println ( obj.g$t ( ) ) 6 no m$tod matcing g$t ( ) 'ound in class Q02C
c. ,
d. 2
$. =ull@oint$r"#c$ption tro!n at run+tim$ .

3. )at is te output &
class Q02G{
public static void main(String args[]){
bool$an b[] ( n$! bool$an[2];
S)st$m.out.println(b[,]);
-
-;
'ptions :
a. .ompil$ $rror / 0ariabl$ b ma) not av$ b$$n initiali1$d./
b. 2un+tim$ $rror / 0ariabl$ b ma) not av$ b$$n initiali1$d./
c. 'als$
d. tru$

14. Consider te !ollo"in# applet . 0s tere sometin# "ron# "it it & Coose te most
appropriate option ( onl1 one ) .
public class 3pp<M$st $#t$nds 3ppl$t{
3pp<M$st(){
JJsom$ initiali1ation
-
public void paint(Orapics g){
g.dra!String(/3ppl$t start$d/ A ?0 A ?0);
-
-;
'ptions :
a. =otings !rong !it it
b. &t sould ov$rrid$ t$ init ( ) m$tod o' it7s sup$rclass ( 3ppl$t )
c. 3n appl$t subclass can7t ov$rrid$ t$ d$'ault constructor
d. M$ dra!String ( ) m$tod in paint ( ) as !rong numb$r o' argum$nts
$. M$ constructor o' 3pp<M$st must b$ d$'in$d as public

Ans"ers :
.. 5
?. d
C. $
H. 5
I. d
J. a
K. d
L. 5
M. $
.=. e
PAPER : JAVA Sample Question Bank (Solved)

1. )ill te !ollo"in# $ode $ompile & 0! 1es $oose te most $orre$t t"o options .
class Q0,,{
public static void main(String args[]){
car a ( 7a7 9 2;
S)st$m.out.println(a);
int i ( 2;
car c ( 7a7 9 i;JJ+++,
S)st$m.out.println(c);JJ+++2

-
-;
'ptions :
a. .ompil$+tim$ $rror / "#plicit cast n$$d$d to conv$rt int to car /
b. M$ cod$ can b$ mad$ to compil$ b) comm$nting out lin$s mar;$d as , N 2
c. M$ cod$ can b$ mad$ to compil$ b) comm$nting out t$ lin$ / car a ( 7a7 9 2; /
d. M$ output is
>C
>C

(. )at is te output & 780 ( int ) ' A ' = 65
class Q,{
public static void main(String args[]){
b)t$ b ( >?;
s!itc (b)
{
cas$ 7376
S)st$m.out.println(/3/);
br$a;;
cas$ >?6
S)st$m.out.println(/>?/);
br$a;;
d$'ault6
S)st$m.out.println(/d$'ault/);

-
-
-;
'ptions :
a. 3
b. >?
c. .ompil$ tim$ $rror A cas$ >? 6 duplicat$ cas$ lab$l
d. 2untim$ $rror /Duplicat$ cas$ lab$l6 >?/
$. d$'ault

+. )ill te output !rom te !ollo"in# t"o $ode snippets 5e an1 di!!erent &
Snipp$t , 6
'or ( int i ( 0 ; i E ? ; i99 )
{
S)st$m.out.println(i);
-
Snipp$t 2 6
'or ( int i ( 0 ; i E ? ; 99i )
{
S)st$m.out.println(i);
-
'ptions :
a. )$s
b. no

,. )at is te output o! te !ollo"in# $ode & 780 1 divided 51 ( 9 4.-
class Q00G{
public static void main(String args[]){
'loat ' ( ,J2;
S)st$m.out.println(');
-
-;
'ptions :
a. .ompil$+tim$ $rror 'loat ' ( , J 2 6 $#plicit cast n$$d$d to conv$rt int to 'loat
b. 0.0
c. 0.?
d. .lass.ast"#c$ption tro!n at run+tim$

-. )at is te output !or te !ollo"in# $ode &
class Morm$nt{
int i ( 2;
public static void main(String args[]){
int i ( ,2;
S)st$m.out.println(i);
-
-;
'ptions :
a. .ompil$r $rror A S)st$m.out.println ( i ) 6 can7t ma;$ a static r$'$r$nc$ to a non static variabl$ i
b. 4utput ( 2
c. 4utput ( ,2
d. .ompil$r $rror A i ( ,2 6 variabl$ i is alr$ad) d$'in$d in tis class

.. )at is te output &
class %$ar%actor){
static{
S)st$m.out.println(/O$n$sis/);
-
%$ar%actor)(){
S)st$m.out.println(/5irt/);
-
public static void main(String args[]){
JJ&7m Ia1)
-
-;
'ptions :
a. 4utput ( 5irt
b. 4utput ( O$n$sis
c. =o output g$n$rat$d
d. .ompil$r $rror A S)st$m.out.println ( / O$n$sis / ) 6 t)p$ $#p$ct$d

/. Consider te !ollo"in# $lass . )i$ o! te marked lines need to 5e $ommented out !or te
$lass to $ompile $orre$tl1 &
class "volv${
static int i ( ,;
static int j ( 2;
int # ( 3;
static int ) ( >;
public static void main(String args[]){
S)st$m.out.println(i 9 j);JJ+++,
S)st$m.out.println(# 9 i);JJ+++2
S)st$m.out.println(i 9 ));JJ+++3
S)st$m.out.println(# 9 j);JJ+++L
-
-;
'ptions :
a. , N 2
b. , A2 N L
c. 3 N L
d. 2 N L
$. , A 2 N 3

2. )at is te $ompiler error #enerated ( i! an1 ) 51 te !ollo"in# pie$e o! $ode .
class P$ll){
public static void main(String args[]){
'loat ' ( ,.J2;
S)st$m.out.println(');
-
-;
'ptions :
a. 'loat ' ( ,. J 2 6 invalid num$ric t)p$
b. 'loat ' ( ,. J 2 6 $#plicit cast n$$d$d t conv$rt int to 'loat
c. S)st$m.out.println ( ' ) 6 can7t invo;$ a m$tod on primitiv$ data t)p$s
d. =o probl$m A t$ cod$ compil$s 'in$ .
$. 'loat ' ( ,. J 2 6 $#plicit cast n$$d$d to conv$rt doubl$ to 'loat

3. )ill te !ollo"in# $lass $ompile & 0! 1es "at is te output &
class "nv){
static int i;
"nv)(){
99i;
-
public static void main(String args[]){
S)st$m.out.println(i);
-
-;
'ptions :
a. K$s A it compil$s but =ull@oint$r"#c$ption tro!n at runtim$
b. .ompil$r $rror A S)st$m.out.println ( i ) 6 variabl$ i ma) not av$ b$$n initiali1$d
c. K$s it compil$s N output ( 0
d. K$s it compil$s N t$ output ( ,
$. .ompil$r $rror A 99 i 6 can7t ma;$ a nonstatic r$'$r$nc$ to a static variabl$ A i

14. Coose all te valid de$larations !or te main metod !rom te list 5elo" ( an1 tree )
a. public void main(String args[])
b. public static int main(String args[])
c. public static void main(String [] ;a)
d. public static void main(String [] args)
$. public static void main(String ;a [])


Ans"er :
.. a : 5
?. $
C. 5
H. 5
I. $
J. 5
K. d
L. e
M. $
.=. $ % d : e
/a"a )ertification 0odel Question 1 Answer
2 3
,. Qat ma;$s a Mr$ad to stop $#$cution
a. 3n int$rrupt$d $#c$ption is tro!n
5. 0nvoke sleep() metod
$. ;i#er priorit1 tread takes over
d. )ile a tread does a read() usin# inputstream
2. Qic is t$ corr$ct $#pr$ssion to b$ us$d to r$ad lin$ b) lin$ and stor$ t$ r$sult
into a String obj$ct
a) %il$ ' ( n$! %il$(/t$st.t#t/);
b. %il$&nputStr$am ' ( n$! %il$&nputStr$am(/t$st.t#t/);
c. Data&nputStr$am d ( n$! Data&nputStr$am(n$! %il$&nputStr$am(/t$st.t#t/));
d. Bu!!eredReader 5r 9 ne" Bu!!eredReader(ne" 0nputStreamReader(ne"
7ile0nputStream(<test.t=t<)))>
$. 5u''$r$d2$ad$r br ( n$! 5u''$r$d2$ad$r(n$! &nputStr$am2$ad$r(n$!
%il$&nputStr$am(/t$st.t#t/A /::?G<,)));
3. Qic o' t$ 'ollo!ing !ill not tro! a =ull@oint$r"#c$ptionF
String s ( null;
a. i' ((s*(null) N (s.l$ngt() B 0))
5. i! ((s?9null) :: (s.len#t() @ 4))
c. i' ((s((null) R (s.l$ngt() (( 0))
d. i! ((s99null) AA (s.len#t() 99 4))
L. Qic o' t$ 'ollo!ing d$scrib$s a 'ull) $ncapsulat$d classF
a. H$tods cannot b$ privat$
b. 0ariabl$s cannot b$ privat$
$. 6e state o! te o5Be$t $an onl1 5e modi!ied trou# a$$essor metod.
d. All varia5les are private.
$. 3ll variabl$s and all m$tods ar$ privat$
?. Qic stat$ d$cid$ a var. SaS !ic is suitabl$ 'or r$'$rring to an arra) o' ?0 string
obj$ctsF
a. car a[ ] [ ];
5. Strin# a C D>
$. Strin# C D a>
d. 4bj$ct a [?0];
$. String a[?0];
>. &n t$ 'ollo!ing programA i' somecondition() is tru$A t$n onl) lin$ numb$r 3 must
tro! a custom $#c$ption MyException. MyException is not a subclass o' runtim$
$#c$ptions. Qat ar$ t$ cang$s to b$ mad$ to t$ giv$n m$tod.
,. @ublic void m$tod() {
2. &' (som$condition()) {
3.
L. -
?.
>. -
a. 3dd tro!s n$! H)"#c$ption(); in lin$ numb$r 3
b. 3dd tro!s n$! H)"#c$ption(); in lin$ numb$r ?
$. Add tro" ne" E1E=$eption()> in line num5er +
d. Eodi!1 te metod de$laration su$ tat an o5Be$t o! t1pe E=$eption is to
5e tro"n
C. Qat is t$ output o' t$ 'ollo!ing program
public class "#ampl${
privat$ int i;
public static void main(String args[]) {
m$tod() ;
-
public static void m$tod() {
int j;
j( i;
S)st$m.out.println(/M$ valu$ o' i is / 9i);
-
-
a. M$ program prints M$ valu$ o' i is 0;
b. M$ program giv$s a compilation $rror. 5) canging t$ privat$ int i to public int i
t$ probl$m g$ts r$solv$d
$. 6e pro#ram #ives a $ompilation error. B1 $an#in# te private int i to
private stati$ int i te pro5lem #ets resolved
d. 6e pro#ram #ives a $ompilation error. B1 $an#in# te pu5li$ stati$ o! te
metod to pu5li$ onl1 and ten $allin# tis metod !rom te main usin# an
instan$e o! E=ample% te pro5lem #ets resolved.
:. Qic o' t$ 'ollo!ing ar$ tru$F
Iong IG ( n$! Iong(G);
Iong I,0 ( n$! Iong(G);
Iong I,, ( I,0;
long 3 ( G;
long 5 ( G;
a. IG (( I,0
b. IG (( I,,
$. F14 99 F11
d. 3 (( IG
e. A 99 B
G. To! sould !$ ma;$ a class to andl$ t$ $v$nts g$n$rat$d b) a singl$ us$r
int$r'ac$ compon$ntF
a. Subclassing a adapt$r class is inappropriat$ in tis cas$ + %als$
5. 0mplements $lass "i$ andles all te user inter!a$e listener metods *
6rue

,0. Qat ar$ t$ assignm$nts !ic ar$ valid in t$ lin$ UUUU
class Sup$r{
privat$ int i;
public int ma<cd('loat '){
i ( (int) ';
r$turn i; --
class Sub $#t$nds Sup$r{
int j;
'loat g;
public Sub(){
Sup$r s ( n$! Sup$r();
UUUU -
-
a. j ( i;
b. g ( ';
$. B 9 s.maG$d(+.(!)>
d. j ( s.i;
$. g ( s.';
,,. Qat is t$ output o' t$ abov$ cod$F
out$r 6 'or(int # ( 0 ; #E2 ; #99){
inn$r6 'or(int a ( 0 ; a E 2 ; a99){
i' (a((,) {
br$a; inn$r;
-
S)st$m.out.println(/ a is / 9 a 9 / # is / 9 # );
-
-
a. a is 4 = is 4
5. a is 4 = is 1
$. a is 4 = is (
d. a is 1 = is 4
e. a is 1 = is 1
!. a is 1 = is (
#. a is ( = is 4
. a is ( = is 1
i. a is ( = is (
1(. )i$ is te earliest possi5le instan$e tat Har5a#e Colle$tion is a$tivated !or
Strin# $reated in line 1.
pu5li$ stati$ void main(Strin# ar#sC D)I
1. Strin# s 9 <a5$d<>
(. Strin# s1 9 <e!#i<>
+. Strin# s( 9 sJ s1>
,. s 9 null>
-. s 9 s1>
.. s1 9 s>
a. Be!ore Fine +.
5. Be!ore Fine ,.
$. Be!ore Fine -.
d. Be!ore line ..
1+. 6ere is a plan to prepare a $lass "i$ is #oin# to used in man1 unrelated
parts o! te proBe$t. 6e $lass sould 5e Pol1#on o5Be$t "i$ is a Sape. 6e
pol1#on as a in!ormation a5out te $oordinates stored in a ve$tor% $olor status
"i$ states "eter true or !alse. )rite a $lass de$laration "i$ des$ri5es te
a5ove
pu5li$ $lass Pol1#on e=tends SapeI
ve$tor $oord>
5oolean $olorstatus>
K
1,. 6ere is an Emplo1ee "o is a Person. 6e emplo1ee stores details in a
Ve$tor% date emplo1ed and num5er o! instan$es. )at are te t1pe o!
varia5les tat is to 5e added to te Emplo1ee $lass
a. Ve$tor
5. Late
$. '5Be$t
d. Person
e. Emplo1ee
!. 0nt
1-. )at is te $onstru$tor ar#ument !or te 7ilter0nputStream
a. 7ile
5. 0nputStream
$. Lata0nputStream
d. Bu!!eredReader
e. 0nputStreamReader
1.. )at is te e=ade$imal representation o! / (not more tat , $ara$ters)
4=/
1/. )at is te output o! te !ollo"in# pro#ram E=ample i! ar#sC4D is printed
Bava E=ample $at do#
a. do#
5. $at
$. E=ample
d. Bava
e. Mull PointerE=$eption is tro"n
12. )at is te modi!ier !or all te listener metods
a. private
5. de!ault (no a$$ess modi!ier spe$i!ied)
$. prote$ted
d. pu5li$
e. stati$
13. )i$ o! te !ollo"in# is true re#ardin# HridBa#Fa1out
a. i! a $omponent as 5een #iven !ill 5ot is true% ten as te $ontainer
resiNes te $omponent resiNes
5. 6e num5er o! ro"s and $olumns are !i=ed "ile loadin# te $omponents.
$. 6e num5er o! ro"s and $olumns are !i=ed "ile loadin# te la1out itsel! .
d. i! a $omponent as a non*Nero "ei#t1 value% ten te $omponent #ro"s in
ei#t as te $ontainer is resiNed.
(4. )at is te value o! =% i! <6est +< to 5e printed
S"it$(=)I
Case 1: S1stem.out.println(<6est 1<)>
Case (:
Case +: S1stem.out.println(<6est +<)> 5reak>
de!ault : S1stem.out.println(<6est ,<)> 5reak>
K
a. 1
5. (
$. +
d. ,
e. 4
(1. 0! te strin# arra1 name is ar#$ in te ar#uments in te main metod% "i$ is
invoked 51 te interpreter "en a pro#ram is e=e$uted
a. $ar strin# C D C D
5. $ar C D a C D
$. $ar aC D
d. Strin# ar#$
e. Strin# ar#vC D
!. Strin# ar#$C D
((. )at is te ar#ument o! te Oe1Fistener metods
Oe1Event
(+. )at is te $orre$t de$laration o! an a5stra$t metod
a. pu5li$ a5stra$t metod()> PP no ret t1pe
5. pu5li$ void a5stra$t metod(): PP position ret t1pe
$. pu5li$ a5stra$t void metod() IK PP no 5od1
d. pu5li$ !inal a5stra$t void metod()> PP !inal a5s $annot $ome to#eter
e. pu5li$ a5stra$t void metod () >
(,. ;o" "ill 1ou override or overload te !ollo"in# metod metod1 o! te Super
$lass in te $lass Su5&
$lass SuperI
prote$ted void metod1() IK
K
$lass Su5 e=tends SuperIK
a. pu5li$ void metod1() I return 4> K
5. pu5li$ int metod1() I return 4> K
$. pu5li$ void metod1(Strin#Bu!!er s) I K
d. pu5li$ void metod1() I K
e. pu5li$ void metod1(Strin# s) I K
(-. )at is te value o! = i! 6est + is to 5e printed
i! (= @ ,) I
S1stem.out.println( <6est 1< )>
K else i! (=@ 3)I
S1stem.out.println(<6est (<)>
K else
S1stem.out.println(<6est +<)>
a. 4 to ,
5. Fess tan 4
$. - to 3
d. Hreater tan 14
(.. )at is te ran#e o! a $ar t1pe&
4 Q (
1.
*1
(/. )at does @@ and @@@ denotes
A. @@ is ri#t si!t @@@ is round
B. @@ is si#ned ri#t si!t @@@ round
C. @@ is si#ned si!t and @@@ is unsi#ned si!t
L. @@ is unsi#ned @@@ is unsi#ned
(2. )at are valid ke1"ords
a. MRFF
5. 6RRE
$. implements
d. inter!a$e
e. instan$eo!
!. siNeo!
(3. )i$ o! te !ollo"in# sould 5e used to ave Mo 'rder% Lupli$ation or
Per!e$t retrieval me$anism
a. Eap PP no order% no dupe% per!e$t retrive
5. Fist PPorder% dupe% no ret
$. Set PPno order% no dupe% not per!e$t retrieve
d. Colle$tion PPno order% dupes% no ret
+4. 0n "i$ Fa1outEana#er% a $omponent to 5e added to ave onl1 te "idt
resiNed 5ut not te ei#t
a. 7lo"Fa1out
5. HridFa1out
$. HridBa#Fa1out
d. East or )est o! BorderFa1out
e. Mort or Sout o! BorderFa1out
+1. )at is te a$$ess modi!ier !or a $lass mem5er varia5le "i$ is to 5e used in
te same pa$ka#e "ere te $lass is de!ined
a. protected
b. private
c. public
d. no access modifier
e. static
32. What is the body of a hread
a. run
b. be!in
c. e"ecute
d. start
e. resume
33. What is the output of the follo#in! code$
int i = %&
do '
(ystem.out.println()he value of i is ) * i)&
+#hile(,,i - %)
(ystem.out.println().inished))&
a. he value of i is /
b. he value of i is %
c. .inished
d. Compilation Error ( no ; after while condn);
e. 0untime 1rror
32. What is the output of the follo#in! pro!ram
class 1"ample'
static int arr34 = ne# int3/%4&
public static void main((trin! ar!s34)'
(ystem.out.println() he value 2
th
element is ) * arr324)&
+ +
a. he value of 2
th
element is 2
b. he value of 2
th
element is null
c. he value of 2
th
element is %
d. 5ull 6ointer e"ception is raised
e. 0untime error7 because the class is not instantiated
35. Which of the follo#in! is the correct class declaration for 8ar.9ava. (ee to that
it is a case,sensitive system
a. public class 8ar'
int in&
public 8ar(int inn)'
in = inn
+ +
b. public class 8ar e"tends ruc:7 ;ehicle'
int in&
public 8ar(int inn)'
in = inn&
+ +
c. public class 8ar'
int in&
public abstract void race8ar() '(ystem.out.println()0ace8ar))&+
public 8ar(int inn)'
in = inn&
+ +
d. import 9ava.io.<&
public class 8ar e"tends =b9ect'
int in&
public 8ar(int inn)'
in = inn&
+ +
36. Which of the follo#in! are true about hreads$
a. hreads can only be created by e"tendin! the 9ava.lan!.hread
b. hreads of the same pro!ram end to!ether
c. A thread #hich is suspended7 cannot be restarted
d. >ncoordination of threads7 #ill result in the data be corrupted
e. ?ava @nterepter #ill e"it only #hen all non,demon threads are not ended
3A. What is true about Barba!e 8ollection mechanism
a. Barba!e 8ollection releases memory at predictable times and at
predictable rates
b. A correct pro!ram is one in #hich does not depend on the memory release
by the !arba!e collector
c. A pro!rammer can indicate to the !c mechanism by ma:in! reference to a
variable as null
d. Barba!e collection ensures that there may not be any lea:a!e of memory.
3C. A Duestion on 1Duality operator
=:
3E. What is the output of the follo#in! pro!ram$
class (uper'
(trin! name&
(uper((trin! s)'
name =s &
+ +
class (ub e"tends (uper'
(trin! name&
(ub((trin! s)'
name=s&
+
public static void main((trin! ar!s34)'
(uper sup = ne# (uper().irst))&
(ub sub = ne# (ub()(econd))&
(ystem.out.println(sub.name * ) ) * sup.name)&
+
+
a. .irst (econd
b. (econd .irst
c. 8ompilation error
d. 0untime error statin! same name found in (uper as #ell as in the (ub
class
2%. An @=1"ception needs to be thro#n in some method of a pro!ram. (elect the
correct e"pression for the raisin! an e"ception
a. ne# 1"ception()&
b. thro# 1"ception()&
c. thro# ne#(ne# @=1"ception())&
d. thro# ne# 1"ception()& FF its actually thro# ne# @=1"ception()&
e. thro#s ne# 1"ception()&
2/. A Guestion on Hethod =verridin!
=I
22. What is the output of the follo#in! pro!ram if method/() does not thro# any
e"ception$
try'
method/()&
(ystem.out.println().irst))&
+catch (1"ception e)'
(ystem.out.prinln()(econd))&
+finally'
(ystem.out.println().inally))&
+ (ystem.out.println()Jast))&
a. .irst follo#ed by .inally
b. .irst follo#ed by .inally follo#ed by Jast
c. .irst follo#ed by Jast
d. .irst
23. What are the modifier #hich cannot be used for a local automatic variable
a. default ( no access modifier )
b. final
c. static
d. public
22. What does !et@K() method of the event return
a. time of the event
b. source of the event
c. nature of the cause of the event
d. place of the event
25. What cannot be added to a container
a. Applet
b. 6anel
c. 8omponent
d. 8ontainer
e. Henu@tem FF can be added only to a Henu
26. Lo# to invo:e the constructor from a constructor in the same class
class (uper'
float "&
float y&
float M&
(uper(float a7 float b)'
" = a&
y = b&
+
(uper(float a7 float b7 float c)'
NNNN
M = c&
+
+
a. super(a7b)&
b. (uper(a7b)&
c. this(a7b)&
d. his(a7b)&
2A. What is true about inner classes$
a. @nner classes have to be instantiated only in the enclosin! class
b. @nner classes can access all the final variables of the enclosin! class
c. @nner classes cannot be static
d. @nner classes cannot be anonymous class
e. @nner classes can e"tend another class.
2C. What are the correct declaration for an inner class
a. private class 8
b. ne# simpleinterface() ' FFAnonymous so v can use ne#
c. ne# comple"interface(") '
d. ne# innerclasses() e"tends someotherclass '
e. ne# innerclasses e"tends someotherclass ' FF5ot as #e have !iven a name
and so v cannot use ne#
2E. What are true about Jistener interfaces
a. A component can have only one listener attached to it
b. @f a component has multiple listeners attached7 the order in #hich the
listeners are invo:ed are un:no#n
c. @f a component has multiple listeners7 then all the listeners have to be
friends
5%. @f a class member variable is initialiMed and the value is not be chan!ed at all7
#hat is the modifier to be used durin! the declaration of the variable
a. const
b. fi"ed
c. public
d. static
e. final
5/. What #ill happen if the follo#in! assi!nment is made7 ta:e the above into
account$
class 6arent
class Kerived/ e"tends 6arent
class Kerived2 e"tends 6arent
6arent p&
Kerived d/&
p = d/&
a. Je!al at compile time and ille!al at run time
b. Je!al at compile time and possibly le!al at run time
c. Je!al at compile time and definitely le!al at run time
d. @lle!al at compile time
52. Which modifiers are to be used to obtain the loc: on the ob9ect
a. public
b. private
c. static
d. synchorniMed
e. loc:
53. What can be possibly used at 6oint N
FF 6oint N
public class 1"ample
a. import 9ava.a#t.<&
b. pac:a!e local.util&
c. class 5o1"ample'+
d. protected class (imple1"ample
e. public static final double 6@ = 3./2&
52. What is the ran!e of int type
,2
3/
to 2
3/
,/
55. What is the output of the follo#in! pro!ram$
class (uper'
(trin! firstname&
(trin! secondname&
(uper()'+
(uper((trin! f7 (trin! s)'
firstname = f&
secondname = s&
+
public (trin! to(trin!()'
return )@t is Honopoly Hr. ) * firstname&
++
class (ub e"tends (uper'
(trin! firstname&
(trin! secondname&
(ub((trin! f7 (trin! s)'
firstname = f&
secondname = s&
+
public (trin! to(trin!()'
return )@t is Honopoly Hr. ) * secondname * ) )* firstname&
++
class est'
public static void main((trin! ar!s34)'
(uper first = ne# (uper()(cott)7 )Hc5ealy))&
(uper second = ne# (ub()Oill)7)Bates))&
(ystem.out.println( second * ) Pn ) *first)&
++
a. @t is Honopoly Hr. Oill Bates
@t is Honopoly Hr. (cott
b. @t is Honopoly Hr. Bates Oill
@t is Honopoly Hr. Hc5ealy
c. @t is Honopoly Hr. Bates Oill
@t is Honopoly Hr. (cott
d. @t is Honopoly Hr. Bates
@t is Honopoly Hr. (cott Hc5ealy
56. Lo# to instantiate the class @nner at point NNNN
class =uter'
class @nner'
+
public static void main((trin! ar!s34)'
NNNN
+
+
a. ne# @nner()&
b. @nner i = =uter.ne# @nner()&
c. =uter.@nner i = ne# =uter().ne# @nner()&
d. @nner i = =uter(ne# @nner())&
5A. What is the output of the follo#in! pro!ram
public class 1"ample'
(tac: s/&
(tac: s2&
public static void main((trin! ar!s34)'
ne# 1"ample()&
+
public 1"ample() '
s/ = ne# (tac:()&
s2 = ne# (tac:()&
method/(s/7s2)&
(ystem.out.println(s/ * ) ) * s2)&
+
public void method/((tac: ms/7 (tac: ms2)'
ms2.push(ne# Jon!(/%%))&
ms/ = ms2&
+
+
a. 8ompilation error since ms2 cannot be assi!ned to ms/.
b. s/ 3 4 s2 3 4
c. s/ 3 4 s2 3/%%4
d. s/ 3/%%4 s2 3/%%4
5C. What are the le!al identifers in ?ava$
a. Qemployee
b. Remployee
c. employ,ee
d. employee/
e. Semployee
5E. Which of the follo#in! are true about the listener mathods in AW$ (8)
a. @n a#t listener menthods !enerally ta:es an ar!ument #hich is an instance
of some subclass of 9ava.a#t.AW1vent
b. When multiple listeners are added to a sin!le component the order of
invocation of the listeners is not specified.
c. A sin!le component can have multiple listeners added to it.
(11)What is HashMap and Map?
Map is Interface and Hashmap is class that implements that and its not serialized HashMap is
non serialized and Hashtale is serialized
(12)Difference between HashMap and HashTable?
!he HashMap class is ro"#hl$ e%"i&alent to Hashtale' e(cept that it is "ns$nchronized and
permits n"lls. )HashMap allo*s n"ll &al"es as +e$ and &al"e *hereas Hashtale doesnt allo*,.
HashMap does not #"arantee that the order of the map *ill remain constant o&er time.
(12a) Difference between Vector and ArrayList?
-ector is serialized *hereas arra$list is not

(1)Difference between !win" and Awt?
./! are hea&$*ei#ht componenets. 0*in#s are li#ht*ei#ht components. Hence
s*in# *or+s faster than ./!.
1#) $%plain types of $nterprise &eans?
!ession beans ' .ssociated *ith a client and +eeps states for a client
$ntity &eans ' 1epresents some entit$ in persistent stora#e s"ch as a dataase
1() What is enterprise bean?
0er&er side re"sale 2a&a component
3ffers ser&ices that are hard to implement $ the pro#rammer
!)n* 4nterprise 5ean architect"re is a component architect"re for the deplo$ment and
de&elopment of componentased distri"ted "siness applications. .pplications *ritten "sin#
enterprise 2a&a eans are scalale' transactional and m"lti"ser sec"re. !hese applications ma$
e *ritten once and then deplo$ed on an$ ser&er plattform that s"pports enterprise 2a&a eans
specification.
4nterprise eans are e(ec"ted $ the 6244 ser&er.
7irst &ersion 1.0 contained session eans' entit$ eans *ere not incl"ded. 4ntit$ eans *ere
added to &ersion 1.1 *hich came o"t d"rin# $ear 1999. 8"rrent release is 465 &ersion 1.2

1+)!er,ices of $-&?
9ataase mana#ement :
;9ataase connection poolin#
;9ata0o"rce' offered $ the 6244 ser&er. <eeded to access connection pool of the ser&er.
;9ataase access is confi#"red to the 6244 ser&er = eas$ to chan#e dataase > dataase
dri&er
Transaction .ana"e.ent *
;9istri"ted transactions
;6244 ser&er offers transaction monitor *hich can e accessed $ the client.
!ec)rity .ana"e.ent *
;."thetication
;."thorization
;encr$ption
4nterprise 2a&a eans can e distri"ted >replicated into separate
machines 9istri"tion>replication offers
;?oad alancin#' load can e di&ided into separate ser&ers.
;7ailo&er' if one ser&er fails' others can +eep on processin# normall$.
;@erformance' one ser&er is not so hea&$ loaded. .lso' for e(ample /elo#ic has thread pools
for impro&in# performance in one ser&er.
)ore :ava ,ntervie# Buestion Page C
Posted on* -arch ?J& ?==L at .?*== 3-
Question: 'hen you declare a method as abstract method 4 Answer: 'hen i want
child class to implement the beha"ior of the method.
)ore /a"a ,nter"iew Question &age 5

Question: When you declare a method as abstract method ?
Answer: When i #ant child class to implement the behavior of the method.
Question: )an , call a abstract method from a non abstract method ?
Answer: Nes& We can call a abstract method from a 'on abstract method in a :ava abstract class

Question: What is the difference bet#een an 3bstract class and ,nterface in :ava ? or can you
e!plain #hen you use 3bstract classes ?
Answer: 3bstract classes let you define some behaviors9 they force your subclasses to provide
others. These abstract classes #ill provide the basic funcationality of your applicatoin& child class
#hich inherited this class #ill provide the funtionality of the abstract methods in abstract class.
When base class calls this method& :ava calls the method defined by the child class.
3n ,nterface can only declare constants and instance methods& but cannot implement
default behavior.
,nterfaces provide a form of multiple inheritance. 3 class can e!tend only one other class.
,nterfaces are limited to public methods and constants #ith no implementation. 3bstract
classes can have a partial implementation& protected parts& static methods& etc.
3 )lass may implement several interfaces. But in case of abstract class& a class may
e!tend only one abstract class.
,nterfaces are slo# as it re6uires e!tra indirection to find corresponding method in the
actual class. 3bstract classes are fast.
Question: What is user4defined e!ception in %ava ?
Answer: >ser4defined e!pections are the e!ceptions defined by the application developer #hich
are errors related to specific application. 3pplication +eveloper can define the user defined
e!ception by inherite the 8!ception class as sho#n belo#. >sing this class #e can thro# ne#
e!ceptions.
Java Example : public class nound8!ception e!tends 8!ception 1 5 Thro# an e!ception using
a thro# statement* public class und 1 ... public $b%ect getunds/0 thro#s nound8!ception 1 if
/8mpty/00 throw ne# nound8!ception/09 ... 5 5 >ser4defined e!ceptions should usually be
chec@ed.
Question: What is the difference bet#een chec@ed and >nchec@ed 8!ceptions in :ava ?
Answer: 3ll predefined e!ceptions in :ava are either a chec@ed e!ception or an unchec@ed
e!ception. )hec@ed e!ceptions must be caught using try .. catch/0 bloc@ or #e should thro# the
e!ception using thro#s clause. ,f you dont& compilation of program #ill fail.
Java Exception Hierarchy O44444444O P $b%ect P O44444444O P P O44444444444O P Thro#able P O44444444444
O 2 Q 2 Q O4444444O O44444444444O P 8rror P P 8!ception P O4444444O O44444444444O 2 P Q 2 P Q Q;;;;;;;;2
Q;;;;;;2 Q O444444444444444444O unchec@ed chec@ed P Runtime8!ception P O444444444444444444O 2 P P Q
Q;;;;;;;;;;;;;;;;;2 unchec@ed
Question: 8!plain garbage collection ?
Answer: Darbage collection is an important part of :ava's security strategy. Darbage collection
is also called automatic memory management as :V- automatically removes the unused
variables2ob%ects from the memory. The name Egarbage collectionE implies that ob%ects that are
no longer needed by the program are EgarbageE and can be thro#n a#ay. 3 more accurate and
up4to4date metaphor might be Ememory recycling.E When an ob%ect is no longer referenced by
the program& the heap space it occupies must be recycled so that the space is available for
subse6uent ne# ob%ects. The garbage collector must someho# determine #hich ob%ects are no
longer referenced by the program and ma@e available the heap space occupied by such
unreferenced ob%ects. ,n the process of freeing unreferenced ob%ects& the garbage collector must
run any finalizers of ob%ects being freed.
Question: 7o# you can force the garbage collection ?
Answer: Darbage collection automatic process and can't be forced. We can call garbage
collector in :ava by calling "ystem.gc/0 and Runtime.gc/0& :V- tries to recycle the unused
ob%ects& but there is no guarantee #hen all the ob%ects #ill garbage collected.
Question: What are the field2method access levels /specifiers0 and class access levels ?
Answer: 8ach field and method has an access level*
private* accessible only in this class
/pac@age0* accessible only in this pac@age
protected* accessible only in this pac@age and in all subclasses of this class
public* accessible every#here this class is available
Similarly% each class has one of two possible access le"els:
/pac@age0* class ob%ects can only be declared and manipulated by code in this pac@age
public* class ob%ects can be declared and manipulated by code in any pac@age
Question: What are the static fields R static -ethods ?
Answer: ,f a field or method defined as a static& there is only one copy for entire class& rather
than one copy for each instance of class. static method cannot accecss non4static field or call
non4static method
8!ample :ava )ode
static int counter < =9
3 public static field or method can be accessed from outside the class using either the usual
notation*
:ava4class4ob%ect.field4or4method4name
or using the class name instead of the name of the class ob%ect*
:ava4 class4name.field4or4method4name
Question: What are the inal fields R inal -ethods ?
Answer: ields and methods can also be declared final. 3 final method cannot be overridden in
a subclass. 3 final field is li@e a constant* once it has been given a value& it cannot be assigned to
again.
:ava )ode
private static final int -3A3TT8-PT" < .=9
Question: +escribe the #rapper classes in :ava ?
Answer: Wrapper class is #rapper around a primitive data type. 3n instance of a #rapper class
contains& or #raps& a primitive value of the corresponding type.
ollo#ing table lists the primitive types and the corresponding #rapper classes*
&rimiti"e 'rapper
boolean %ava.lang.Boolean
byte %ava.lang.Byte
char %ava.lang.)haracter
double %ava.lang.+ouble
float %ava.lang.loat
int %ava.lang.,nteger
long %ava.lang.(ong
short %ava.lang."hort
void %ava.lang.Void
Question: What are different types of inner classes ?
Answer: ,nner classes nest #ithin other classes. 3 normal class is a direct member of a pac@age.
,nner classes& #hich became available #ith :ava ...& are four types
"tatic member classes
-ember classes
(ocal classes
3nonymous classes
Static member classes 4 a static member class is a static member of a class. (i@e any other static
method& a static member class has access to all static methods of the parent& or top4level& class.
0ember )lasses 4 a member class is also defined as a member of a class. >nli@e the static
variety& the member class is instance specific and has access to any and all methods and
members& even the parent's this reference.
-ocal )lasses 4 (ocal )lasses declared #ithin a bloc@ of code and these classes are visible only
#ithin the bloc@.
Anonymous )lasses 4 These type of classes does not have any name and its li@e a local class
:ava 3nonymous )lass 8!ample public class "omeD>, e!tends :rame 1 ... button member
declarations ... protected void buildD>,/0 1 button. < ne# :Button/09 button? < ne# :Button/09 ...
button..add3ction(istener/ ne# %ava.a#t.event.3ction(istener/0 S444444 3nonymous )lass
1 public void actionPerformed/%ava.a#t.event.3ction8vent e0 1 22 do something 5 5 09
Question: What are the uses of "erialization?
Answer: ,n some types of applications you have to #rite the code to serialize ob%ects& but in
many cases serialization is performed behind the scenes by various server4side containers.
These are some of the typical uses of serialization*
To persist data for future use.
To send data to a remote computer using such client2server :ava technologies as R-, or
soc@et programming.
To EflattenE an ob%ect into array of bytes in memory.
To e!change data bet#een applets and servlets.
To store user session in Web applications.
To activate2passivate enterprise %ava beans.
To send ob%ects bet#een the servers in a cluster.
Question: #hat is a collection ?
Answer: )ollection is a group of ob%ects. %ava.util pac@age provides important types of
collections. There are t#o fundamental types of collections they are )ollection and -ap.
)ollection types hold a group of ob%ects& 8g. (ists and "ets #here as -ap types hold group of
ob%ects as @ey& value pairs 8g. 7ash-ap and 7ashtable.
Question: or concatenation of strings& #hich method is good& "tringBuffer or "tring ?
Answer: "tringBuffer is faster than "tring for concatenation.
Question: What is Runnable interface ? 3re there any other #ays to ma@e a %ava program as
multithred %ava program?
Answer: There are t#o #ays to create ne# @inds of threads*
4 +efine a ne# class that e!tends the Thread class
4 +efine a ne# class that implements the Runnable interface& and pass an ob%ect of that class to a
Thread's constructor.
4 3n advantage of the second approach is that the ne# class can be a subclass of any class& not
%ust of the Thread class.
7ere is a very simple e!ample %ust to illustrate ho# to use the second approach to creating
threads* class myThread implements Runnable 1 public void run/0 1 "ystem.out.println/E,'m
runningTE09 5 5 public class tstRunnable 1 public static void main/"tringFG args0 1 myThread my.
< ne# myThread/09 myThread my? < ne# myThread/09 ne# Thread/my.0.start/09 ne#
Thread/my?0.start/09 5
Question: 7o# can i tell #hat state a thread is in ?
Answer: Prior to :ava I& is3live/0 #as commonly used to test a threads state. ,f is3live/0
returned false the thread #as either ne# or terminated but there #as simply no #ay to
differentiate bet#een the t#o.
"tarting #ith the release of Tiger /:ava I0 you can no# get #hat state a thread is in by using the
get"tate/0 method #hich returns an 8num of Thread."tates. 3 thread can only be in one of the
follo#ing states at a given point in time.
'8W 3 resh thread that has not yet started to e!ecute.
R>''3B(8 3 thread that is e!ecuting in the :ava virtual machine.
B($)U8+ 3 thread that is bloc@ed #aiting for a monitor loc@.
W3,T,'D 3 thread that is #ating to be notified by another thread.
T,-8+;W3,T,'D
3 thread that is #ating to be notified by another thread for a specific amount
of time
T8R-,'3T8+ 3 thread #hos run method has ended.
The folo#ing code prints out all thread states. public class Thread"tates1 public static void
main/"tringFG args01 Thread t < ne# Thread/09 Thread."tate e < t.get"tate/09 Thread."tateFG ts <
e.values/09 for/int i < =9 i S ts.length9 iOO01 "ystem.out.println/tsFiG09 5 5 5
Question: What methods %ava providing for Thread communications ?
Answer: :ava provides three methods that threads can use to communicate #ith each other* #ait&
notify& and notify3ll. These methods are defined for all $b%ects /not %ust Threads0. The idea is
that a method called by a thread may need to #ait for some condition to be satisfied by another
thread9 in that case& it can call the #ait method& #hich causes its thread to #ait until another
thread calls notify or notify3ll.
Question: What is the difference bet#een notify and notify 3ll methods ?
Answer: 3 call to notify causes at most one thread #aiting on the same ob%ect to be notified
/i.e.& the ob%ect that calls notify must be the same as the ob%ect that called #ait0. 3 call to
notify3ll causes all threads #aiting on the same ob%ect to be notified. ,f more than one thread is
#aiting on that ob%ect& there is no #ay to control #hich of them is notified by a call to notify /so
it is often better to use notify3ll than notify0.
Question: What is synchronized @ey#ord? ,n #hat situations you #ill >se it?
Answer: "ynchronization is the act of serializing access to critical sections of code. We #ill use
this @ey#ord #hen #e e!pect multiple threads to access2modify the same data. To understand
synchronization #e need to loo@ into thread e!ecution manner.
Threads may e!ecute in a manner #here their paths of e!ecution are completely independent of
each other. 'either thread depends upon the other for assistance. or e!ample& one thread might
e!ecute a print %ob& #hile a second thread repaints a #indo#. 3nd then there are threads that
re6uire synchronization& the act of serializing access to critical sections of code& at various
moments during their e!ecutions. or e!ample& say that t#o threads need to send data pac@ets
over a single net#or@ connection. 8ach thread must be able to send its entire data pac@et before
the other thread starts sending its data pac@et9 other#ise& the data is scrambled. This scenario
re6uires each thread to synchronize its access to the code that does the actual data4pac@et
sending.
,f you feel a method is very critical for business that needs to be e!ecuted by only one thread at a
time /to prevent data loss or corruption0& then #e need to use synchronized @ey#ord.
E6A0&-E
"ome real4#orld tas@s are better modeled by a program that uses threads than by a normal&
se6uential program. or e!ample& consider a ban@ #hose accounts can be accessed and updated
by any of a number of automatic teller machines /3T-s0. 8ach 3T- could be a separate thread&
responding to deposit and #ithdra#al re6uests from different users simultaneously. $f course& it
#ould be important to ma@e sure that t#o users did not access the same account simultaneously.
This is done in :ava using synchronization& #hich can be applied to individual methods& or to
se6uences of statements.
$ne or more methods of a class can be declared to be synchronized. When a thread calls an
ob%ect's synchronized method& the #hole ob%ect is loc@ed. This means that if another thread tries
to call any synchronized method of the same ob%ect& the call #ill bloc@ until the loc@ is released
/#hich happens #hen the original call finishes0. ,n general& if the value of a field of an ob%ect can
be changed& then all methods that read or #rite that field should be synchronized to prevent t#o
threads from trying to #rite the field at the same time& and to prevent one thread from reading the
field #hile another thread is in the process of #riting it.
7ere is an e!ample of a Ban@3ccount class that uses synchronized methods to ensure that
deposits and #ithdra#als cannot be performed simultaneously& and to ensure that the account
balance cannot be read #hile either a deposit or a #ithdra#al is in progress. /To @eep the
e!ample simple& no chec@ is done to ensure that a #ithdra#al does not lead to a negative
balance.0
public class Ban@3ccount 1 private double balance9 22 constructor* set balance to given amount
public Ban@3ccount/ double initial+eposit 0 1 balance < initial+eposit9 5 public synchronized
double Balance/ 0 1 return balance9 5 public synchronized void +eposit/ double deposit 0
1 balance O< deposit9 5 public synchronized void Withdra#/ double #ithdra#al 0 1 balance 4<
#ithdra#al9 5 5
'ote* that the Ban@3ccount's constructor is not declared to be synchronized. That is because it
can only be e!ecuted #hen the ob%ect is being created& and no other method can be called until
that creation is finished.
There are cases #here #e need to synchronize a group of statements& #e can do that using
synchrozed statement.
:ava )ode 8!ample synchronized / B 0 1 if / + V B.Balance/0 0 1 Report,nsuffucientunds/09 5
else 1 B.Withdra#/ + 09 5 5
Question: What is serialization ?
Answer: "erialization is the process of #riting complete state of %ava ob%ect into output stream&
that stream can be file or byte array or stream associated #ith T)P2,P soc@et.
Question: What does the "erializable interface do ?
Answer: "erializable is a tagging interface9 it prescribes no methods. ,t serves to assign the
"erializable data type to the tagged class and to identify the class as one #hich the developer has
designed for persistence. $b%ect$utput"tream serializes only those ob%ects #hich implement this
interface.
Question: 7o# do , serialize an ob%ect to a file ?
Answer: To serialize an ob%ect into a stream perform the follo#ing actions*
4 $pen one of the output streams& for e!aample ile$utput"tream
4 )hain it #ith the $b%ect$utput"tream 4 )all the method #rite$b%ect/0 providingg the instance
of a "erializable ob%ect as an argument.
4 )lose the streams
:ava )ode 444444444 try1 f$ut< ne# ile$utput"tream/Ec*QQemp.serE09 out < ne#
$b%ect$utput"tream/f$ut09 out.#rite$b%ect/employee09 22serializing "ystem.out.println/E3n
employee is serialized into c*QQemp.serE09 5 catch/,$8!ception e01 e.print"tac@Trace/09 5
Question: 7o# do , deserilaize an $b%ect?
Answer: To deserialize an ob%ect& perform the follo#ing steps*
4 $pen an input stream
4 )hain it #ith the $b%ect,nput"tream 4 )all the method read$b%ect/0 and cast tthe returned
ob%ect to the class that is being deserialized.
4 )lose the streams
:ava )ode try1 f,n< ne# ile,nput"tream/Ec*QQemp.serE09 in < ne# $b%ect,nput"tream/f,n09 22de4
serializing employee 8mployee emp < /8mployee0 in.read$b%ect/09
"ystem.out.println/E+eserialized E O emp.f'ame O E E O emp.l'ame O E from emp.ser E09 5
catch/,$8!ception e01 e.print"tac@Trace/09 5catch/)lass'otound8!ception e0
1 e.print"tac@Trace/09 5
Question: What is 8!ternalizable ,nterface ?
Answer : 8!ternalizable interface is a subclass of "erializable. :ava provides 8!ternalizable
interface that gives you more control over #hat is being serialized and it can produce smaller
ob%ect footprint. / Nou can serialize #hatever field values you #ant to serialize0
This interface defines ? methods* read8!ternal/0 and #rite8!ternal/0 and you have to implement
these methods in the class that #ill be serialized. ,n these methods you'll have to #rite code that
reads2#rites only the values of the attributes you are interested in. Programs that perform
serialization and deserialization have to #rite and read these attributes in the same se6uence.
Question: 8!plain garbage collection ?
Answer: Darbage collection is an important part of :ava's security strategy. Darbage collection
is also called automatic memory management as :V- automatically removes the unused
variables2ob%ects from the memory. The name Egarbage collectionE implies that ob%ects that are
no longer needed by the program are EgarbageE and can be thro#n a#ay. 3 more accurate and
up4to4date metaphor might be Ememory recycling.E When an ob%ect is no longer referenced by
the program& the heap space it occupies must be recycled so that the space is available for
subse6uent ne# ob%ects. The garbage collector must someho# determine #hich ob%ects are no
longer referenced by the program and ma@e available the heap space occupied by such
unreferenced ob%ects. ,n the process of freeing unreferenced ob%ects& the garbage collector must
run any finalizers of ob%ects being freed
Question : 7o# you can force the garbage collection ?
Answer : Darbage collection automatic process and can't be forced. We can call garbage
collector in :ava by calling "ystem.gc/0 and Runtime.gc/0& :V- tries to recycle the unused
ob%ects& but there is no guarantee #hen all the ob%ects #ill garbage collected.
Question : What are the field2method access levels /specifiers0 and class access levels ?
Answer: 8ach field and method has an access level*
private* accessible only in this class
/pac@age0* accessible only in this pac@age
protected* accessible only in this pac@age and in all subclasses of this class
public* accessible every#here this class is available
"imilarly& each class has one of t#o possible access levels*
/pac@age0* class ob%ects can only be declared and manipulated by code in this pac@age
public* class ob%ects can be declared and manipulated by code in any pac@age
Question: What are the static fields R static -ethods ?
Answer: ,f a field or method defined as a static& there is only one copy for entire class& rather
than one copy for each instance of class. static method cannot accecss non4static field or call
non4static method
8!ample :ava )ode
static int counter < =9
3 public static field or method can be accessed from outside the class using either the usual
notation*
:ava4class4ob%ect.field4or4method4name
or using the class name instead of the name of the class ob%ect*
:ava4 class4name.field4or4method4name
Question: What are the inal fields R inal -ethods ?
Answer: ields and methods can also be declared final. 3 final method cannot be overridden in
a subclass. 3 final field is li@e a constant* once it has been given a value& it cannot be assigned to
again.
:ava )ode
private static final int -3A3TT8-PT" < .=9
Question: +escribe the #rapper classes in :ava ?
Answer: Wrapper class is #rapper around a primitive data type. 3n instance of a #rapper class
contains& or #raps& a primitive value of the corresponding type.
ollo#ing table lists the primitive types and the corresponding #rapper classes*
&rimiti"e 'rapper
boolean %ava.lang.Boolean
byte %ava.lang.Byte
char %ava.lang.)haracter
double %ava.lang.+ouble
float %ava.lang.loat
int %ava.lang.,nteger
long %ava.lang.(ong
short %ava.lang."hort
void %ava.lang.Void
Question: What are different types of inner classes ?
Answer: ,nner classes nest #ithin other classes. 3 normal class is a direct member of a pac@age.
,nner classes& #hich became available #ith :ava ...& are four types
"tatic member classes
-ember classes
(ocal classes
3nonymous classes
Static member classes 4 a static member class is a static member of a class. (i@e any other static
method& a static member class has access to all static methods of the parent& or top4level& class.
0ember )lasses 4 a member class is also defined as a member of a class. >nli@e the static
variety& the member class is instance specific and has access to any and all methods and
members& even the parent's this reference.
-ocal )lasses 4 (ocal )lasses declared #ithin a bloc@ of code and these classes are visible only
#ithin the bloc@.
Anonymous )lasses 4 These type of classes does not have any name and its li@e a local class
:ava 3nonymous )lass 8!ample public class "omeD>, e!tends :rame 1 ... button member
declarations ... protected void buildD>,/0 1 button. < ne# :Button/09 button? < ne# :Button/09 ...
button..add3ction(istener/ ne# %ava.a#t.event.3ction(istener/0 S444444 3nonymous )lass
1 public void actionPerformed/%ava.a#t.event.3ction8vent e0 1 22 do something 5 5 09
Question: What is the difference bet#een notify and notify 3ll methods ?
Answer: 3 call to notify causes at most one thread #aiting on the same ob%ect to be notified
/i.e.& the ob%ect that calls notify must be the same as the ob%ect that called #ait0. 3 call to
notify3ll causes all threads #aiting on the same ob%ect to be notified. ,f more than one thread is
#aiting on that ob%ect& there is no #ay to control #hich of them is notified by a call to notify /so
it is often better to use notify3ll than notify0.
Question: What is synchronized @ey#ord? ,n #hat situations you #ill >se it?
Answer: "ynchronization is the act of serializing access to critical sections of code. We #ill use
this @ey#ord #hen #e e!pect multiple threads to access2modify the same data. To understand
synchronization #e need to loo@ into thread e!ecution manner.
Threads may e!ecute in a manner #here their paths of e!ecution are completely independent of
each other. 'either thread depends upon the other for assistance. or e!ample& one thread might
e!ecute a print %ob& #hile a second thread repaints a #indo#. 3nd then there are threads that
re6uire synchronization& the act of serializing access to critical sections of code& at various
moments during their e!ecutions. or e!ample& say that t#o threads need to send data pac@ets
over a single net#or@ connection. 8ach thread must be able to send its entire data pac@et before
the other thread starts sending its data pac@et9 other#ise& the data is scrambled. This scenario
re6uires each thread to synchronize its access to the code that does the actual data4pac@et
sending.
,f you feel a method is very critical for business that needs to be e!ecuted by only one thread at a
time /to prevent data loss or corruption0& then #e need to use synchronized @ey#ord.
E6A0&-E
"ome real4#orld tas@s are better modeled by a program that uses threads than by a normal&
se6uential program. or e!ample& consider a ban@ #hose accounts can be accessed and updated
by any of a number of automatic teller machines /3T-s0. 8ach 3T- could be a separate thread&
responding to deposit and #ithdra#al re6uests from different users simultaneously. $f course& it
#ould be important to ma@e sure that t#o users did not access the same account simultaneously.
This is done in :ava using synchronization& #hich can be applied to individual methods& or to
se6uences of statements.
$ne or more methods of a class can be declared to be synchronized. When a thread calls an
ob%ect's synchronized method& the #hole ob%ect is loc@ed. This means that if another thread tries
to call any synchronized method of the same ob%ect& the call #ill bloc@ until the loc@ is released
/#hich happens #hen the original call finishes0. ,n general& if the value of a field of an ob%ect can
be changed& then all methods that read or #rite that field should be synchronized to prevent t#o
threads from trying to #rite the field at the same time& and to prevent one thread from reading the
field #hile another thread is in the process of #riting it.
7ere is an e!ample of a Ban@3ccount class that uses synchronized methods to ensure that
deposits and #ithdra#als cannot be performed simultaneously& and to ensure that the account
balance cannot be read #hile either a deposit or a #ithdra#al is in progress. /To @eep the
e!ample simple& no chec@ is done to ensure that a #ithdra#al does not lead to a negative
balance.0
public class Ban@3ccount 1 private double balance9 22 constructor* set balance to given amount
public Ban@3ccount/ double initial+eposit 0 1 balance < initial+eposit9 5 public synchronized
double Balance/ 0 1 return balance9 5 public synchronized void +eposit/ double deposit 0
1 balance O< deposit9 5 public synchronized void Withdra#/ double #ithdra#al 0 1 balance 4<
#ithdra#al9 5 5
'ote* that the Ban@3ccount's constructor is not declared to be synchronized. That is because it
can only be e!ecuted #hen the ob%ect is being created& and no other method can be called until
that creation is finished.
There are cases #here #e need to synchronize a group of statements& #e can do that using
synchrozed statement.
:ava )ode 8!ample synchronized / B 0 1 if / + V B.Balance/0 0 1 Report,nsuffucientunds/09 5
else 1 B.Withdra#/ + 09 5 5
7.what is a transient "ariable4
3 transient variable is a variable that may not be serialized.
3.which containers use a border -ayout as their default layout4
The #indo#& rame and +ialog classes use a border layout as their default layout.
5.'hy do threads block on ,8#4
Threads bloc@ on i2o /that is enters the #aiting state0 so that other threads may e!ecute #hile the
i2o $peration is performed.
9. :ow are #bser"er and #bser"able used4
$b%ects that subclass the $bservable class maintain a list of observers. When an $bservable
ob%ect is updated it invo@es the update/0 method of each of its observers to notify the observers
that it has changed state. The $bserver interface is implemented by ob%ects that observe
$bservable ob%ects.
;. 'hat is synchronization and why is it important4
With respect to multithreading& synchronization is the capability to control the access of multiple
threads to shared resources. Without synchronization& it is possible for one thread to modify a
shared ob%ect #hile another thread is in the process of using or updating that ob%ect's value. This
often leads to significant errors.
<. )an a lock be ac=uired on a class4
Nes& a loc@ can be ac6uired on a class. This loc@ is ac6uired on the class's )lass ob%ect.
>. 'hat?s new with the stop(% suspend( and resume( methods in /*@ 7.34
The stop/0& suspend/0 and resume/0 methods have been deprecated in :+U ..?.
A. ,s null a keyword4
The null value is not a @ey#ord.
B. 'hat is the preferred size of a component4
The preferred size of a component is the minimum component size that #ill allo# the component
to display normally.
7C. 'hat method is used to specify a container?s layout4
The set(ayout/0 method is used to specify a container's layout.
77. 'hich containers use a +low-ayout as their default layout4
The Panel and 3pplet classes use the lo#(ayout as their default layout.
73. 'hat state does a thread enter when it terminates its processing4
When a thread terminates its processing& it enters the dead state.
75. 'hat is the )ollections A&,4
The )ollections 3P, is a set of classes and interfaces that support operations on collections of
ob%ects.
79. 'hich characters may be used as the second character of an identifier% but not as the
first character of an identifier4
The digits = through M may not be used as the first character of an identifier but they may be used
after the first character of an identifier.
7;. 'hat is the -ist interface4
The (ist interface provides support for ordered collections of ob%ects.
7<. :ow does /a"a handle integer o"erflows and underflows4
,t uses those lo# order bytes of the result that can fit into the size of the type allo#ed by the
operation.
7>. 'hat is the .ector class4
The Vector class provides the capability to implement a gro#able array of ob%ects
7A. 'hat modifiers may be used with an inner class that is a member of an outer class4
3 /non4local0 inner class may be declared as public& protected& private& static& final& or abstract.
7B. 'hat is an ,terator interface4
The ,terator interface is used to step through the elements of a )ollection.
3C. 'hat is the difference between the DD and DDD operators4
The VV operator carries the sign bit #hen shifting right. The VVV zero4fills bits that have been
shifted out.
37. 'hich method of the )omponent class is used to set the position and size of a
component4
setBounds/0
33. :ow many bits are used to represent Enicode% AS),,% EF+27<% and EF+2A characters4
>nicode re6uires .J bits and 3"),, re6uire K bits. 3lthough the 3"),, character set uses only K
bits& it is usually represented as L bits. >T4L represents characters using L& .J& and .L bit
patterns. >T4.J uses .J4bit and larger bit patterns.
35'hat is the difference between yielding and sleeping4
When a tas@ invo@es its yield/0 method& it returns to the ready state. When a tas@ invo@es its
sleep/0 method& it returns to the #aiting state.
39. 'hich !a"a.util classes and interfaces support e"ent handling4
The 8vent$b%ect class and the 8vent(istener interface support event processing.
3;. ,s sizeof a keyword4
The sizeof operator is not a @ey#ord.
3<. 'hat are wrapped classes4
Wrapped classes are classes that allo# primitive types to be accessed as ob%ects.
3>. *oes garbage collection guarantee that a program will not run out of memory4
Darbage collection does not guarantee that a program #ill not run out of memory. ,t is possible
for programs to use up memory resources faster than they are garbage collected. ,t is also
possible for programs to create ob%ects that are not sub%ect to garbage collection
3A. 'hat restrictions are placed on the location of a package statement within a source
code file4
3 pac@age statement must appear as the first line in a source code file /e!cluding blan@ lines and
comments0.
3B. )an an ob!ect?s finalize( method be in"oked while it is reachable4
3n ob%ect's finalize/0 method cannot be invo@ed by the garbage collector #hile the ob%ect is still
reachable. 7o#ever& an ob%ect's finalize/0 method may be invo@ed by other ob%ects.
5C. 'hat is the immediate superclass of the Applet class4
Panel
57. 'hat is the difference between preempti"e scheduling and time slicing4
>nder preemptive scheduling& the highest priority tas@ e!ecutes until it enters the #aiting or dead
states or a higher priority tas@ comes into e!istence. >nder time slicing& a tas@ e!ecutes for a
predefined slice of time and then reenters the pool of ready tas@s. The scheduler then determines
#hich tas@ should e!ecute ne!t& based on priority and other factors.
53. Game three )omponent subclasses that support painting.
The )anvas& rame& Panel& and 3pplet classes support painting.
55. 'hat "alue does read-ine( return when it has reached the end of a file4
The read(ine/0 method returns null #hen it has reached the end of a file.
59. 'hat is the immediate superclass of the *ialog class4
Windo#
5;. 'hat is clipping4
)lipping is the process of confining paint operations to a limited area or shape.
5<. 'hat is a nati"e method4
3 native method is a method that is implemented in a language other than :ava.
5>. )an a for statement loop indefinitely4
Nes& a for statement can loop indefinitely. or e!ample& consider the follo#ing* for/990 9
5A. 'hat are order of precedence and associati"ity% and how are they used4
$rder of precedence determines the order in #hich operators are evaluated in e!pressions.
3ssociatity determines #hether an e!pression is evaluated left4to4right or right4to4left
5B. 'hen a thread blocks on ,8#% what state does it enter4
3 thread enters the #aiting state #hen it bloc@s on ,2$.
9C. Fo what "alue is a "ariable of the String type automatically initialized4
The default value of an "tring type is null.
97. 'hat is the catch or declare rule for method declarations4
,f a chec@ed e!ception may be thro#n #ithin the body of a method& the method must either catch
the e!ception or declare it in its thro#s clause.
93. 'hat is the difference between a 0enu,tem and a )heckbox0enu,tem4
The )hec@bo!-enu,tem class e!tends the -enu,tem class to support a menu item that may be
chec@ed or unchec@ed.
95. 'hat is a task?s priority and how is it used in scheduling4
3 tas@'s priority is an integer value that identifies the relative order in #hich it should be
e!ecuted #ith respect to other tas@s. The scheduler attempts to schedule higher priority tas@s
before lo#er priority tas@s.
99. 'hat class is the top of the A'F e"ent hierarchy4
The %ava.a#t.3WT8vent class is the highest4level class in the 3WT event4class hierarchy.
9;. 'hen a thread is created and started% what is its initial state4
3 thread is in the ready state after it has been created and started.
9<. )an an anonymous class be declared as implementing an interface and extending a
class4
3n anonymous class may implement an interface or e!tend a superclass& but may not be declared
to do both.
9>. 'hat is the range of the short type4
The range of the short type is 4/?W.I0 to ?W.I 4 ..
9A. 'hat is the range of the char type4
The range of the char type is = to ?W.J 4 ..
9B. ,n which package are most of the A'F e"ents that support the e"ent2delegation model
defined4
-ost of the 3WT4related events of the event4delegation model are defined in the %ava.a#t.event
pac@age. The 3WT8vent class is defined in the %ava.a#t pac@age.
;C. 'hat is the immediate superclass of 0enu4
-enu,tem
;7. 'hat is the purpose of finalization4
The purpose of finalization is to give an unreachable ob%ect the opportunity to perform any
cleanup processing before the ob%ect is garbage collected.
;3. 'hich class is the immediate superclass of the 0enu)omponent class.
$b%ect
;5. 'hat in"okes a thread?s run( method4
3fter a thread is started& via its start/0 method or that of the Thread class& the :V- invo@es the
thread's run/0 method #hen the thread is initially e!ecuted.
;9. 'hat is the difference between the (oolean 1 operator and the 11 operator4
,f an e!pression involving the Boolean R operator is evaluated& both operands are evaluated.
Then the R operator is applied to the operand. When an e!pression involving the RR operator is
evaluated& the first operand is evaluated. ,f the first operand returns a value of true then the
second operand is evaluated. The RR operator is then applied to the first and second operands. ,f
the first operand evaluates to false& the evaluation of the second operand is s@ipped.
;;. Game three subclasses of the )omponent class.
Bo!.iller& Button& )anvas& )hec@bo!& )hoice& )ontainer& (abel& (ist& "crollbar& or
Te!t)omponent
;<. 'hat is the Hregorian)alendar class4
The Dregorian)alendar provides support for traditional Western calendars.
;>. 'hich )ontainer method is used to cause a container to be laid out and redisplayed4
validate/0
;A. 'hat is the purpose of the $untime class4
The purpose of the Runtime class is to provide access to the :ava runtime system.
;B. :ow many times may an ob!ect?s finalize( method be in"oked by the garbage collector4
3n ob%ect's finalize/0 method may only be invo@ed once by the garbage collector.
<C. 'hat is the purpose of the finally clause of a try2catch2finally statement4
The finally clause is used to provide the capability to e!ecute code no matter #hether or not an
e!ception is thro#n or caught.
<7. 'hat is the argument type of a program?s main( method4
3 program's main/0 method ta@es an argument of the "tringFG type.
<3. 'hich /a"a operator is right associati"e4
The < operator is right associative.
<5. 'hat is the -ocale class4
The (ocale class is used to tailor program output to the conventions of a particular geographic&
political& or cultural region.
<9. )an a double "alue be cast to a byte4
Nes& a double value can be cast to a byte.
<;. 'hat is the difference between a break statement and a continue statement4
3 brea@ statement results in the termination of the statement to #hich it applies /s#itch& for& do&
or #hile0. 3 continue statement is used to end the current loop iteration and return control to the
loop statement.
<<. 'hat must a class do to implement an interface4
,t must provide all of the methods in the interface and identify the interface in its implements
clause.
<>. 'hat method is in"oked to cause an ob!ect to begin executing as a separate thread4
The start/0 method of the Thread class is invo@ed to cause an ob%ect to begin e!ecuting as a
separate thread.
<A. Game two subclasses of the Fext)omponent class.
Te!tield and Te!t3rea
<B. 'hat is the ad"antage of the e"ent2delegation model o"er the earlier e"ent2inheritance
model4
The event4delegation model has t#o advantages over the event4inheritance model. irst& it
enables event handling to be handled by ob%ects other than the ones that generate the events /or
their containers0. This allo#s a clean separation bet#een a component's design and its use. The
other advantage of the event4delegation model is that it performs much better in applications
#here many events are generated. This performance improvement is due to the fact that the
event4delegation model does not have to repeatedly process unhandled events& as is the case of
the event4inheritance model.
>C. 'hich containers may ha"e a 0enu(ar4
rame
>7. :ow are commas used in the intialization and iteration parts of a for statement4
)ommas are used to separate multiple statements #ithin the initialization and iteration parts of a
for statement.
>3. 'hat is the purpose of the wait(% notify(% and notifyAll( methods4
The #ait/0&notify/0& and notify3ll/0 methods are used to provide an efficient #ay for threads to
#ait for a shared resource. When a thread e!ecutes an ob%ect's #ait/0 method& it enters the
#aiting state. ,t only enters the ready state after another thread invo@es the ob%ect's notify/0 or
notify3ll/0 methods.
>5. 'hat is an abstract method4
3n abstract method is a method #hose implementation is deferred to a subclass.
>9. :ow are /a"a source code files named4
3 :ava source code file ta@es the name of a public class or interface that is defined #ithin the
file. 3 source code file may contain at most one public class or interface. ,f a public class or
interface is defined #ithin a source code file& then the source code file must ta@e the name of the
public class or interface. ,f no public class or interface is defined #ithin a source code file& then
the file must ta@e on a name that is different than its classes and interfaces. "ource code files use
the .%ava e!tension.
>;. 'hat is the relationship between the )an"as class and the Hraphics class4
3 )anvas ob%ect provides access to a Draphics ob%ect via its paint/0 method.
><. 'hat are the high2le"el thread states4
The high4level thread states are ready& running& #aiting& and dead.
>>. 'hat "alue does read( return when it has reached the end of a file4
The read/0 method returns 4. #hen it has reached the end of a file.
>A. )an a (yte ob!ect be cast to a double "alue4
'o& an ob%ect cannot be cast to a primitive value.
>B. 'hat is the difference between a static and a non2static inner class4
3 non4static inner class may have ob%ect instances that are associated #ith instances of the class's
outer class. 3 static inner class does not have any ob%ect instances.
AC. 'hat is the difference between the String and String(uffer classes4
"tring ob%ects are constants. "tringBuffer ob%ects are not.
A7. ,f a "ariable is declared as pri"ate% where may the "ariable be accessed4
3 private variable may only be accessed #ithin the class in #hich it is declared.
A3. 'hat is an ob!ect?s lock and which ob!ect?s ha"e locks4
3n ob%ect's loc@ is a mechanism that is used by multiple threads to obtain synchronized access to
the ob%ect. 3 thread may e!ecute a synchronized method of an ob%ect only after it has ac6uired
the ob%ect's loc@. 3ll ob%ects and classes have loc@s. 3 class's loc@ is ac6uired on the class's )lass
ob%ect.
A5. 'hat is the *ictionary class4
The +ictionary class provides the capability to store @ey4value pairs.
A9. :ow are the elements of a (order-ayout organized4
The elements of a Border(ayout are organized at the borders /'orth& "outh& 8ast& and West0 and
the center of a container.
A;. 'hat is the I operator4
,t is referred to as the modulo or remainder operator. ,t returns the remainder of dividing the first
operand by the second operand.
A<. 'hen can an ob!ect reference be cast to an interface reference4
3n ob%ect reference be cast to an interface reference #hen the ob%ect implements the referenced
interface.
A>. 'hat is the difference between a 'indow and a +rame4
The rame class e!tends Windo# to define a main application #indo# that can have a menu
bar.
AA. 'hich class is extended by all other classes4
The $b%ect class is e!tended by all other classes.
AB. )an an ob!ect be garbage collected while it is still reachable4
3 reachable ob%ect cannot be garbage collected. $nly unreachable ob%ects may be garbage
collected..
BC. ,s the ternary operator written x : y 4 z or x 4 y : z 4
,t is #ritten ! ? y * z.
B7. 'hat is the difference between the +ont and +ont0etrics classes4
The ont-etrics class is used to define implementation4specific properties& such as ascent and
descent& of a ont ob%ect.
B3. :ow is rounding performed under integer di"ision4
The fractional part of the result is truncated. This is @no#n as rounding to#ard zero.
B5. 'hat happens when a thread cannot ac=uire a lock on an ob!ect4
,f a thread attempts to e!ecute a synchronized method or synchronized statement and is unable to
ac6uire an ob%ect's loc@& it enters the #aiting state until the loc@ becomes available.
B9. 'hat is the difference between the $eader8'riter class hierarchy and the
,nputStream8#utputStream class hierarchy4
The Reader2Writer class hierarchy is character4oriented& and the ,nput"tream2$utput"tream class
hierarchy is byte4oriented.
B;. 'hat classes of exceptions may be caught by a catch clause4
3 catch clause can catch any e!ception that may be assigned to the Thro#able type. This
includes the 8rror and 8!ception types.
B<. ,f a class is declared without any access modifiers% where may the class be accessed4
3 class that is declared #ithout any access modifiers is said to have pac@age access. This means
that the class can only be accessed by other classes and interfaces that are defined #ithin the
same pac@age.
B>. 'hat is the SimpleFimeJone class4
The "impleTimeXone class provides support for a Dregorian calendar.
BA. 'hat is the 0ap interface4
The -ap interface replaces the :+U ... +ictionary class and is used associate @eys #ith values.
BB. *oes a class inherit the constructors of its superclass4
3 class does not inherit constructors from any of its superclasses.
7CC. +or which statements does it make sense to use a label4
The only statements for #hich it ma@es sense to use a label are those statements that can enclose
a brea@ or continue statement.
7C7. 'hat is the purpose of the System class4
The purpose of the "ystem class is to provide access to system resources.
7C3. 'hich Fext)omponent method is used to set a Fext)omponent to the read2only state4
set8ditable/0
7C5. :ow are the elements of a )ard-ayout organized4
The elements of a )ard(ayout are stac@ed& one on top of the other& li@e a dec@ of cards.
7C9. ,s 11K a "alid /a"a operator4
'o& it is not.
7C;. Game the eight primiti"e /a"a types.
The eight primitive types are byte& char& short& int& long& float& double& and boolean.
7C<. 'hich class should you use to obtain design information about an ob!ect4
The )lass class is used to obtain information about an ob%ect's design.
7C>. 'hat is the relationship between clipping and repainting4
When a #indo# is repainted by the 3WT painting thread& it sets the clipping regions to the area
of the #indo# that re6uires repainting.
7CA. ,s LabcL a primiti"e "alue4
The "tring literal EabcE is not a primitive value. ,t is a "tring ob%ect.
7CB. 'hat is the relationship between an e"ent2listener interface and an e"ent2adapter
class4
3n event4listener interface defines the methods that must be implemented by an event handler
for a particular @ind of event. 3n event adapter provides a default implementation of an event4
listener interface.
77C. 'hat restrictions are placed on the "alues of each case of a switch statement4
+uring compilation& the values of each case of a s#itch statement must evaluate to a value that
can be promoted to an int value.
777. 'hat modifiers may be used with an interface declaration4
3n interface may be declared as public or abstract.
773. ,s a class a subclass of itself4
3 class is a subclass of itself.
775. 'hat is the highest2le"el e"ent class of the e"ent2delegation model4
The %ava.util.8vent$b%ect class is the highest4level class in the event4delegation class hierarchy.
779. 'hat e"ent results from the clicking of a button4
The 3ction8vent event is generated as the result of the clic@ing of a button.
77;. :ow can a HE, component handle its own e"ents4
3 component can handle its o#n events by implementing the re6uired event4listener interface
and adding itself as its o#n event listener.
77<. 'hat is the difference between a while statement and a do statement4
3 #hile statement chec@s at the beginning of a loop to see #hether the ne!t loop iteration should
occur. 3 do statement chec@s at the end of a loop to see #hether the ne!t iteration of a loop
should occur. The do statement #ill al#ays e!ecute the body of a loop at least once.
77>. :ow are the elements of a Hrid(ag-ayout organized4
The elements of a DridBag(ayout are organized according to a grid. 7o#ever& the elements are
of different sizes and may occupy more than one ro# or column of the grid. ,n addition& the ro#s
and columns may have different sizes.
77A. 'hat ad"antage do /a"a?s layout managers pro"ide o"er traditional windowing
systems4
:ava uses layout managers to lay out components in a consistent manner across all #indo#ing
platforms. "ince :ava's layout managers aren't tied to absolute sizing and positioning& they are
able to accomodate platform4specific differences among #indo#ing systems.
77B. 'hat is the )ollection interface4
The )ollection interface provides support for the implementation of a mathematical bag 4 an
unordered collection of ob%ects that may contain duplicates.
73C. 'hat modifiers can be used with a local inner class4
3 local inner class may be final or abstract.
737. 'hat is the difference between static and non2static "ariables4
3 static variable is associated #ith the class as a #hole rather than #ith specific instances of a
class. 'on4static variables ta@e on uni6ue values #ith each ob%ect instance.
733. 'hat is the difference between the paint( and repaint( methods4
The paint/0 method supports painting via a Draphics ob%ect. The repaint/0 method is used to
cause paint/0 to be invo@ed by the 3WT painting thread.
735. 'hat is the purpose of the +ile class4
The ile class is used to create ob%ects that provide access to the files and directories of a local
file system.
739. )an an exception be rethrown4
Nes& an e!ception can be rethro#n.
73;. 'hich 0ath method is used to calculate the absolute "alue of a number4
The abs/0 method is used to calculate absolute values.
73<. :ow does multithreading take place on a computer with a single )&E4
The operating system's tas@ scheduler allocates e!ecution time to multiple tas@s. By 6uic@ly
s#itching bet#een e!ecuting tas@s& it creates the impression that tas@s e!ecute se6uentially.
73>. 'hen does the compiler supply a default constructor for a class4
The compiler supplies a default constructor for a class if no other constructors are provided.
73A. 'hen is the finally clause of a try2catch2finally statement executed4
The finally clause of the try4catch4finally statement is al#ays e!ecuted unless the thread of
e!ecution terminates or an e!ception occurs #ithin the e!ecution of the finally clause.
73B. 'hich class is the immediate superclass of the )ontainer class4
)omponent
75C. ,f a method is declared as protected% where may the method be accessed4
3 protected method may only be accessed by classes or interfaces of the same pac@age or by
subclasses of the class in #hich it is declared.
757. :ow can the )heckbox class be used to create a radio button4
By associating )hec@bo! ob%ects #ith a )hec@bo!Droup.
753. 'hich non2Enicode letter characters may be used as the first character of an
identifier4
The non4>nicode letter characters Y and ; may appear as the first character of an identifier
755. 'hat restrictions are placed on method o"erloading4
T#o methods may not have the same name and argument list but different return types.
759. 'hat happens when you in"oke a thread?s interrupt method while it is sleeping or
waiting4
When a tas@'s interrupt/0 method is e!ecuted& the tas@ enters the ready state. The ne!t time the
tas@ enters the running state& an ,nterrupted8!ception is thro#n.
75;. 'hat is casting4
There are t#o types of casting& casting bet#een primitive numeric types and casting bet#een
ob%ect references. )asting bet#een numeric types is used to convert larger values& such as double
values& to smaller values& such as byte values. )asting bet#een ob%ect references is used to refer
to an ob%ect by a compatible class& interface& or array type reference.
75<. 'hat is the return type of a program?s main( method4
3 program's main/0 method has a void return type.
75>. Game four )ontainer classes.
Windo#& rame& +ialog& ile+ialog& Panel& 3pplet& or "crollPane
75A. 'hat is the difference between a )hoice and a -ist4
3 )hoice is displayed in a compact form that re6uires you to pull it do#n to see the list of
available choices. $nly one item may be selected from a )hoice. 3 (ist may be displayed in
such a #ay that several (ist items are visible. 3 (ist supports the selection of one or more (ist
items.
75B. 'hat class of exceptions are generated by the /a"a run2time system4
The :ava runtime system generates Runtime8!ception and 8rror e!ceptions.
79C. 'hat class allows you to read ob!ects directly from a stream4
The $b%ect,nput"tream class supports the reading of ob%ects from input streams.
797. 'hat is the difference between a field "ariable and a local "ariable4
3 field variable is a variable that is declared as a member of a class. 3 local variable is a variable
that is declared local to a method.
793. Ender what conditions is an ob!ect?s finalize( method in"oked by the garbage
collector4
The garbage collector invo@es an ob%ect's finalize/0 method #hen it detects that the ob%ect has
become unreachable.
795. :ow are this( and super( used with constructors4
this/0 is used to invo@e a constructor of the same class. super/0 is used to invo@e a superclass
constructor.
799. 'hat is the relationship between a method?s throws clause and the exceptions that can
be thrown during the method?s execution4
3 method's thro#s clause must declare any chec@ed e!ceptions that are not caught #ithin the
body of the method.
79;. 'hat is the difference between the /*@ 7.C3 e"ent model and the e"ent2delegation
model introduced with /*@ 7.74
The :+U ..=? event model uses an event inheritance or bubbling approach. ,n this model&
components are re6uired to handle their o#n events. ,f they do not handle a particular event& the
event is inherited by /or bubbled up to0 the component's container. The container then either
handles the event or it is bubbled up to its container and so on& until the highest4level container
has been tried.
,n the event4delegation model& specific ob%ects are designated as event handlers for D>,
components. These ob%ects implement event4listener interfaces. The event4delegation model is
more efficient than the event4inheritance model because it eliminates the processing re6uired to
support the bubbling of unhandled events.
79<. :ow is it possible for two String ob!ects with identical "alues not to be e=ual under the
KK operator4
The << operator compares t#o ob%ects to determine if they are the same ob%ect in memory. ,t is
possible for t#o "tring ob%ects to have the same value& but located indifferent areas of memory.
79>. 'hy are the methods of the 0ath class static4
"o they can be invo@ed as if they are a mathematical code library.
79A. 'hat )heckbox method allows you to tell if a )heckbox is checked4
get"tate/0
79B. 'hat state is a thread in when it is executing4
3n e!ecuting thread is in the running state.
7;C. 'hat are the legal operands of the instanceof operator4
The left operand is an ob%ect reference or null value and the right operand is a class& interface& or
array type.
7;7. :ow are the elements of a Hrid-ayout organized4
The elements of a DridBad layout are of e6ual size and are laid out using the s6uares of a grid.
7;3. 'hat an ,8# filter4
3n ,2$ filter is an ob%ect that reads from one stream and #rites to another& usually altering the
data in some #ay as it is passed from one stream to another.
7;5. ,f an ob!ect is garbage collected% can it become reachable again4
$nce an ob%ect is garbage collected& it ceases to e!ist. ,t can no longer become reachable again.
7;9. 'hat is the Set interface4
The "et interface provides methods for accessing the elements of a finite mathematical set. "ets
do not allo# duplicate elements.
7;;. 'hat classes of exceptions may be thrown by a throw statement4
3 thro# statement may thro# any e!pression that may be assigned to the Thro#able type.
7;<. 'hat are E and &,4
8 is the base of the natural logarithm and P, is mathematical value pi.
7;>. Are true and false keywords4
The values true and false are not @ey#ords.
7;A. 'hat is a "oid return type4
3 void return type indicates that a method does not return a value.
7;B. 'hat is the purpose of the enableE"ents( method4
The enable8vents/0 method is used to enable an event for a particular ob%ect. 'ormally& an event
is enabled #hen a listener is added to an ob%ect for a particular event. The enable8vents/0 method
is used by ob%ects that handle events by overriding their event4dispatch methods.
7<C. 'hat is the difference between the +ile and $andomAccess+ile classes4
The ile class encapsulates the files and directories of the local file system. The
Random3ccessile class provides the methods needed to directly access data contained in any
part of a file.
7<7. 'hat happens when you add a double "alue to a String4
The result is a "tring ob%ect.
7<3. 'hat is your platform?s default character encoding4
,f you are running :ava on 8nglish Windo#s platforms& it is probably )p.?I?. ,f you are running
:ava on 8nglish "olaris platforms& it is most li@ely LLIM;...
7<5. 'hich package is always imported by default4
The %ava.lang pac@age is al#ays imported by default.
7<9. 'hat interface must an ob!ect implement before it can be written to a stream as an
ob!ect4
3n ob%ect must implement the "erializable or 8!ternalizable interface before it can be #ritten to
a stream as an ob%ect.
7<;. :ow are this and super used4
this is used to refer to the current ob%ect instance. super is used to refer to the variables and
methods of the superclass of the current ob%ect instance.
7<<. 'hat is the purpose of garbage collection4
The purpose of garbage collection is to identify and discard ob%ects that are no longer needed by
a program so that their resources may be reclaimed and reused.
7<>. 'hat is a compilation unit4
3 compilation unit is a :ava source code file.
7<A. 'hat interface is extended by A'F e"ent listeners4
3ll 3WT event listeners e!tend the %ava.util.8vent(istener interface.
7<B. 'hat restrictions are placed on method o"erriding4
$verridden methods must have the same name& argument list& and return type. The overriding
method may not limit the access of the method it overrides. The overriding method may not
thro# any e!ceptions that may not be thro#n by the overridden method.
7>C. :ow can a dead thread be restarted4
3 dead thread cannot be restarted.
7>7. 'hat happens if an exception is not caught4
3n uncaught e!ception results in the uncaught8!ception/0 method of the thread's ThreadDroup
being invo@ed& #hich eventually results in the termination of the program in #hich it is thro#n.
7>3. 'hat is a layout manager4
3 layout manager is an ob%ect that is used to organize components in a container.
7>5. 'hich arithmetic operations can result in the throwing of an ArithmeticException4
,nteger 2 and Z can result in the thro#ing of an 3rithmetic8!ception.
7>9. 'hat are three ways in which a thread can enter the waiting state4
3 thread can enter the #aiting state by invo@ing its sleep/0 method& by bloc@ing on ,2$& by
unsuccessfully attempting to ac6uire an ob%ect's loc@& or by invo@ing an ob%ect's #ait/0 method. ,t
can also enter the #aiting state by invo@ing its /deprecated0 suspend/0 method.
7>;. )an an abstract class be final4
3n abstract class may not be declared as final.
7><. 'hat is the $esource(undle class4
The ResourceBundle class is used to store locale4specific resources that can be loaded by a
program to tailor the program's appearance to the particular locale in #hich it is being run.
7>>. 'hat happens if a try2catch2finally statement does not ha"e a catch clause to handle
an exception that is thrown within the body of the try statement4
The e!ception propagates up to the ne!t higher level try4catch statement /if any0 or results in the
program's termination.
7>A. 'hat is numeric promotion4
'umeric promotion is the conversion of a smaller numeric type to a larger numeric type& so that
integer and floating4point operations may ta@e place. ,n numerical promotion& byte& char& and
short values are converted to int
values. The int values are also converted to long values& if necessary. The long and float values
are converted to double values& as re6uired.
7>B. 'hat is the difference between a Scrollbar and a Scroll&ane4
3 "crollbar is a )omponent& but not a )ontainer. 3 "crollPane is a )ontainer. 3 "crollPane
handles its o#n events and performs its o#n scrolling.
7AC. 'hat is the difference between a public and a non2public class4
3 public class may be accessed outside of its pac@age. 3 non4public class may not be accessed
outside of its pac@age.
7A7. Fo what "alue is a "ariable of the boolean type automatically initialized4
The default value of the boolean type is false.
7A3. )an try statements be nested4
Try statements may be tested.
7A5. 'hat is the difference between the prefix and postfix forms of the MM operator4
The prefi! form performs the increment operation and returns the value of the increment
operation. The postfi! form returns the current value all of the e!pression and then performs the
increment operation on that value.
7A9. 'hat is the purpose of a statement block4
3 statement bloc@ is used to organize a se6uence of statements as a single statement group.
7A;. 'hat is a /a"a package and how is it used4
3 :ava pac@age is a naming conte!t for classes and interfaces. 3 pac@age is used to create a
separate name space for groups of classes and interfaces. Pac@ages are also used to organize
related classes and interfaces into a single 3P, unit and to control accessibility to these classes
and interfaces.
7A<. 'hat modifiers may be used with a top2le"el class4
3 top4level class may be public& abstract& or final.
7A>. 'hat are the #b!ect and )lass classes used for4
The $b%ect class is the highest4level class in the :ava class hierarchy. The )lass class is used to
represent the classes and interfaces that are loaded by a :ava program.
7AA. :ow does a try statement determine which catch clause should be used to handle an
exception4
When an e!ception is thro#n #ithin the body of a try statement& the catch clauses of the try
statement are e!amined in the order in #hich they appear. The first catch clause that is capable of
handling the e!ception is e!ecuted. The remaining catch clauses are ignored.
7AB. )an an unreachable ob!ect become reachable again4
3n unreachable ob%ect may become reachable again. This can happen #hen the ob%ect's finalize/0
method is invo@ed and the ob%ect performs an operation #hich causes it to become accessible to
reachable ob%ects.
7BC. 'hen is an ob!ect sub!ect to garbage collection4
3n ob%ect is sub%ect to garbage collection #hen it becomes unreachable to the program in #hich
it is used.
7B7. 'hat method must be implemented by all threads4
3ll tas@s must implement the run/0 method& #hether they are a subclass of Thread or implement
the Runnable interface.
7B3. 'hat methods are used to get and set the text label displayed by a (utton ob!ect4
get(abel/0 and set(abel/0
7B5. 'hich )omponent subclass is used for drawing and painting4
)anvas
7B9. 'hat are synchronized methods and synchronized statements4
"ynchronized methods are methods that are used to control access to an ob%ect. 3 thread only
e!ecutes a synchronized method after it has ac6uired the loc@ for the method's ob%ect or class.
"ynchronized statements are similar to synchronized methods. 3 synchronized statement can
only be e!ecuted after a thread has ac6uired the loc@ for the ob%ect or class referenced in the
synchronized statement.
7B;. 'hat are the two basic ways in which classes that can be run as threads may be
defined4
3 thread class may be declared as a subclass of Thread& or it may implement the Runnable
interface.
7B<. 'hat are the problems faced by /a"a programmers who don?t use layout managers4
Without layout managers& :ava programmers are faced #ith determining ho# their D>, #ill be
displayed across multiple #indo#ing systems and finding a common sizing and positioning that
#ill #or@ #ithin the constraints imposed by each #indo#ing system.
7B>. 'hat is the difference between an if statement and a switch statement4
The if statement is used to select among t#o alternatives. ,t uses a boolean e!pression to decide
#hich alternative should be e!ecuted. The s#itch statement is used to select among multiple
alternatives. ,t uses an int e!pression to determine #hich alternative should be e!ecuted.
7BA. 'hat happens when you add a double "alue to a String4
The result is a "tring ob%ect.
7BB. 'hat is the -ist interface4
The (ist interface provides support for ordered collections of ob%ects.
3B4:3V34+ifferences4Bet#een4:3V343nd4)4)PP
The +ifferences Bet#een :ava& ) 3nd )OO
This article aims to set out some of the differences bet#een )& )OO and :ava. What
it does not aim to do is conclude that one language is al#ays the best one to use.
(anguage choice depends upon a range of factors including field of application
/operating systems& des@top soft#are& #eb applications etc0& #hat programming
paradigm suits the application /$$P& procedural& etc0& the target platform and
available programmer e!pertise. What follo#s should help you decide #here it might
be suitable to use )& )OO or :ava.
Paradigm
) is geared to#ards procedural programming. That is& you #rite a number of
procedures to do certain tas@s and build up a program by calling those procedures as
needed.
:ava& on the other hand& is geared to#ards $$P /ob%ect oriented programming0. With
$$P& you define classes #hich represent an entity /for e!ample& a #indo#& a button&
a string of te!t& a file0. rom one class many ob%ects may be created& #ith every
ob%ect of a certain class having the fields /places to store data0 and methods /named
bloc@s of code associated #ith the ob%ect0 as defined by the class.
,t is possible to #rite in an ob%ect oriented style in ) and in a procedural style in
:ava& but in each case the language #ill some#hat get in your #ay. )OO is designed
to support both paradigms.
Preprocessor
3ll ) and )OO compilers implement a stage of compilation @no#n as the
preprocessor. The preprocessor basically performs an intelligent search and replace
on identifiers that have been declared using the [define or [typedef directives.
[define can also be used to declare macros. or e!ample& a macro -3A/!&y0 could
be defined to return #hichever of ! or y holds the greatest value. This is not li@e
calling a function as the substitution is done before the code is compiled. -ost of the
preprocessor definitions in ) and )OO are stored in header files& #hich complement
the actual source code files.
:ava does not have a preprocessor. )onstant data members are used in place of the
[define directive and class definitions are used in lieu of the [typedef directive&
ho#ever there is no substitute for macros& #hich can be useful. The :ava approach to
defining constants and naming types of data structures is probably conceptually
simpler for the programmer. 3dditionally& :ava programs don't use header files9 the
:ava compiler builds class definitions directly from the source code files& #hich
contain both class definitions and method implementations.
-emory -anagement
,n ) and )OO& any memory that is allocated on the heap /e.g. using malloc or ne#0 must be e!plicitly freed by the programmer
/e.g. using free or delete0. orgetting to free memory leads to memory lea@s& and in long4running programs can lead to the
memory usage of the program gro#ing very large.
:ava provides garbage collection& meaning that memory is freed automatically #hen
it is no longer reachable by any references. This prevents memory lea@s& but can
lead to pauses in e!ecution #hile the garbage collector runs. 3lso& there is no
promise of timely destruction in :ava.
Pointers
-ost developers agree that the misuse of pointers causes the ma%ority of bugs in )
and )OO programs. Put simply& #hen you have pointers& you have the ability to
attempt to access memory that isn't yours and modify memory relating to a different
data structure than the one you intended by accident. )2)OO programmers regularly
use comple! pointer arithmetic to create and maintain dynamic data structures. ,t's
po#erful& but can lead to a lot of time spent hunting do#n comple! and often subtle
bugs that arise as a result of having unguarded memory access.
The :ava language does not support pointers. ,nstead& it provides similar
functionality by ma@ing heavy use of references. 3 reference can be thought of as a
Esafe pointerE 4 the programmer can not directly manipulate the memory address.
:ava passes all arrays and ob%ects by reference. This approach prevents common
errors due to pointer mismanagement. ,t also ma@es programming easier in a lot of
#ays simply because the correct usage of pointers is easily misunderstood by
ine!perienced programmers.
)OO does provide references too. ,t considers them as aliases to another variable or
ob%ect. They are safer than pointers #here they can be used.
Bounds )hec@ing
3n array in ) or )OO is not bounds chec@ed& so attempts to access the si!th element
of a I4element array #ill appear to #or@ 4 that is& no runtime error #ill occur. This
means the programmer needs to code very carefully& especially considering the
potential for buffer overflo# attac@s.
:ava #ill bounds chec@ arrays to prevent this from happening& of course #ith a little
e!tra runtime cost.
Portability 3nd Performance
) and )OO both compile to native machine code. This means that& #ith a good
compiler& programs #ritten in these languages #ill perform very #ell. 7o#ever& it
also restricts them to running on the platform they #ere compiled to run on.
:ava generally compiles to :ava bytecode& #hich then runs on top of a virtual
machine /the :V-0. The :V- has to turn instructions in the bytecode into instructions
that are understood by the machine that the bytecode is running on. This gives a
runtime performance penalty /although this is getting less significant as the :V-
improves and computers get faster0. 7o#ever& no# only the virtual machine /and
standard library0 have to be ported to different platforms& then the bytecode for
many :ava programs can be e!ecuted on that platform. "o bytecode is portable
accross different operating systems and processors.
)omple! +ata Types
There are t#o types of comple! data types in )* structures and unions. )OO adds
classes to this list. :ava only implements one of these data types* classes.
3 structure can be emulated by a class 4 simply #rite a class #ithout any methods
and ma@e all the fields public. 7o#ever& emulating a union is not al#ays possible in
:ava& and the memory saving advantages unions hold in ) may not carry accross.
:ava presents a simpler model but at the cost of not being able to save a little
memory. or many applications this #ill be a non4issue.
"trings
) has no built4in string data type. The standard techni6ue adopted among )
programmers is that of using null4terminated arrays of characters to represent
strings. This practice if often seen in )OO programs too.
'either )OO or :ava have string as a primitive type& but they do both have string ob%ects that are a standard part of the language.
,n :ava this type is called "tring& and in )OO it is called )"tring.
-ultiple ,nheritance
-ultiple inheritance is a feature of some ob%ect oriented languages that allo#s you to
derive a class from multiple parent classes. 3lthough multiple inheritance is indeed
po#erful /and sometimes the logical #ay to define a class hierachy0& it is complicated
to use correctly and can create situations #here it's uncertain #hich method #ill be
e!ecuted. or e!ample& if each of the parent classes provide a method A and the
derived class does not& it is unclear #hich A should be invo@ed. ,t is also complicated
to implement from the compiler perspective.
)OO supports multiple inheritance. :ava provides no direct support for multiple
inheritance& but you can implement functionality similar to multiple inheritance by
using interfaces in :ava. :ava interfaces provide method descriptions but contain no
implementations. Therefore implementations can only be inherited from one class& so
there is no ambiguity over #hich method to invo@e.
$perator $verloading
$perator overloading enables a class to define special behaviour for built4in operators
#hen they are applied to ob%ects of that class. or e!ample& if the \ /multiply0
operator #as to be used on t#o ob%ects of type -atri!& then matri! multiplication
could be implemented. This allo#s ob%ect types to feel much more tightly integrated
into the language and can deliver much clearer code. 7o#ever& sometimes it is not
clear #hat a particular operator #ould sensibly do for a particular type& #hereas a
#ell4named method call #ould be clear.
$perator overloading is considered a prominent feature in )OO. ,t is not supported in :ava& probably in an effort to @eep the
language as simple as possible and help ensure it is obvious #hat code does& even though it may ta@e longer to type and read.
3utomatic )oercions
eature
)
)OO
:ava
Paradigms
Procedural
Procedural& $$P& Deneric
Programming
$$P& Deneric
Programming /from :ava
I0
orm of
)ompiled "ource
8!ecutable
'ative )ode
8!ecutable 'ative )ode :ava bytecode

Anda mungkin juga menyukai