Sei sulla pagina 1di 159

Table of Contents

Core java ......................................................................................................................................................2


Basics............................................................................................................................................................2
Primitive...................................................................................................................................................12
Inheritance, Method overloading and overriding.....................................................................................23
Overrding........................................................................................................................................................25
WEBI!E " #2........................................................................................................................................$%
Primitive...................................................................................................................................................5#
&ava Basics...............................................................................................................................................'2
Collections (rame Wor).............................................................................................................................%'
E*ce+tion ,andling....................................................................................................................................-2
!hreading ./estions...................................................................................................................................00
(ile 1ame2 !hread3ro/+In4o.java........................................................................................................1#$
Main thread is e*iting............................................................................................................................1#-
Main thread is e*iting............................................................................................................................1#0
5ll Pac)ages..................................................................................................................................................120
&6BC ./estions............................................................................................................................................135
6ata7ase ./estions.......................................................................................................................................1$3
1
Core java
Basics
Q) What is difference between Java and C++?
58 9i8 &ava does not s/++ort +ointers. Pointers are inherentl: insec/re and tro/7lesome. ince +ointers do not
e*ist in &ava. 9ii8 &ava does not s/++ort o+erator overloading. 9iii8 &ava does not +er4orm an: a/tomatic t:+e
conversions that res/lt in a loss o4 +recision 9iv8 5ll the code in a &ava +rogram is enca+s/lated ;ithin one or
more classes. !here4ore, &ava does not have glo7al varia7les or glo7al 4/nctions. 9v8 &ava does not s/++ort
m/lti+le inheritance.
&ava does not s/++ort destr/ctors, 7/t rather, add the 4inali<e98 4/nction. 9vi8 &ava does not have the delete
o+erator. 9vii8 !he == and >> are not overloaded 4or I?O o+erations
Q) Oops concepts
Polymorphism
57ilit: to ta)e more than one 4orm, in java ;e achieve this /sing Method Overloading 9com+ile time
+ol:mor+hism8, Method overriding 9r/ntime +ol:mor+hism8
Inheritance
Is the +rocess 7: ;hich one o7ject ac@/ires the +ro+erties o4 another o7ject. !he advantages o4 inheritance are
re/sa7ilit: o4 code and accessi7ilit: o4 varia7les and methods o4 the s/+er class 7: s/7classes.
Encapsulation
Wra++ing o4 data and 4/nction into a single /nit called enca+s/lation. E*2A all java +rograms.
9Or8
1othing 7/t data hiding, li)e the varia7les declared /nder +rivate o4 a +artic/lar class are accessed onl: in that
class and cannot access in an: other the class. Or ,iding the in4ormation 4rom others is called as
Enca+s/lation. Or Enca+s/lation is the mechanism that 7inds together code and data it mani+/lates and )ee+s
7oth sa4e 4rom o/tside inter4erence and mis/se.
Abstraction
1othing 7/t re+resenting the essential 4/t/res ;itho/t incl/ding 7ac)gro/nd details.
6:namic 7inding
Code associated ;ith a given +roced/ral call is not )no;n /ntil the time o4 the call at r/ntime.
6:namic 7inding is nothing 7/t late 7inding.
Q) class & object?
class class is a 7l/e +rint o4 an o7ject
O7ject instance o4 class.
Q) Object creation?
O7ject is constr/cted either on a memor: hea+ or on a stac).
Memor: hea+
3enerall: the o7jects are created /sing the ne; )e:;ord. ome hea+ memor: is allocated to this ne;l:
created o7ject. !his memor: remains allocated thro/gho/t the li4e c:cle o4 the o7ject. When the o7ject is
no more re4erred, the memor: allocated to the o7ject is eligi7le to 7e 7ac) on the hea+.
tac)
6/ring method calls, o7jects are created 4or method arg/ments and method varia7les. !hese o7jects are
created on stac).
2
Q) Syste!o"t!println#)
+rintln98 is a methd o4 java.io.+rintWriter.
Bo/tC is an instance varia7le o4 java.lang.:stem class.
Q) $ransient & volatile
!ransient AA> !he transient modi4ier a++lies to varia7les onl:, the o7ject are varia7le ;ill not +ersist.
!ransient varia7les are not seriali<ed.
Dolatile AA> val/e ;ill 7e changed /ne*+ectedl: 7: the other +art o4 the +rogram, Eit tells the com+iler a
varia7le ma: change as:nchrono/sl: d/e to threadsE
Q) %ccess Specifiers & %ccess odifiers?
5ccess +eci4iers 5. gives access +rivileges to o/tside o4 a++lication 9or8 others, the: are P/7lic,
Protected, Private, 6e4a/lts.
5ccess Modi4iers 5.M ;hich gives additional meaning to data, methods and classes, 4inal cannot 7e
modi4ied at an: +oint o4 time.
Private P/7lic Protected 1o modi4ier
ame class Fes Fes Fes Fes
ame +ac)age /7class 1o Fes Fes Fes
ame +ac)age nonAs/7class 1o Fes Fes Fes
6i44erent +ac)age s/7class 1o Fes Fes 1o
6i44erent +ac)age nonAs/7class 1o Fes 1o 1o
Q) &efa"lt 'al"es
long A2G'3 to 2G'3 "1
#H
do/7le #.#d
Int A2G31 to 2G31 "1 # (loat #.#4
hort A2G15 to 2G15 "1 # Boolean 4alse
B:te A2G% to 2G% "1 # Char # to 2G% "1 n/ll character 9or8 IJ/
####K

Q) Byte code & J($ copiler & J') & J*+ & J&,
B:te code is a highl: o+timi<ed set o4 instr/ctions. &DM is an inter+reter 4or 7:te code. !ranslating a java
+rogram into 7:te code hel+s ma)es it m/ch easier to r/n a +rogram in a ;ide variet: o4 environment.
JVM is an interpreter for byte code
JIT (Just In Time) is a part of JVM, it compiles byte code into executable code in real time, will increase the
performance of the interpretations.
JR is an implementation of the Ja!a Virtual Machine, which actually executes Ja!a pro"rams.
J#$ is bundle of software that you can use to de!elop Ja!a based software, Tools pro!ided by J#$ is
9i8 javac " com+iler 9ii8 java " inter+retor 9iii8 jd7 " de7/gger 9iv8 java+ A 6isassem7les
9v8 a++letvie;er " 5++lets 9vi8 javadoc A doc/mentation generator 9vii8 javah A LCL header 4ile
generator
Q) Wrapper classes
Primitive data t:+es can 7e converted into o7jects 7: /sing ;ra++er classes. !hese are in java.lang.+ac)age.
.8 6oes &ava +ass method arg/ments 7: val/e or 7: re4erenceM
3
&ava +asses all arg/ments 7: val/e, not 7: re4erence
Q) %r-"ents & .araeters
While de4ining method, varia7le +assed in the method are called +arameters. While /sing those methods,
val/es +assed to those varia7les are called arg/ments.
5rg/ment " Passing end
Parameter " Method di4inaton
Q) ."blic static void ain #Strin- /0 ar-s)
We can overHoad the main98 method.
What i4 the main method is declared as BPrivateCM
!he +rogram com+iles +ro+erl: 7/t at r/ntime it ;ill give EMain method not +/7lic.E Message
What i4 the static modi4ier is removed 4rom the signat/re o4 the main methodM
%ro"ram compiles. &ut at runtime throws an error '(o)uchMethodrror'.
We can ;rite Bstatic +/7lic voidC instead o4 B+/7lic static voidC 7/t not B+/7lic void staticC.
Protected static void main98, static void main98, +rivate static void main98 are also valid.
B/t r/n time it ;ont ;or)N
I4 I do not +rovide the tring arra: as the arg/ment to the methodM
%ro"ram compiles but throws a runtime error '(o)uchMethodrror'.
I4 no arg/ments on the command line, tring arra: o4 Main method ;ill 7e em+t: or n/llM
It is em+t:. B/t not n/ll.
Daria7les can have the same name as a method or a class
Q) Can an application have "ltiple classes havin- ain#) ethod?
58 Fes it is +ossi7le. While starting the a++lication ;e mention the class name to 7e r/n. !he &DM ;ill loo)
4or the Main method onl: in the class ;hose name :o/ have mentioned. ,ence there is not con4lict amongst
the m/lti+le classes having main method.
Q) Can ( have "ltiple ain ethods in the sae class?
58 1o the +rogram 4ails to com+ile. !he com+iler sa:s that the main method is alread: de4ined in the class.
Else ;ith di44erent arg/ments
Q) Constr"ctor
!he a/tomatic initiali<ation is +er4ormed thro/gh the constr/ctor, constr/ctor has same name has class
name. Constr/ctor has no ret/rn t:+e not even void. We can +ass the +arameters to the constr/ctor. this98 is
/sed to invo)e a constr/ctor o4 the same class. /+er98 is /sed to invo)e a s/+er class constr/ctor. Constr/ctor
is called immediatel: a4ter the o7ject is created 7e4ore the ne; o+erator com+letes.
Constr/ctor can /se the access modi4iers +/7lic, +rotected, +rivate or have no access modi4ier
Constr/ctor can not /se the modi4iers a7stract, static, 4inal, native, s:nchroni<ed or strict4+
Constr/ctor can 7e overloaded, ;e cannot override.
Fo/ cannot /se this98 and /+er98 in the same constr/ctor.
Class A(
A(){
:stem.o/t.+rintln9BhelloC8O
PP
$
Class B e*tends 5 Q
B98Q
:stem.o/t.+rintln9B4riendC8O
PP
Class +rint Q
P/7lic static void main 9tring args RS8Q
B 7 T ne; B98O
P
o?+2A hello 4riend
Q) &iff between Constr"ctor & )ethod
Constr/ctor Method
Use to instance of a class Grouping java statement
1o ret/rn t:+e Doid 9or8 valid ret/rn t:+e
ame name as class name 5s a name e*ce+t the class method name, 7egin
;ith lo;er case.
B!hisC re4er to another constr/ctor in the same
class
Refers to instance of class
B/+erC to invo)e the s/+er class constr/ctor
Execute an overridden method in the super
class
nheritance! cannot "e inherited
Can 7e inherited
#e can overload! "ut $e cannot
overridden!
Can 7e inherited
#ill automaticall% invo&e $hen an
o"ject is created
Method has called e*+licitl:
Q) 1arba-e collection
3.C is also called a/tomatic memor: management as &DM a/tomaticall: removes the /n/sed
varia7les?o7jects 9val/e is n/ll8 4rom the memor:. User +rogram cannLt directl: 4ree the o7ject 4rom memor:,
instead it is the jo7 o4 the gar7age collector to a/tomaticall: 4ree the o7jects that are no longer re4erenced 7: a
+rogram. Ever: class inherits 4inali<e98 method 4rom java.lang.O7ject, the 4inali<e98 method is called 7:
gar7age collector ;hen it determines no more re4erences to the o7ject e*ists. In &ava, it is good idea to
e*+licitl: assign n/ll into a varia7le ;hen no more in /se, calling :stem.gc98 and V/ntime.gc98, &DM tries to
rec:cle the /n/sed o7jects, 7/t there is no g/arantee ;hen all the o7jects ;ill gar7age collected. 3ar7age
collection is a lo;A+riorit: thread.
G.C is a low priority thread in java, G.C cannot be forced explicitly. JVM may do garbage collection if it is
running short of memory. he call !ystem.gc"# does $% force the garbage collection but only suggests
that the JVM may ma&e an effort to do garbage collection.
Q) 2ow an object becoes eli-ible for 1arba-e Collection?
58 5n o7ject is eligi7le 4or gar7age collection ;hen no o7ject re4ers to it, 5n o7ject also 7ecomes eligi7le
;hen its re4erence is set to n/ll. !he o7jects re4erred 7: method varia7les or local varia7les are eligi7le 4or
gar7age collection ;hen the: go o/t o4 sco+e.
Integer i T ne; Integer9%8O
i T n/llO
Q) 3inal4 3inally4 3inali5e
*inal+ , -hen we declare a sub class a final the compiler will "i!e error as .cannot subclass final class/ *inal to pre!ent
inheritance and method o!erridin". 0nce to declare a !ariable as final it cannot occupy memory per instance basis.
5
(inal class cannot have static methods
(inal class cannot have a7stract methods 9Beca/se o4 4inal class never allo;s an: class to inherit it8
'inal class can have a final method.
(inall:2 A (inall: create a 7loc) o4 code that ;ill 7e e*ec/ted a4ter tr: catch 7loc) has com+leted. (inall:
7loc) ;ill e*ec/te ;hether or not an e*ce+tion is thro;n. I4 an e*ce+tion is thro;n, the 4inall: 7loc) ;ill
e*ec/te even i4 no catch statement match the e*ce+tion. 5n: time a method is a7o/t to ret/rn to the caller
4rom inside tr:?catch 7loc), via an /nca/ght e*ce+tion or an e*+licit ret/rn statement, the 4inall: cla/se is also
e*ec/te.
Using :stem.e*it98 in tr: 7loc) ;ill not allo; 4inall: code to e*ec/te
(inali<e2 A some times an o7ject need to +er4orm some actions ;hen it is going to destro:, i4 an o7ject holding
some nonAjava reso/rce s/ch as 4ile handle 9or8 ;indo; character 4ont, these reso/rces are 4reed 7e4ore the
o7ject is going to destro:.
Q) Can we declare abstract ethod in final class?
58 It indicates an error to declare a7stract method in 4inal class. Beca/se o4 4inal class never allo;s an: class
to inherit it.
Q) Can we declare final ethod in abstract class?
58 I4 a method is de4ined as 4inal then ;e canKt +rovide the reim+lementation 4or that 4inal method in itKs
derived classes i.e overriding is not +ossi7le 4or that method. We can declare 4inal method in a7stract class
s/++ose o4 it is a7stract too, then there is no /sed to declare li)e that.
Q) S"perclass & S"bclass
5 s/+er class is a class that is inherited ;hereas s/7class is a class that does the inheriting
Q) 2ow will " ipleent 6) polyorphis 7) "ltiple inheritance 8) "ltilevel inheritance in java?
58 Pol:mor+hism " overloading and overriding
Multiple inheritances 1 interfaces.
M/ltilevel inheritance " e*tending class.
Q) Overloadin- & Overridin-?
Overloading 9Com+ile time +ol:mor+hism8
6e4ine t;o or more methods ;ithin the same class 9or8 s/7class that share the same name and their
n/m7er o4 +arameter, order o4 +arameter W ret/rn t:+e are di44erent then the methods are said to 7e
overloaded.
Overloaded methods do not have an: restrictions on ;hat ret/rn t:+e o4 Method 9Vet/rn t:+e are
di44erent8 9or8 e*ce+tions can 7e thro;n. !hat is something to ;orr: a7o/t ;ith overriding.
Overloading is /sed ;hile im+lementing several methods that im+lement similar 7ehavior 7/t 4or di44erent
data t:+es.
Overriding 9V/ntime +ol:mor+hism8
When a method in a s/7class has the same name, ret/rn t:+e W +arameters as the method in the s/+er
class then the method in the s/7class is override the method in the s/+er class.
!he access modi4ier 4or the overriding method ma: not 7e more restrictive than the access modi4ier o4
the s/+erclass method.
'
I4 the s/+erclass method is +/7lic, the overriding method m/st 7e +/7lic.
I4 the s/+erclass method is +rotected, the overriding method ma: 7e +rotected or +/7lic.
I4 the s/+erclass method is +ac)age, the overriding method ma: 7e +ac)agage, +rotected, or +/7lic.
I4 the s/+erclass methods is +rivate, it is not inherited and overriding is not an iss/e.
Methods declared as 4inal cannot 7e overridden.
!he thro;s cla/se o4 the overriding method ma: onl: incl/de e*ce+tions that can 7e thro;n 7: the
s/+erclass method, incl/ding its s/7classes.

Onl: mem7er method can 7e overriden, not mem7er varia7le
class ParentQ
int i T #O
void amethod98Q
:stem.o/t.+rintln9Ein ParentE8O
P
P
class Child e*tends ParentQ
int i T 1#O
void amethod98Q
:stem.o/t.+rintln9Ein ChildE8O
P
P
class !estQ
+/7lic static void main9tringRS args8Q
Parent + T ne; Child98O
Child c T ne; Child98O
:stem.o/t.+rint9EiTEX+.iXE E8O
+.amethod 98O
:stem.o/t.+rint9EiTEXc.iXE E8O
c.amethod98O
P
P
o?+2 A iT# in Child iT1# in Child
Q) 3inal variable
0nce to declare a !ariable as final it cannot occupy memory per instance basis.
Q) Static bloc9
)tatic bloc2 which exactly executed exactly once when the class is first loaded into JVM. &efore "oin" to the
main method the static bloc2 will execute.
)tatic and contructor
( static initiali)er bloc& will execute when a class is initiali)ed ** right after the class is loaded. his will happen "basically# the first time the class is
referenced in the program. $o instances need to be created. he static bloc& will only be executed once "or in any case, only once each time the class
is loaded.#
( constructor executes when, and only when, the +new+ operator is used, or the Class.new,nstance"# or Constructor.new,nstance"# methods are
called.
here are also instance initializer blocks- they loo& li&e static initiali)ers except without the +static+ &eyword- just a bare set of brac&ets outside of
any method. hese get inserted into each of the class.s constructors immediately after the call to the superclass constructor, and before the
statements in the constructor body.
Q) Static variable & Static ethod
%
)tatic !ariables 3 methods are instantiated only once per class. In other words they are class !ariables, not
instance !ariables. If you chan"e the !alue of a static !ariable in a particular ob4ect, the !alue of that !ariable chan"es
for all instances of that class.
)tatic methods can be referenced with the name of the class. It may not access the instance !ariables of that
class, only its static !ariables. *urther it may not in!o2e instance (non,static) methods of that class unless it pro!ides
them with some ob4ect.
When a mem7er is declared a static it can 7e accessed 7e4ore an: o7ject o4 its class are created.
Instance varia7les declared as static are essentiall: glo7al varia7les.
I4 :o/ do not s+eci4: an initial val/e to an instance W tatic varia7le a de4a/lt val/e ;ill 7e assigned
a/tomaticall:.
Methods declared as static have some restrictions the: can access onl: static data, the: can onl: call other
static data, the: cannot re4er this or s/+er.
tatic methods cant 7e overriden to nonAstatic methods.
tatic methods is called 7: the static methods onl:, an ordinar: method can call the static methods, 7/t
static methods cannot call ordinar: methods.
tatic methods are im+licitl: E4inalE, 7eca/se overriding is onl: done 7ased on the t:+e o4 the o7jects
!he: cannot re4er BthisC are Bs/+erC in an: ;a:.
Q) Class variable & (nstance variable & (nstance ethods & class ethods
Instance !ariable !ariables defined inside a class are called instance !ariables with multiple instance of class, each
instance has a !ariable stored in separate memory location.
Class varia7les :o/ ;ant a varia7le to 7e common to all classes then ;e crate class varia7les. !o create a
class varia7le +/t the BstaticC )e:;ord 7e4ore the varia7le name.
Class methods ;e create class methods to allo; /s to call a method ;itho/t creating instance o4 the class.
!o declare a class method /se the BstaticC )e: ;ord .
Instance methods ;e de4ine a method in a class, in order to /se that methods ;e need to 4irst create o7jects
o4 the class.
Q) Static ethods cannot access instance variables why?
tatic methods can 7e invo)ed 7e4ore the o7ject is createdO Instance varia7les are created onl: ;hen
the ne; o7ject is created. ince there is no +ossi7ilit: to the static method to access the instance varia7les.
Instance varia7les are called called as nonAstatic varia7les.
Q) Strin- & Strin-B"ffer
tring is a 4i*ed length o4 se@/ence o4 characters, tring is imm/ta7le.
tringB/44er re+resent gro;a7le and ;ritea7le character se@/ence, tringB/44er is m/ta7le ;hich
means that its val/e can 7e changed. It allocates room 4or 1'Aaddition character s+ace ;hen no s+eci4ic length
is s+eci4ied. &ava.lang.tringB/44er is also a 4inal class hence it cannot 7e s/7 classed. tringB/44er cannot 7e
overridden the e@/als98 method.
Q) Conversions
tring to Int Conversion2 A
int I T integer.val/eO49B2$C8.intDal/e98O
int * T integer.+arseInt9B$33C8O
4loat 4 T 4loat.val/eO4923.08.4loatDal/e98O
-
Int to tring Conversion 2A
tring arg T tring.val/eO491#8O
Q) S"per#)
)uper() always callin" the constructor of immediate super class, super() must always be the first statements
executed inside a subclass constructor.
Q) What are different types of inner classes?
58 1ested to+Alevel classesA I4 :o/ declare a class ;ithin a class and s+eci4: the static modi4ier, the com+iler
treats the class j/st li)e an: other to+Alevel class. 5n: class o/tside the declaring class accesses the nested
class ;ith the declaring class name acting similarl: to a +ac)age. e.g., o/ter.inner. !o+Alevel inner classes
im+licitl: have access onl: to static varia7les. !here can also 7e inner inter4aces. 5ll o4 these are o4 the nested
to+Alevel variet:.
Mem7er classes A Mem7er inner classes are j/st li)e other mem7er methods and mem7er varia7les and access
to the mem7er class is restricted, j/st li)e methods and varia7les. !his means a +/7lic mem7er class acts
similarl: to a nested to+Alevel class. !he +rimar: di44erence 7et;een mem7er classes and nested to+Alevel
classes is that mem7er classes have access to the s+eci4ic instance o4 the enclosing class.
Hocal classes A Hocal classes are li)e local varia7les, s+eci4ic to a 7loc) o4 code. !heir visi7ilit: is onl: ;ithin
the 7loc) o4 their declaration. In order 4or the class to 7e /se4/l 7e:ond the declaration 7loc), it ;o/ld need to
im+lement a more +/7licl: availa7le inter4ace. Beca/se local classes are not mem7ers the modi4iers +/7lic,
+rotected, +rivate and static are not /sa7le.
5non:mo/s classes A 5non:mo/s inner classes e*tend local inner classes one level 4/rther. 5s anon:mo/s
classes have no name, :o/ cannot +rovide a constr/ctor.
Inner class inside method cannot have static mem7ers or 7loc)s
Q) Which circ"stances yo" "se %bstract Class & (nterface?
**/ ,f you need to change your design ma&e it an interface.
AA> 57stract class +rovide some de4a/lt 7ehavio/r, 5.C are e*cellent candidates inside o4 a++lication
4rame;or). 5.C allo; single inheritance model, ;hich sho/ld 7e ver: 4aster.
Q) %bstract Class
5n: class that contain one are more a7stract methods m/st also 7e declared as an a7stract, there can 7e
no o7ject o4 an a7stract class, ;e cannot directl: instantiate the a7stract classes. 5.C can contain concrete
methods.
5n: s/7 class o4 an 57stract class m/st either im+lement all the a7stract methods in the s/+er class or 7e
declared itsel4 as 57stract.
Com+ile time error occ/r i4 an attem+t to create an instance o4 an 57stract class.
Fo/ cannot declare Ba7stract constr/ctorC and Ba7stract static methodC.
5n Ba7stract methodC also declared +rivate, native, 4inal, s:nchroni<ed, strict4+, +rotected.
57stract class can have static, 4inal method 97/t there is no /se8.
57stract class have visi7ilit: +/7lic, +rivate, +rotected.
B: de4a/lt the methods W varia7les ;ill ta)e the access modi4iers is =de4a/lt>, ;hich is accessi7ilit: as
+ac)age.
5n a7stract method declared in a nonAa7stract class. 1O
5n a7stract class can have instance methods that im+lement a de4a/lt 7ehavior.
0
5 class can 7e declared a7stract even i4 it does not act/all: have an: a7stract methods. 6eclaring s/ch a
class a7stract indicates that the im+lementation is someho; incom+lete and is meant to serve as a s/+er class
4or one or more s/7classes that ;ill com+lete the im+lementation.
5 class ;ith an a7stract method. 5gain note that the class itsel4 is declared a7stract, other;ise a com+ile
time error ;o/ld have occ/rred.
57stract class 5Q
P/7lic a7stract callme98O
Doid callmetoo98Q
P
P
class B e*tends 59
void callme(){
P
P
class 57stract6emoQ
+/7lic static void main9string argsRS8Q
B 7 T ne; B98O
7.callme98O
7.callmetoo98O
P
P
Q) When we "se %bstract class?
58 Het /s ta)e the 7ehavio/r o4 animals, animals are ca+a7le o4 doing di44erent things li)e 4l:ing, digging,
Wal)ing. B/t these are some common o+erations +er4ormed 7: all animals, 7/t in a di44erent ;a: as ;ell.
When an o+eration is +er4ormed in a di44erent ;a: it is a good candidate 4or an a7stract method.
P/7lic 57starctclass 5nimalQ
P/7lic void eat94ood 4ood8 Q
P
+/7lic void slee+9int ho/rs8 Q
P
+/7lic a7stract void ma)e1oise98
P
+/7lic 6og e*tends 5nimal
Q
+/7lic void ma)e1oise98 Q
:stem.o/t.+rintln9BBar)Y Bar)C8O
P
P
+/7lic Co; e*tends 5nimal
Q
+/7lic void ma)e1oise98 Q
:stem.o/t.+rintln9BmooY mooC8O
P
1
P
Q) (nterface
Inter4ace is similar to class 7/t the: lac) instance varia7le, their methods are declared ;ith o/t an:
7od:. Inter4aces are designed to s/++ort d:namic method resol/tion at r/n time. 5ll methods in inter4ace are
im+licitl:
a7stract, even i4 the a7stract modi4ier is omitted. Inter4ace methods have no im+lementationO
Inter4aces are /se4/l 4orM
a8 6eclaring methods that one or more classes are e*+ected to im+lement
78 Ca+t/ring similarities 7et;een /nrelated classes ;itho/t 4orcing a class relationshi+.
c8 6etermining an o7jectLs +rogramming inter4ace ;itho/t revealing the act/al 7od: o4 the class.
Why (nterfaces?
. one interface multiple methods . si"nifies the polymorphism concept.
Inter4ace has visi7ilit: +/7lic.
Inter4ace can 7e e*tended W im+lemented.
5n inter4ace 7od: ma: contain constant declarations, a7stract method declarations, inner classes and inner
inter4aces.
5ll methods o4 an inter4ace are im+licitl: 57stract, P/7lic, even i4 the +/7lic modi4ier is omitted.
5n inter4ace methods cannot 7e declared +rotected, +rivate, strict4+, native or s:nchroni<ed.
5ll Daria7les are im+licitl: 4inal, +/7lic, static 4ields.
5 com+ile time error occ/rs i4 an inter4ace has a sim+le name the same as an: o4 itLs enclosing classes or
inter4aces.
5n Inter4ace can onl: declare constants and instance methods, 7/t cannot im+lement de4a/lt 7ehavior.
to+Alevel inter4aces ma: onl: 7e declared +/7lic, inner inter4aces ma: 7e declared +rivate and +rotected 7/t
onl: i4 the: are de4ined in a class.
5 class can onl: e*tend one other class.
5 class ma: im+lements more than one inter4ace.
Inter4ace can e*tend more than one inter4ace.
Inter4ace 5
Q
4inal static 4loat +i T 3.1$4O
P
class B im+lements 5
Q
+/7lic 4loat com+/te94loat *, 4loat :8 Q
ret/rn9*Z:8O
P
P
class testQ
+/7lic static void main9tring argsRS8
Q
5 a T ne; B98O
a.com+/te98O
1
P
P
Q) &iff (nterface & %bstract Class?
5.C ma: have some e*ec/ta7le methods and methods le4t /nim+lemented. Inter4ace contains no
im+lementation code.
5n 5.C can have nona7stract methods. 5ll methods o4 an Inter4ace are a7stract.
5n 5.C can have instance varia7les. 5n Inter4ace cannot.
5n 5.C m/st have s/7classes ;hereas inter4ace canLt have s/7classes
5n 5.C can de4ine constr/ctor. 5n Inter4ace cannot.
5n 5.6 can ha!e any !isibility+ public, pri!ate, protected. 5n Interface !isibility must be public (or) none.
5n 5.C can have instance methods that im+lement a de4a/lt 7ehavior. 5n Inter4ace can onl: declare
constants and instance methods, 7/t cannot im+lement de4a/lt 7ehavior.
Q) What is the difference between (nterface and class?
5 class has instance varia7le and an Inter4ace has no instance varia7les.
O7jects can 7e created 4or classes ;here as o7jects cannot 7e created 4or inter4aces.
5ll methods de4ined inside class are concrete. Methods declared inside inter4ace are ;itho/t an: 7od:.
Q) What is the difference between %bstract class and Class?
Classes are 4/ll: de4ined. 57stract classes are not 4/ll: de4ined 9incom+lete class8
O7jects can 7e created 4or classes, there can 7e no o7jects o4 an a7stract class.
16.Describe the wrapper classes in Java.
Answer: Wra++er class is ;ra++er aro/nd a +rimitive data t:+e. 5n instance o4 a ;ra++er class contains, or
;ra+s, a +rimitive val/e o4 the corres+onding t:+e.
(ollo;ing ta7le lists the +rimitive t:+es and the corres+onding ;ra++er classes2
.riitive
Wrapper
Boolean java.lang.Boolean
Byte java.lang.B:te
har java.lang.Character
Double java.lang.6o/7le
!loat java.lang.(loat
Int java.lang.Integer
"on# java.lang.Hong
$hort java.lang.hort
%oi& java.lang.Doid
'. What is similarities(&i))erence between an Abstract class an& Inter)ace*
1
Answer: 6i44erences are as 4ollo;s2
Inter4aces +rovide a 4orm o4 m/lti+le inheritance. 5 class can e*tend onl: one other class.
Inter4aces are limited to +/7lic methods and constants ;ith no im+lementation. 57stract classes can
have a +artial im+lementation, +rotected +arts, static methods, etc.
5 Class ma: im+lement several inter4aces. B/t in case o4 a7stract class, a class ma: e*tend onl: one
a7stract class.
Inter4aces are slo; as it re@/ires e*tra indirection to to 4ind corres+onding method in in the act/al
class. 57stract classes are 4ast.
$imilarities:
1either 57stract classes or Inter4ace can not 7e instantiated.
1+. E,plain the &i))erent )orms o) Polymorphism.
Answer: (rom a +ractical +rogramming vie;+oint, +ol:mor+hism e*ists in three distinct 4orms in &ava2
Method overloading
Method overriding thro/gh inheritance
Method overriding thro/gh the &ava inter4ace
Q) What are soe alternatives to inheritance?
58 6elegation is an alternative to inheritance. 6elegation means that :o/ incl/de an instance o4 another class
as an instance varia7le, and 4or;ard messages to the instance. It is o4ten sa4er than inheritance 7eca/se it
4orces :o/ to thin) a7o/t each message :o/ 4or;ard, 7eca/se the instance is o4 a )no;n class, rather than a
ne; class, and 7eca/se it doesnKt 4orce :o/ to acce+t all the methods o4 the s/+er class2 :o/ can +rovide onl:
the methods that reall: ma)e sense. On the other hand, it ma)es :o/ ;rite more code, and it is harder to reA/se
97eca/se it is not a s/7class8.
Q) Seriali5able & +:ternali5able
0. ,n case of !eriali)able, default serialization process is used. while in case of 1xternali)able custom
!eriali)ation process is used which is implemented by application.
2. JVM gives call bac& to readExternel() and $riteExternal() of java'io'Externali(al"e interface
for restoring and writing objects into persistence.
3. Externalizable interface provides complete control of seriali)ation process to application.
4. readExternal() and $riteExternal() supersede any specific implementation
of $rite)"ject and read)"ject methods.
Read more: http://javarevisited.blogspot.com/2012/01/serializable-externalizable-in-java.html#ixzz2P!tx1"n
Q) (nternalisation & ;ocali5ation
Internalisation AA Ma)ing a +rogramme to 4le*i7le to r/n in an: locale called internalisation.
Hocali<ation AA Ma)ing a +rogramme to 4le*i7le to r/n in a s+eci4ic locale called Hocali<ation.
Q) Seriali5ation
1
eriali<ation is the +rocess o4 ;riting the state o4 the o7ject to a 7:te stream, this is /se4/l ;hen ever
:o/ ;ant to save the state o4 :o/r +rogramme to a +ersistence storage area.
Q) Synchroni5ation
:nchroni<ation is a +rocess o4 controlling the access o4 shared reso/rces 7: the m/lti+le threads in
s/ch a manner that onl: one thread can access one reso/rce at a time. 9Or8 When 2 are more threads need to
access the shared reso/rces the: need to some ;a: ens/re that the reso/rces ;ill 7e /sed 7: onl: one thread at
a time. !his +rocess ;hich is achieved is called s:nchroni<ation.
9i8 E*2 A :nchroni<ing a 4/nction2
+/7lic s:nchroni<ed void Method1 98 Q
P
9i8 E*2 A :nchroni<ing a 7loc) o4 code inside a 4/nction2
+/7lic m:(/nction 98Q
s:nchroni<ed 9this8 Q
P
P
9iii8 E*2 A +/7lic :nchroni<ed void main9tring argsRS8
B/t this is not the right a++roach 7eca/se it means servlet can handle one re@/est at a time.
9iv8 E*2 A +/7lic :nchroni<ed void service98
ervlet handle one re@/est at a time in a seriali<ed manner
Q) &ifferent level of loc9in- "sin- Synchroni5ation?
58 Class level, O7ject level, Method level, Bloc) level
*irst of all to achie!e Multithreadin" mechanism in 4a!a we should "o for synchroni7ation. 5nd this can be done in two ways dependin" on the
re8uirement.
9. )ynchroni7ed bloc2 and
:. )ynchroni7ed method.
if you "o for synchroni7ed bloc2 it will loc2 a specific ob4ect.
if you "o for synchroni7ed method it will loc2 all the ob4ects.
in other way &oth the synchroni7ed method and bloc2 are used to ac8uires the loc2 for an ob4ect. &ut the context may !ary. )uppose if we want to
in!o2e a critical method which is in a class whose access is not a!ailable then synchroni7ed bloc2 is used. 0therwise synchroni7ed method can be
used.
)ynchroni7ed methods are used when we are sure all instance will wor2 on the same set of data throu"h the same function )ynchroni7ed bloc2 is
used when we use code which we cannot modify oursel!es li2e third party 4ars etc
Q) )onitor
5 monitor is a m/te*, once a thread enter a monitor, all other threads m/st ;ait /ntil that thread e*ist
the monitor.
Q) &iff < < and !e="als#)?
58 TT Com+are o7ject re4erences ;hether the: re4er to the sane instance are not.
e@/als 98 method com+are the characters in the string o7ject.
tringB/44er s71 T ne; tringB/44er9E5mitE8O
tringB/44er s72T ne; tringB/44er9E5mitE8O
tring s1 T E5mitEO
tring s2 T E5mitEO
1
tring s3 T ne; tring9Ea7cdE8O
tring s$ T ne; tring9Ea7cdE8O
tring ss1 T E5mitEO
9s71TTs728O ( 9s1.e@/als9s288O !
9s71.e@/als9s7288O ( 99s1TTs288O !
9s71.e@/als9ss188O ( 9s3.e@/als9s$88O !
99s3TTs$88O (
tring s1 T Ea7cEO
tring s2 T ne; tring9Ea7cE8O
s1 TT s2 (
s1.e@/als9s288 !
1-. where an& how can you use a private constructor.
Answer: Private constr/ctor can 7e /sed i4 :o/ do not ;ant an: other class to instanstiate the o7ject , the
instantiation is done 4rom a static +/7lic method, this method is /sed ;hen dealing ;ith the 4actor: method
+attern ;hen the designer ;ants onl: one controller 94ator: method 8 to create the o7ject.
'6. Parsers* D./ vs $A0 parser
Answer: +arsers are 4/ndamental *ml com+onents, a 7ridge 7et;een [MH doc/ments and a++lications that
+rocess that [MH. !he +arser is res+onsi7le 4or handling *ml s:nta*, chec)ing the contents o4 the doc/ment
against constraints esta7lished in a 6!6 or chema.
'1. Di))erence between $A0 an& D./
In simple $A0 is )aster2 ant insert or &elete2 .ccupy less memory
D./ traverse in any &irection an& tree mo&el parser
5[
\ Parses node 7: node
\ 6oesnKt store the [MH in memor:
\ We cant insert or delete a node
\ 5[ is an event 7ased +arser
\ 5[ is a im+le 5PI 4or [MH
\ doesnKt +reserve comments
\ 5[ generall: r/ns a little 4aster than 6OM
6OM
\ tores the entire [MH doc/ment into memor: 7e4ore +rocessing
\ Occ/+ies more memor:
\ We can insert or delete nodes
\ !raverse in an: direction.
\ 6OM is a tree model +arser
\ 6oc/ment O7ject Model 96OM8 5PI
1
\ Preserves comments
\ 5[ generall: r/ns a little 4aster than 6OM

Q) )ar9er (nterfaces #or) $a--ed (nterfaces >?
5n Inter4ace ;ith no methods. Is called mar)er Inter4aces, eg. eriali<a7le, ingle!hread Model,
Clonea7le.
Q) @*; +ncodin- & @*; &ecodin-
UVH Encoding is the method o4 re+lacing all the s+aces and other e*tra characters into their
corres+onding ,e* Characters and UVH 6ecoding is the reverse +rocess converting all ,e* Characters 7ac)
their normal 4orm.
Q) @*; & @*;Connection
UVH is to identi4: a reso/rce in a net;or), is onl: /sed to read something 4rom the net;or).
UVH /rl T ne; UVH9+rotocol name, host name, +ort, /rl s+eci4ier8
UVHConnection can esta7lish comm/nication 7et;een t;o +rograms in the net;or).
UVH h+ T ne; UVH9B;;;.:ahoo.comC8O
UVHConnection con T h+.o+enConnection98O
Q) *"ntie class
V/ntime class enca+s/late the r/nAtime environment. Fo/ cannot instantiate a V/ntime o7ject. Fo/ can
get a re4erence to the c/rrent V/ntime o7ject 7: calling the static method V/ntime.getV/ntime98
V/ntime r T V/ntime.getV/ntime98
Hong mem1O
Mem1 T r.4reeMemor:98O
Mem1 T r.totalMemor:98O
Q) +:ec"te other pro-ras
5ou can use java to execute other heavy weight process on your multi tas&ing operating system,
several form of exec"# method allow you to name the programme you want to run.
V/ntime r T V/ntime.getV/ntime98O
Process + T n/llO
!r:Q
+ T r.e*ce9Bnote+adC8O
+.;ai(or98
P
Q) Syste class
:stem class hold a collection o4 static methods and varia7les. !he standard in+/t, o/t+/t, error o/t+/t
o4 the java r/ntime are stored in the in, o/t, err varia7les.
Q) Aative )ethods
1ative methods are /sed to call s/7ro/tine that is ;ritten in a lang/age other than java, this s/7ro/tine
e*ist as e*ec/ta7le code 4or the CPU.
Q) Cloneable (nterface
(ny class that implements the cloneable interface can be cloned, this interface defines no
methods. ,t is used to indicate that a class allow a bit wise copy of an object to be made.
1
Q) Clone
Generate a duplicate copy of the object on which it is called. Cloning is a dangerous action.
Q) Coparable (nterface
Classes that im+lements com+ara7le contain o7jects that can 7e com+ared in some meaning4/l
manner. !his inter4ace having one method com+are the invo)ing o7ject ;ith the o7ject. (or sorting
com+ara7le inter4ace ;ill 7e /sed.
E*2A int com+are!o9O7ject o7j8
Q) Class
Class encapsulate the run*time state of an object or interface. Methods in this class are
static Class for$ame"!tring name#
throws Class$ot'ound1xception
getClass"#
getClass6oader"# getConstructor"#
get'ield"# get7eclared'ields"#
getMethods"# get7eclearedMethods"#
get,nterface"# get!uperClass"#
Q) java!jlan-!*eflect #pac9a-e)
Ve4lection is the a7ilit: o4 so4t;are to anal:se it sel4, to o7tain in4ormation a7o/t the 4ield, constr/ctor,
methods W modi4ier o4 class. Fo/ need this in4ormation to 7/ild so4t;are tools that ena7les :o/ to ;or) ;ith
java 7eans com+onents.
Q) (nstanceOf
nstanceof means "% $hich %our program can o"tain run time t%pe information a"out
an o"ject'
Ex*+ A a , ne$ A()-
a'instance)f A-
.) /ava pass arguments "% value are "% reference0
A) 1% value
.) /ava lac& pointers ho$ do implements classic pointer structures li&e lin&ed list0
A) Using o"ject reference'
.) java' Exe
2icro soft provided sd& for java3 $hich includes jexegentool!' 4his converts class file
into a 'Exec! form' )nl% disadvantage is user needs a 2'5 java 6'2 installed'
.8 Bin W Hi7 in jd)M
8in contains all tools such as javac, appletviewer and awt tool.
Hi7 contains 5PI and all +ac)ages.
B! What is a platfor?

5 +lat4orm is the hard;are or so4t;are environment in ;hich a +rogram r/ns. Most +lat4orms can 7e
descri7ed as a com7ination o4 the o+erating s:stem and hard;are, li)e Windo;s 2### and [P, Hin/*, olaris,
and MacO.
C! What is the ain difference between Java platfor and other platfors?
1
!he &ava +lat4orm di44ers 4rom most other +lat4orms in that itLs a so4t;areAonl: +lat4orm that r/ns on to+ o4
other hard;areA7ased +lat4orms.
!he &ava +lat4orm has t;o com+onents2
1. !he &ava Dirt/al Machine 9&ava DM8
2. !he &ava 5++lication Programming Inter4ace 9&ava 5PI8
D! What is the Java 'irt"al )achine?
!he &ava Dirt/al Machine is so4t;are that can 7e +orted onto vario/s hard;areA7ased +lat4orms
E! What is the Java %.(?
!he &ava 5PI is a large collection o4 read:Amade so4t;are com+onents that +rovide man: /se4/l ca+a7ilities,
s/ch as gra+hical /ser inter4ace 93UI8 ;idgets.
F! What is the pac9a-e?

!he +ac)age is a &ava names+ace or +art o4 &ava li7raries. !he &ava 5PI is gro/+ed into li7raries o4 related
classes and inter4acesO these li7raries are )no;n as +ac)ages.
6G! What is native code?
!he native code is code that a4ter :o/ com+ile it, the com+iled code r/ns on a s+eci4ic hard;are +lat4orm.
66! (s Java code slower than native code?

1ot reall:. 5s a +lat4ormAinde+endent environment, the &ava +lat4orm can 7e a 7it slo;er than native code.
,o;ever, smart com+ilers, ;ellAt/ned inter+reters, and j/stAinAtime 7:tecode com+ilers can 7ring
+er4ormance close to that o4 native code ;itho/t threatening +orta7ilit:.
67! Can ain#) ethod be overloaded?
Fes. the main98 method is a s+ecial method 4or a +rogram entr:. Fo/ can overload main98 method in an: ;a:s.
B/t i4 :o/ change the signat/re o4 the main method, the entr: +oint 4or the +rogram ;ill 7e gone.
68! What is the seriali5ation?
!he seriali<ation is a )ind o4 mechanism that ma)es a class or a 7ean +ersistence 7: having its +ro+erties or
4ields and state in4ormation saved and restored to and 4rom storage.
6H! 2ow to a9e a class or a bean seriali5able?
B: im+lementing either the java.io.eriali<a7le inter4ace, or the java.io.E*ternali<a7le inter4ace. 5s long as
one class in a classLs inheritance hierarch: im+lements eriali<a7le or E*ternali<a7le, that class is
Inheritance
58 Which class does 7egin &ava class hierarch:M
1
5ns 2 O7ject class
'8 O7ject class is a s/+erclass o4 all other classesM
!r/e?(alse
5ns 2 !r/e
%8 &ava s/++orts m/lti+le inheritanceM
!r/e?(alse
5ns 2 (alse
1#8 Which method is /sed to call the constr/ctors o4 the s/+erclass 4rom the s/7classM
5ns 2 s/+er9arg/ment8
118 Which is /sed to e*ec/te an: method o4 the s/+erclass 4rom the s/7classM
5ns 2 s/+er.methodAname9arg/ments8
128 Which methods are /sed to destro: the o7jects created 7: the constr/ctor methodsM
5ns 2 4inali<e98
158 Which methods in the O7ject class are declared as 4inalM
5ns 2 getClass98, noti4:98, noti4:5ll98, and ;ait98
1%8 6eclaration o4 methods as 4inal res/lts in 4aster e*ec/tion o4 the +rogramM
!r/e?(alse
5ns2 !r/e
1-8 (inal varia7les sho/ld 7e declared in the 7eginningM
!r/e?(alse
5ns 2 !r/e
108 Can ;e declare varia7le inside a method as 4inal varia7lesM Wh:M
5ns 2 Cannot 7eca/se, local varia7le cannot 7e declared as 4inal varia7les.
2#8 Can an a7stract class ma: 7e 4inalM
5ns 2 5n a7stract class ma: not 7e declared as 4inal.
218 6oes a class inherit the constr/ctors o4 itLs s/+er classM
5ns2 5 class does not inherit constr/ctors 4rom an: o4 itLs s/+er classes.
228 What restrictions are +laced on method overloadingM
5ns2 !;o methods ma: not have the same name and arg/ment list 7/t di44erent ret/rn t:+es.
238 What restrictions are +laced on method overridingM
5ns 2 Overridden methods m/st have the same name , arg/ment list , and ret/rn t:+e. !he overriding method
ma: not limit the access o4 the method it overridees.!he overriding method ma: not thro; an: e*ce+tions that
ma: not 7e thro;n 7: the overridden method.
2$8 What modi4iers ma: 7e /sed ;ith an inner class that is a mem7er o4 an o/ter classM
5ns 2 a 9nonAlocal8 inner class ma: 7e declared as +/7lic, +rotected, +rivate, static, 4inal or a7stract.
258 ,o; this98 is /sed ;ith constr/ctorsM
5ns2 this98 is /sed to invo)e a constr/ctor o4 the same class
2'8 ,o; s/+er98 /sed ;ith constr/ctorsM
5ns 2 s/+er98 is /sed to invo)e a s/+er class constr/ctor
2%8 Which o4 the 4ollo;ing statements correctl: descri7es an inter4aceM
a8ItLs a concrete class
78ItLs a s/+erclass
c8ItLs a t:+e o4 a7stract class
5ns2 c
2-8 5n inter4ace contains ]] methods
a81onAa7stract
78Im+lemented
c8/nim+lemented
5ns2c
1
Concrete Classes4 abstract classes & (nterfaces
6! What is an object ?
5n ob4ect is a software entity( unit ) that combines a set of data with a set of operations to manipulate that data.
In 6, &asic and %ascal etc. lan"ua"es we can directly manipulate data from anywhere of the
pro"ram. 6han"in" of data by one part of the pro"ram, affects whole pro"ram and if any other part
desires to ha!e the old !alues, it can not "et.
5 class defines a type of object. That is, each ob4ect belon"s to some class and ob4ect is
also called as an instance.
The Ja!a pro"rammin" lan"ua"e is ob4ect,oriented, which means that classes, instances
and methods ma2es a basis for a pro"ram;s desi"n.
public class #emo <
public static !oid main()trin" ar"s= > ) <
#emo d9 ? new #emo( ) @
A
A
In the abo!e pro"ram, d6 is the ob4ect of class #emo.
7! What is a class ?
% class is bl"eprint for objects! $he class defines variables4 ethods and objects!
$he object anip"lates data thro"-h ethods! $hese ethods constit"tes a set of
operations!
6lasses are the fundamental units in an ob4ect,oriented pro"rammin". -e use a class to
create ob4ects( instances ). ach instance carries its own data. That is, data belon"in" to one
ob4ect, if chan"ed, does not affect the data belon"in" to other ob4ect.
The followin" is a simple structure of a class.
class *irst%ro"ram <
int count @
public !oid display( ) <
count B B @
A
A
The followin" table displays the difference between an instance and a class.
Class (nstance
2
Couse plan( blue print ) Couse
Rubber stamp )tamped ima"e
%hoto"raphic ne"ati!e %rinted photo
8! What is a ethod ?
% ethod is the basic "nit of f"nctionality contained in a class! (t contains the
e:ec"table body that can be applied to specific object of the class!
The functions and subroutines of a procedural lan"ua"e( li2e 6 ) are called as methods in an
ob4ect,oriented lan"ua"e. Di2e function, a method includes+
a name
parameters used to input some !alues( optional )
a return type that "i!es output to another part of the pro"ram( atleast !oid)
a body of executable code
The followin" code snippet declares a method whose output ( return type ) is a double !alue, the
sum of two numbers.
public double sum( double a, double b ) <
Return ( a B b ) @
A
&ecause methods belon" to classes, the abo!e method is to be placed in a class. Methods
are not simply called. They must be called with the help of an ob4ect. *or example+
&utton btn9 ? new &utton( ) @
&utton btn: ? new &utton( ) @
btn9.setDabel( . 0$ . ) @
btn:.setDabel( . 6ancel . ) @
In the abo!e code, btn9 and btn: are the ob4ects of &utton class. setDabel( ) method of
&utton class is called with ob4ects btn9 and btn:.
H! What is the difference between an instance variable and class variable ?
5n instance !ariable represents separate data for each instance( because of separate memory allocation ) and
a class !ariable represents a sin"le data shared by whole class( that is, by all instances).
5n instance !ariable represents data for which each instance has its own copy.
5 class !ariable belon"s to the class as a whole. 5ll instances access the same sin"le copy. That
is, a class !ariable is shared resource and a means of communication between all instances of a
class. class !ariables declared as static 2eyword.
public class #emo <
int x @ EE instance !ariable
static int y @ EE static !ariable
2
A
B! What is the difference between # instance ) ethod and a class ethod ?
%n instance ethod has a this instance reference and whereas a class ethod does
not!
5n instance method wor2s always with an instance of a class. 5n instance method should be
called with an instance. 5 class method can be called without an instance. 5 class method should
be declared with a static 2eyword.
*or example, )trin" class has both instance and class methods. len"th( ) method is an
instance method and !alue0f( ) is a class(declared with static 2eyword ) method.
)trin" str ? . )(Rao . @
int x ? str.len"th( ) @
int y ? . 9F . @
)trin" s9 ? )trin".!alue0f( y ) @
C! What is an abstract ethod ?
%n abstract ethod does not contain e:ec"table body!
5n abstract method declares method name, parameter types and return type and not
body( e!en empty braces constitutes a body, but an empty body). That is functionality is not written.
5n abstract method is declared with an abstract 2eyword and ends with a semicolon instead of a
method body.
5n abstract class allows us to desi"n a new class. 5 class with abstract methods should be
abstract. 1raphics class defined in java!awt pac2a"e contains se!eral abstract methods of which
few are "i!en below+
public abstract class Graphics extends 0b4ect +
public !oid abstract drawDine( int x9, int y9, int x:, int y: ) @
public !oid abstract drawRect( int x, int y, int width, int hei"ht ) @
A
D! What is an abstract class ?
5n abstract is a class desi"ned with implementations "aps for subclasses to fill in.
5n abstract class is an incomplete class. It "i!es s2eleton of methods for the subclasses to
implement( to "i!e body ). The abstract class should be declared with abstract 9eyword. The
subclass should implement all the abstract methods of an interface and e!en if one is omitted it
does not compile. 5n abstract class can contain 9. all abstract methods :. all concrete methods
H. a mixture of abstract and concrete methods.
2
1raphics class defined in java!awt pac2a"e contains se!eral abstract methods of which few
are "i!en below+
public abstract class Graphics extends 0b4ect +
public !oid abstract drawDine( int x9, int y9, int x:, int y: ) @
public !oid abstract drawRect( int x, int y, int width, int hei"ht ) @
A
E! What is an interface and how it differs fro an abstract class ?
%n interface is a special case of an abstract class where all ethods are abstract!
5ll the methods of an interface must be abstract. It is to the subclass to implement( to "i!e
functionality ) all the methods. The subclass should implement all the abstract methods of an
interface and e!en if one is omitted it does not compile. Interface "i!es a template to subclasses.
That is with interface methods, a new class can be de!eloped.
!en thou"h, basically Ja!a does not support multiple inheritance, it is possible throu"h
interfaces.
5n interface can lin2ed to another interface with e:tends 2eyword only and abstract classes
and concrete classes should be lined with ipleents 2eyword.
The followin" are some fra"ments of code that shows lin2in" of different classes with
interfaces+
interface 5 < A
interface & < A
abstract class 6 < A
public class # implements 5, & < A EE le"al and multiple inheritance supported
interface & extends 5 < A EE le"al, extends 2eyword is used here
public class # extends 6 implements 5, & < A EE le"al
&ifferences between an abstract class and interface>
%bstract class (nterface
9. 5bstract class may contain all concrete Interface should contain only abstract
methods or abstract methods or a mixture. methods.
:. The methods may ha!e any access specifier The access specifier must be public.
except pri!ate.
H. The !ariables can ha!e any access specifier The !ariables must be public, static and
except pri!ate. final.
I. Multiple inheritance is not possible. Multiple inheritance is possible.
J. Inheritance "oes with extends 2eyword. Inheritance "oes with implements
2eyword.
2
K. abstract 2eyword must be included in public and abstract, e!en if omitted, they
method declaration. are assumed by default.
The followin" is a typical example for an interface defined in java!awt!event pac2a"e+
public interface -indowDistener extends !entDistener <
public !oid window6losin"( -indow!ent e ) @
public !oid window6losed( -indow!ent e ) @
public !oid window0pened( -indow!ent e ) @
public !oid window5cti!ated( -indow!ent e ) @
public !oid window#eacti!ated( -indow!ent e ) @
public !oid windowIconified( -indow!ent e ) @
public !oid window#eiconified( -indow!ent e ) @
A
(nheritance4 )ethod overloadin- and overridin-
F! What is inheritance ?
(nheritance is an OO.S concept where a s"bclass can a9e "se of s"perclass
ethods and variables as if they belon- to itself!
Inheritance is powerful mechanism for reusin" the code. Inheritance pro!ides a chain in
which a class inherits not only from its immediate superclass, but also from any superclass upwards
to the 0b4ect class.
*or example, &utton is a subclass of abstract superclass 6omponent.
public class &utton extends 6omponent < A
The methods li2e set6olor( ) and set*ont( ) of 6omponent class can be used by
&utton class.
The followin" are some fra"ments of code that shows lin2in" of different classes with
interfaces for inheritance+
interface 5 < A
interface & < A
abstract class 6 < A
public class # implements 5, & < A EE le"al and multiple inheritance supported
2
interface & extends 5 < A EE le"al, extends 2eyword is used here
public class # extends 6 implements 5, & < A EE le"al
6G! What is a s"bclass ?
% s"bclass is a class defined as an e:tension or odification of another class!
In Ja!a, e!ery class is a subclass of another( an exception is 0b4ect class, because it the
root class). If a class omits the 2eyword extends, it is implicitly a subclass of class 0b4ect. 5
subclass can modify the beha!ior of superclass by substitutin" some of its method definitions with
its own. 5 subclass is lin2ed with superclass with extends 2eyword( and for interfaces it is
implements).
class 5 < A
class & < A
class 6 extends 5, & < A EE ille"al as multiple inheritance is not
EE possible with concrete classes
class & extends 5 < A
class 6 extends & < A
*or class 6, & class is called immediate( or direct ) superclass and 5 class is indirect
superclass.
Aote> Lou can include this answer also in the notes of inheritance 8uestion.
66! What is ethod overloadin- ?
%n overloaded ethod is ore than one ethod> it is two or ore separate ethods
"sin- the sae ethod nae# of co"rse4 with different paraeters )!
Methods are defined in classes. Methods are distin"uished by the compiler by their method
si"natures. 5 method si"nature includes method name, number of parameters and their type. &ut in
procedural lan"ua"es li2e in 6, method o!erloadin" is not permitted.
Method o!erloadin" allows to "roup methods of same functionality under one name. 5lways
the name of the method should reflect its functionality( that is, what is it "oin" to "i!e us). In
method o!erloadin", compiler does not consider ret"rn type in differentiatin" the methods.
*or example println( ) method is o!erloaded 9F times in .rintStrea class of java!io
pac2a"e.
public class %rint)tream extends *ilter0utput)tream <
public !oid println( char x ) < A
public !oid println( int x ) < A
public !oid println( )trin" str ) < A EE etc.
A
2
67! What is ethod overridin- ?
(f the ethod si-nat"res of a ethod in s"perclass and s"bclass are sae4 we say
s"perclass ethod is overridden in s"bclass! (n ethod overridin- the ret"rn type also
"st be sae of that of s"perclass!
The subclass method must ha!e the same name, parameter list and return type as the
superclass method. That is, by usin" the same method name of the superclass, the subclass "i!es
different output.
What is the difference between ethod overloadin- and ethod overrdin- ?
Overloadin- occ"rs in the sae class when two or ore ethods "se the sae nae!
Overridin- occ"rs in two different classes# s"perclass and s"bclass) when the sae ethod
nae is "sed by both of the!
&ifferences between Overloadin- and Overridin->
Overloadin- Overrdin-
0ccurs in the same class 0ccurs between two classes
2nown as superclass and subclass.
(o method hides another. )ubclass method hides(bloc2s)
superclass mehod
(o method replaces the other. )ubclass method replaces the
suerclasss method.
#ifferent method si"natures )ame method si"nataure.
May ha!e different return types )hould ha!e the same return type.
May ha!e different declared
exceptions
Must ha!e compatible declared
exceptions.
68! +:plain the followin- 9eywords> 6! s"per 7! final
6! s"per>
s"per 9eyword -ives e:plicit access to the constr"ctors4 ethods and variables of its
superclass.
The super 2eyword wor2s with inheritance. Inheritance "i!es implicit access to subclass to
call its superclass members. &ut implicit access is bloc2ed by method o!erridin" or by declarin" the
same instance !ariables in subclass what superclass is ha!in". Cere, super 2eyword is used. That
is s"per 9eyword "i!es explicit access to immediate superclass parts, e!en if access is bloc2ed.
@sa-e of s"per with variables>
In the followin" pro"ram, the instance !ariable x is bloc2ed by the subclass !ariable. Cere
s"per is used to print the superclass !ariable.
2
class 5 <
int x ? 9F @
A
public class & extends 5 <
in x ? :F @
public !oid display( ) <
)ystem.out.println( x ) @ EE prints :F
)ystem.out.println( s"per!: ) @ EE prints 9F
)ystem.out.println( x B super.x) @ EE prints HF
A
public static !oid main()trin" ar"s= > ) <
& b new &( ) @
b.display( ) @
A
A
@sa-e of s"per with ethods>
In the followin" pro"ram, the display method is bloc2ed by the subclass o!erridden method.
Cere s"per is used to call the superclass method.
class 5 <
public !oid display( ) <
)ystem.out.println( . Cello9 . ) @
A
A
public class & extends 5 <
public !oid display( ) <
)ystem.out.println( . Cello: . ) @
A
public !oid show( ) <
display( ) @ EE Cello: is printed
s"per!display# ) I EE Cello9 is printed
A
public static !oid main()trin" ar"s= > ) <
& b new &( ) @
b.show( )@
A
A
@sa-e of s"per with constr"ctors ? s"per# ) >
super 2eyword should be called in a different way with constructors, because constr"ctors
are not inherited b"t accessed. To access the superclass constructor from a subclass constructor
we use super( ). JVM distin"uishes which superclass consturctor is to be called by matchin" the
parameters we pass with super( ). *ollowin" is the example +
class 5 <
5( ) < )ystem.out.println( . #efault 5/ ) @
5( int x ) < )ystem.out.println( x ) @
A
class & extends 5 <
2
&( ) < )ystem.out.println( . #efault &/ ) @
&( int x ) <
s"per# 6G ) I EE calls superclass 5( int x ) constructor
)ystem.out.println( x ) @
A
public static !oid main()trin" ar"s= > ) <
& b ? new &( J ) @
A
A EE output is 9F and J
7! final >
final is a 2eyword in Ja!a which "enerically means, cannot be chan-ed once
created. 5ny final 2eyword when declared with !ariables, methods and classes specifically means+
a final !ariable cannot be reassi"ned once initiali7ed.
a final method cannot be o!erridden.
a final class cannot be subclassed.
6lasses are usually declared final for either performance or security reasons. final methods
wor2 li2e inline code of 6BB.
final with variables>
final !ariables wor2 li2e const of 6,lan"ua"e that can;t be altered in the whole pro"ram.
That is, final !ariables once created can;t be chan"ed and they must be used as it is by all the
pro"ram.
public static !oid main( )trin" ar"s= > ) <
int x ? 9F@
final int y ? :F @
x ? 9FF @ EE not an error as x is not final
y ? :FF @ EE error because y is final
A
final with ethods>
Generally, a superclass method can be o!erriden by the subclass if it wants a different
functionality. 0r, it can use the same method if it wants the same functionality( output ). If the
superclass desires that the subclass shoud not o!erride its method by the subclass, it declares the
method as final. That is mehods declared final can not be o!erridden( else it is a compilation
error ).
class 5 <
final !oid display( ) < )ystem.out.println( . )(Rao/ ) @ A
A
class & extends 5 <
!oid display( ) < )ystem.out.println( . )umathi / ) @ A EE raises an error
A EE as display( ) is declared as final in the superclass
2
final with classes>
If you want the class not be subclassed by any other class, declare it final. 6lasses declared
final can not be extended. That is, any class can use the methods of a final class by creatin" an
ob4ect of final class and call the methods with its ob4ect.
final class 5 < A
class & extends 5 < A EE error because class 5 is declared final
6H! What is "ltiple inheritance and how Java s"pports "ltiple inheritance ?
Inheritance is the mechanism by which one class can ma2e use of the properties of another class. %roperties
includes data( instance !ariables) and operations( methods ) that can manipulate the data. These two classes must be
lin2ed by e:tends 2eyword.
The class that is bein" inherited is called s"perclass or base class. The class that inherits is called
s"bclass or deri!ed class. The subclass should extend the superclass with e:tends 2eyword.
Inheritance is an 00%s concept where code re"sability is maximum. That is, subclass can ma2e use of the
superclass constructors, !ariables and methods as if they belon" to itself.
)"ltiple inheritance >
-hen a subclass extends more than one class it is called multiple inheritance. That is, a subclass will ha!e
more than one superclass. $his is not allowed in Java.
class 5 < A
class & < A
class 6 extends 5, & < A
5 &
6
)"ltiple (nheritance # not allowed in Java )
In the abo!e pro"ram, class 6 extends class 5 and class &. This is "ltiple inheritance and is not allowed in
Java.
&ut, Java allows "ltiple inheritance thro"-h interfaces. That is, a class can be lin2ed to more than one
interface. Interface is a class with all abstract methods. 5bstract methods do not ha!e any functionality( body, includin"
empty body ).
interface 5 < A
interface & < A
class 6 ipleents 5, & < A
class 6 has "ot two interface superclasses. !en thou"h, it is multiple inheritance, it is allowed in Ja!a.
Basically4 Java does not s"pport "ltiple inheritance4 b"t s"pports thro"-h interfaces!
6B! &isc"ss the restrictions on a static ethod ? ( 0ctober, :FFF )
static is a 2eyword in Ja!a. This 2eyword can be used with methods and instance
!ariables. )tatic !ariable is called as class variable as it is shared by all the ob4ects of the class.
2
9. Generally to call a method from a main( ) method, we re8uire an ob4ect of the class. &ut a static
method can be called without an ob4ect. The followin" pro"ram illustrates +
public class )tatic#emo <
public static !oid display( ) <
)ystem.out.println ( ' Cello9 ' ) @
A
public static !oid main( )trin" ar"s= > ) <
display( ) @ EE because method is static, it can be called without an ob4ect
A
A
In the abo!e pro"ram, main and display are both static methods. That is callin" and called
methods are both static.
:. )tatic method can be called from another static method. 5 non,static method can be called from
a static method. &ut a static ethod cannot call a non?static ethod. The followin" pro"ram
illustrates +
public class )tatic#emo <
public !oid show( ) <
)ystem.out.println ( ' Cello9 ' ) @
A
public static !oid display( ) <
show( ) @ EE raises an error
A
public static !oid main( )trin" ar"s= > ) <
)tatic#emo sd ? new )tatic#emo( ) @
sd.display( ) @
A
A
H. )tatic methods do not ha!e . this . reference, because static method can be called without an
ob4ect.
I. )tatic methods cannot be called with . s"per . 2eyword in inheritance.
6C! 2ow interfaces are appropriate in Java ? ( 0ctober, :FFF )
&asically, Ja!a does not support multiple inheritance. &ut supports throu"h interfaces.
Interfaces "i!e template to create new classes. That is why, all the mehods of an interface are
public( for the reason they can be accessed by the classes of other pac2a"es also) and abstract
( that is, they do not contain body at all ). The followin" pro"ram illustrates +
interface class Jet%lane < EE abstract class
abstract int numn"ines( ) @ EE abstract method
A
class #6M implements Jet%lane <
int numn"ines( ) <
3
return H @
A
A
class #69F implements Jet%lane <
int numn"ines( ) <
return I @
A
A
class InterfaceJet%lane <
public static !oid main()trin" ar"s= > ) <
)ystem.out.println( '(o. of en"ines #6M contains ' B
new #6M( ).numn"ines( ) ) @
)ystem.out.println( '(o. of en"ines #69F contains ' B
new #69F( ).numn"ines( ) ) @
A
A
O"tp"t>
(o. of en"ines #6M contains H
(o. of en"ines #69F contains I
In the abo!e pro"ram, interface Jet%lane "i!es a template and dictates that e!ery plane
should ha!e en"ines. Interface always says what to do but not how to do. The class that
implements Jet%lane should o!erride this method and can put its own number of en"ines. In the
abo!e pro"ram, #6M 2eeps H en"ines and #69F 2eeps I en"ines. &ut the subclass cannot escape
of puttin" en"ines( as all the abstract methods of an interface must be "i!en body in the subclass ).
.ac9a-es and %ccess )odifiers
6D! What are pac9a-es and what for they are "sed ?
% pac9a-e is a collection of classes and interfaces# -enerally4 havin- a coon f"nctionality )!
.ac9a-es provide access restrictions to other classes!
5 pac2a"e "roups to"ether a set of classes and interfaces that are needed to wor2 as a whole. The java!io
pac2a"e contains classes and interfaces for mana"in" !arious 2inds input and output operations.
%ac2a"e defines boundary lines to "o!ern how classes and interfaces may interact (access) with each other.
%ac2a"es also red"ce the potential nae clashes between classes. 5 sin"le pac2a"e
cannot ha!e classes with the same name more than one. &ut the classes with the same name
can exist in different pac2a"es. That is, we can ma2e a &utton class of our own and 2eep in our
own pac2a"e. The &utton in our own pac2a"e does not clash with the &utton of java!io pac2a"e.
ach class and interface belon"s to some pac2a"e( li2e a file cannot exist without a
directory) . -hen we compile a class without mentionin" the pac2a"e name, it is placed in the
default( unnamed ) pac2a"e created by the JVM. %ac2a"es can be nested, if needed. That is
we can create sub,pac2a"es to pac2a"es. *or example, in java!awt!event e!ent is the
sub,pac2a"e to awt pac2a"e.
In declarin" a class, the order of stateents is very iportant as "i!en below, else compilation error. 5lways
pac9a-e nae "st be the first, if one exists.
pac2a"e animal @
import 4a!a.io.N @
3
class #o" < A
6E! &isc"ss the followin- access odifiers > 6! p"blic 7! protected 8! defa"lt
H! private
6! p"blic>
p"blic is a 2eyword in Ja!a and dictates the accessibility of a member. 5 method declared
p"blic can be accessed freely( without restrictions ) by any class belon"in" to any pac2a"e. p"blic 9eyword has "ot
maximum access of all access modifiers. 5 class must be declared as public or default.
7! protected>
protected is a 2eyword in Ja!a and dictates the accessibility of a member. 5 method,
constructor or !ariable declared protected, is accessible to all classes of the same pac2a"e and to s"bclasses of
other pac9a-es. That is, no restrictions to the methods belon"in" to the same pac2a"e.
8! defa"lt>
5ctually, there is no default access modifier@ the absence of a modifier is treated as default. 5 method or
!ariable, declared default( that is, no access modifier specified at all ), can be accessed by any class belon"in" to the
same pac2a"e. 6lasses belon"in" to other pac9a-es cannot access. That is why default access modifier is 2nown as
pac9a-e level access.
5 class can be either default or public.
Aote> defa"lt is 9eyword and is used with switch statements.
H! private >
private is a 2eyword in Ja!a and dictates the accessibility of a member. 5 method or a
!ariable declared pri!ate cannot be accessed by other classes. That is permission of access is "ranted to the ob4ects of
the same class.
5 class cannot be declared pri!ate.
%ccess ;evels for class and interface ebers
%ublic 2eyword 5ccessible to all the classes.
%rotected 2eyword 5ccessible to classes in the same pac2a"e or
subclasses of other pac2a"e.
(o 2eyword( default ) 5ccessible only to classes of the same
pac2a"e
%ri!ate 2eyword (ot accessible to any other class.
Java ;an-"a-e# or java!lan- pac9a-e )
6F! Why Java is preferred as a lan-"a-e of (nternet ?
or
What feat"res a9es Java to be preferred as a prod"ction lan-"a-e than that of CJC++ ?
-hen jd96!G ( Ja!a;s first !ersion ) was released to the world in 9OOJ (o!ember, it was described by Mr!James
Goslin", who heads the Ja!a de!elopment team at )un Microsystems as+
Java is siple4 object?oriented4 distrib"ted4 interpreted4 rob"st4 sec"re4 architect"re?ne"tral4 hi-h?
perforance4 "ltithreaded and dynaic pro-rain- lan-"a-e!
3
5t the same time, --- team was searchin" for a lan"ua"e that suits its Internet applications. 5ll the abo!e
features suited their re8uirements and they adopted Ja!a as the lan"ua"e of Internet.
The followin" points ma2e the abo!e hi"hly technical terms more clear >
6! Siple>
Ja!a has been described as . C+ + in"s / because of many of the most complex and
confusin" elements of 6B B were omitted, li2e pointers, memory mana"ement, operator o!erloadin", !irtual functions
etc. *indin" a pointer error in a lar"e pro"ram is a tou"hest 4ob.
Memory mana"ement occurs automatically in Ja!a. %ro"rammers need not ha!e to write clean,up statements
li2e free( ) or delete( ). Memory allocation and deallocation is implicit built in feature of Ja!a. Garba"e (unwanted
ob4ects, members etc.) collection is a continuous process that automatically ta2es place throu"h out the execution of the
pro"ram.
-oto is reser!ed word in Ja!a, but pro"rammer is not allowed to use it. -ith -oto, pro"rammer looses the
se8uence of flow of control, and it becomes !ery difficult to debu" a pro"ram. There are cases, when maintenance
pro4ects were abandoned, due to -oto, and written afresh.

-ith this simplicity, it is easy to learn Ja!a than learnin" 6 E 6B B.
Object?oriented >
0b4ect,oriented pro"rammin"(00%) is a powerful way of or"ani7in" and de!elopin" software. The components
of 00% called as objects, exist independently of the other. Ja!a exploits the ad!anta"es of 00%s concepts li2e
ncapsulation, Inheritance and %olymorphism.
The Ja!a lan"ua"e includes a set of class libraries( in the form of pac2a"es ) that pro!ide basic functionality to
write pro"rams in a simple way, li2e java!lan-( contains classes re8uired for runnin" e!ery Ja!a pro"ram), java!io( for
Input and 0utput operations ) and java!applet( for writin" applets ) etc.
Sec"re >
5nother essential to Ja!a;s success as an Internet lan"ua"e is that it is safe and sec"re. 5 Ja!a pro"ram that
executes from a -eb pa"e is called an applet. -hen an applet is downloaded by the browser into the system, alon"
text and ima"es, it may brin" vir"ses 1 the enemy of your software on the dis2.
*or this, Ja!a pro!ides security at different le!els. *irst, it eliminated pointers that can chan"e data on the dis2.
(ext, bytecode verifier chec2s anythin" suspicious ( li2e access permissions ) is "oin" on. 5n applet, by default,
cannot open, read or write files on the user system.
jd96!6 offers more ad!anced approach to security by allowin" applets to be di"itally si"ned for !erification
purposes. Jar files can be protected with public and pri!ate 2eys. 5lso you can o!erride the default )ecurityMana"er
class for extra safe"uards.
.latfor?independent >
Most computer software is de!eloped for a specific operatin" system. %latform independent means, the same
pro"ram( !class file ) can wor2 on different operatin" systems. The bytecode of !class file ma2es it platform
independent. That is, we compile only once and can run on any operatin" system any time.
$his feat"re is very iportant for an applet! $he applet downloaded and e:ec"ted on o"r syste is not
9nown on which syste it was copiled!

*ob"st >
Ja!a is a stron"ly typed lan"ua"e and it chec2s the pro"ram both at compile time and run time. *irst of all,
memory lea2s are pre!ented by implicit memory mana"ement. It;s exception handlin" mechanism eliminates common
3
problems li2e . di!ide by 7ero / or . file not found / etc. Pnassi"ned instance !ariables and unassi"ned elements of
arrays are "i!en default !alues instead of "i!in" 4un2 !alues.
)"ltithreaded >
Ja!a;s multithreadin" allows us to do many thin"s at a time. That is, downloadin" an applet, runnin" an
animation and editin" a source code 1 all can be done at once. Ja!a;s $hread class ma2es it easy and simple to write
a multithreaded pro"ram.
&istrib"ted >
Ja!a was desi"ned for the distributed en!ironment of the Internet because it handles T6%EI% protocols. Ja!a;s
RMI( Remote Method In!ocation) is unparalleled in distributed en!ironment of remote clientEser!er pro"rammin". -e
can access a resource by usin" a PRD.
&ynaic >
The Ja!a system supports executable code in dynamic lin2 libraries. 5 dynaic lin9 library is library of Ja!a
classes that can be accessed at run time. The load;ibrary# ) method is used to load a dynamic lin2 library.
7G! What are wrapper classes ?
or
2ow to convert priitive data types into Objects ?
Wrapper class objects wraps# covers ) priitive data types and a9es the to behave li9e objects! We
can "se these objects where priitive data types are re="ired as objects!
0ne circumstance where we re8uire primiti!e data types as ob4ects is when we want to store them in data
structures of Ja!a li2e Vector or )tac2.
+very priitive data type has -ot a correspondin- wrapper class with which we can con!ert it into an
ob4ect. *or example, int has "ot (nte-er class, do"ble has "ot &o"ble class and boolean has "ot Boolean class.
The followin" code con!erts int into (nte-er object.
int x ? 9F @
Inte"er i9 ? new Inte"er( x ) @ EE -e say ob4ect i6 wraps primiti!e data type int :.
The followin" code con!erts do"ble into &o"ble object.
double x ? 9F.J @
#ouble d9 ? new #ouble( x ) @ EE -e say ob4ect d6 wraps primiti!e data type
EE do"ble.
The wrapper classes also pro!ide methods to retrie!e primiti!e data type !alues from ob4ects.
int y ? i9.intValue( ) @ EE to "et bac2 int !alue from i6 ob4ect
double y ? d9.doubleValue( ) @ EE to "et bac2 do"ble !alue from d6 ob4ect
76! What is the difference between (nte-er and int ?
(nte-er is a class defined in java!lan- pac9a-e! int is priitive data type defined in Java ;an-"a-e itself!
(plicit conversion does not place in between (nte-er and int!
3
Ja!a lan"ua"e supports two types of data+ 9. Reference types :. %rimiti!e types.
5 reference type holds reference to a !alue. That is a reference !ariable points to( li2e pointers ) some location.
%rimiti!e types hold raw !alues without any ob4ect,oriented support.
5lthou"h, the Ja!a lan"ua"e is stron"ly ob4ect,oriented, it includes the primiti!e types because of their speed,
simplicity and compactness.
6omin" to the memory they occupy, both int and (nte-er occupies H:,bits( Ibytes ).
The data structures of Ja!a, li2e Vector, does not store primiti!e data types directly. They must be con!erted
into ob4ects and then stored. To con!ert int into an ob4ect class (nte-er helps.
Vector !ect ? new Vector( ) @
int x ? 9F @
!ect.addlement ( x ) @ EE raises a compilation error because int can;t be added
(ow, con!ert int into Inte"er ob4ect and then add as follows+
Inte"er i9 ? new Inte"er( x ) @
!ect.addlement ( i9 ) @
77! Write the r"les -overnin- type cast operation on priitive data types ?
There are M primiti!e data types in Ja!a 1 byte, short, int, lon", float, double, char and
boolean. 0ne type can be con!erted into another implicitly( by the system ) or explicitly( by the
pro"rammer ). The followin" rules apply.
9. The data types that occupies less memory can be assi"ned with to data types that occupies
more memory. The followin" castin" is performed imlicitly.
int x ? J @
double y ? x @
)ystem.out.println( y ) @ EE prints J.F
In the abo!e code, : ( int occupies I bytes ) can be assi"ned to d ( double occupies M bytes )
and this assi"nment is done implicitly( automatically ) without an extra code by the pro"rammer.
:. &ut the followin" code does not compile as explicit castin" is needed by the pro"rammer.
double d ? J.K @
int i ? d @
)ystem.out.println( i ) @ EE raises a compilation error
In the abo!e pro"ram, d ( of M bytes ) can be assi"ned to i ( of I bytes ). It needs explicit
castin". The abo!e code re,written as follows +
double d ? J.K @
int i ? ( int ) d @
)ystem.out.println( i ) @ EE prints J
3
This explicit castin" sometimes results in data truncation and precision of the !alue is lost.
H. 5n important point to note is boolean data type cannot be cast to any other data type. It is
incopatible with any other data type. 5lways con!ersion( either explicitly or implictly ) is
possible between compatible data types only. The followin" code raises a compilation error +
boolean b ? true @
int x ? b @
78! What is object castin- and e:plain itKs r"les ?
or
Can we cast in between objects ?
Truly spea2in", we can not cast in between ob4ects e!en thou"h all ob4ects in Ja!a ta2e H:,bits of memory. &ut,
it is possible to cast in between a subclass ob4ect and superclass ob4ect.
0b4ect castin" is possible in between the classes in!ol!ed in inheritance only.
class *lower < A
class Rose < A EE obser!e there is no e:tends 2eyword here
*lower f ? new *lower( ) @
Rose r ? new Rose( ) @
The followin" statements ca"ses copilation error because ob4ects a and b are not connected at all to"ether.
f ? r @
r ? f @
&ut the followin" code does not ca"se copilation error as class *lower and 6lass Rose are in!ol!ed in
inheritance. Rules of castin"+
9. a subclass ob4ect can be assi"ned to a superclass ob4ect( implicit ob4ect con!ersion ta2es place ).
:. 5 superclass ob4ect cannot be assi"ned to a subclass ob4ect and it needs explicit ob4ect castin".
class *lower < A
class Rose e:tends *lower < A EE obser!e e:tends 9eyword here
*lower f ? new *lower( ) @
Rose r ? new Rose( ) @
f < r I EE it is le"al, as per rule 9.
r < f I EE it is ille"al, as per rule :
r < # *ose ) f I EE now le"al, as explicit casin" is done
7H! What are different variables4 Java lan-"a-e s"poorts ?
or
&ifferentiate between local4 instance and class variables ?
Ja!a lan"ua"e supports three types of !ariables+ class !ariables, instance !ariables and local !ariables.
(nstance variables are those which maintain a separate copy of data when lin2ed to
ob4ects( maintains this reference ). That is, instance !ariables maintain different memory locations.
Class variable is that which can be accessed by all ob4ects( this reference does not exists) of the class. 6lass
!ariable does not maintain different memory locations when lin2ed to ob4ects. The only one memory location, occupied
by the class !ariable, is accessed by the whole class. That is, if one part of the pro"ram chan"es the !alue, all other
parts "et affected. If any part wants old !alue, it cannot "et. 6lass !ariable should be declared static. 5 class !ariable
can be accessed without the help of an ob4ect.
5 local variable is that whose access is limited within the method in which it is declared.
The followin" pro"ram explains +
3
public class Variable#emo <
int x ? 9F @ EE instance !ariable and should be accessed with an ob4ect only
static int y ? :F @ EE class !ariable and can be accessed without ob4ect
public !oid display( ) <
int 2 ? HF @ EE local !ariable and should not be called with ob4ect at all
)ystem.out.println( 2 ) @
A
A
7B! What do yo" ean by L CanKt a9e a static reference to a nonstatic variableM ?
-e cannot call an instance !ariable without an ob4ect( instance ). &ut we can call a static !ariable( also called
class !ariable) without the help of a ob4ect.
. 6an;t ma2e a static reference to a nonstatic !ariable/ is a common compilation error that is flashed when we
"enerally try to call an instance !ariable without an ob4ect. Cere, main is static and !ariable is nonstatic. #eclare the
!ariable static, and this error is not flashed.
I. The followin" code wor9s without a error as variable and ethod are nonstatic.
int x ? 9F @ EE nonstatic !ariable
!oid display( ) < EE nonstatic method
)ystem.out.println( x ) @
A
:. The followin" code does not wor9 as variable is nonstatic and ethod is static.
int x ? 9F @ EE nonstatic !ariable
static !oid display( ) < EE static method
)ystem.out.println( x ) @
A
7C! Write is an Object class ? &isc"ss soe iportant ethods of the class ?
Object is the root class for all Ja!a classes. If a class does not extend any class, implicitly, the class extends
class 0b4ect. 0b4ect class contains methods that dictate some common beha!ior for all Ja!a classes. 0b4ect class is
defined in java!lan- pac2a"e that is implicitly imported.
Soe iportant ethods of Object class>
finali5e# ) >
This method is called implicitly by the "arba"e collector before an ob4ect is "arba"e collected. In Ja!a, an
ob4ect is liable for "arba"e collection, if no references exist for it in the remainin" part of the pro"ram. It;s access
modifier is protected and return !oid. *ollowin" is the method si"nature specified in the 0b4ect class+
protected void finali5e# ) throws Throwable
toStrin-# ) >
This method con!erts any ob4ect into a strin" form. It;s return type is a )trin".
*ollowin" is the method si"nature specified in the 0b4ect class+
p"blic Strin- toStrin-# )
xample+
)trin"&uffer sb ? new )trin"&uffer( )@
)trin" str ? sb.to)trin"( ) @
3
wait# ) >
This method is used in thread synchroni7ation. )ynchroni7ation helps inte"rity of data that is shared in between
concurrently runnin" threads. Doc2in" of a shared resource is necessary to ha!e consistent( or durable) data. In
monitors, when a thread tries to access an ob4ect which already bein" accessed, wait( ) method is called and thread
waits until notify( ) is called. The followin" is the method si"nature as defined in 0b4ect class+
p"blic final void wait# ) throws Interruptedxception
This method cannot be o!erridden in its subclasses as it final. wait( ) method is o!erloaded.
notify# ) and notify%ll# ) >
In thread synchroni7ation, notify( ) or notify5ll( ) is called on the waitin" thread(s) to "et access to the
synchroni7ed code. The followin" is the method si"nature as defined in 0b4ect class+
public final !oid notify( )
public final !oid notify%ll( )
notify( ) is called on a sin"le waitin" thread, notifyin" the thread that the condition of the
synchroni7ed code to be accessed is chan"ed. notify5ll( ) is called when threads are many waitin"
in the 8ueue
.
The abo!e methods cannot be o!erridden in the subclasses as they are final.
7D! &ifferentiate between Bytecode and @nicode ?
Ja!a introduces two new words to the computer world 1 Bytecode and @nicode.
Bytecode>
-hen we compile a !java file, we "et a !class file. The !class file can run on any operatin" system irrespecti!e
of platform on which it was compiled. *or this reason, Ja!a is called platform independent. &ut the !e:e file of C
lan-"a-e is not platform independent. !e:e file contains binary code. Ja!a;s !class file contains bytecode. This
bytecode ma2es Ja!a cross platform. Ja!a compiler produces bytecodes. 5ny JVM, can run these bytecode and
produce output. &ytecode is a achine?independent interediate lan-"a-e 2nown to a Ja!a interpreter. Ja!a
interpreter parses bytecode into an output. That is why Ja!a is said, . write once4 r"n anywhere /.
Interpreter 0utput
6ompiler
Interpreter 0utput
Interpreter
0utput
@nicode>
5)6II(extended) character ran"e is F to :JJ. -e cannot add one more character, if we do want. 0nly n"lish
alphabets has "ot correspondin" 5)6II !alues. That is why we cannot write a 6 pro"ram in any other lan"ua"e than
n"lish.
Ja!a;s motto is internationali5ation. That is, it supports many world lan"ua"es, li2e Telu"u, $annada, Gree2,
Japanese etc. That is, there is a correspondin" 5)6II( Pnicode ) !alue in Ja!a for all these international lan"ua"es.
This is possible due to the si7e of character of : bytes. That is, the character can represent !alues ran"in" from F
to KJ,JHJ. This ran"e is called @nicode. -e can say %SC(( is a s"bset of @nicode. Ppto :JJ, Pnicode represents
3
.3ava )ile
(source
code)
.class )ile
(contians
bytecode
)
Windows A$
S"n Solaris
)acintosh
5)6II ran"e and afterwards it adds its own !alues for the alphabets of many world lan"ua"es. Pnicode is already
includes up to HI,9:M characters.
7E! What are jar files ? &isc"ss briefly how to create and e:tract files ?
J5R( Ja!a 5Rchi!e ) is Ja!a;s platform,independent file format that allows us to bundle different files into one.
The files, to "roup, may include !class files( li2e applets), !-if files( ima"e files), !a" files(sound files) etc. Ja!a
compresses all these files and 2eeps in a 4ar file, specified.
*or example+ jar cvf 2ello!jar &eo!class )y.hoto!-if Space)"sic!a"
In the abo!e statement, jar is Ja!a command( tool ) with which we can create a J%* file.
c stands for to create new 4ar file( updatin" of a 4ar file is also possible with other option)
v stands for to display the 4ar information on a standard output( monitor ).
f indicates that 4ar file name is included in the command line.
#emo.class, My%hoto."if and )paceMusic.au files are compressed( li2e win7ip or p27ip) and placed in the 4ar
file by name 2ello!jar. !jar should be "i!en extension for all archi!e files. The 4ar command also displays the ori"inal
si7e( in bytes) of each file and how much it is compressed and the percenta"e of compression etc.
jar tvf 2ello!jar EE t stands for list table of archi!e file
The abo!e command displays the contents( that is, all file names) present in Cello.4ar file.
jar :vf 2ello!jar EE : is for e:tractin" all files
The abo!e command extracts( un7ips ) all the included files of the 4ar file.
jar :vf 2ello!jar &eo!class
The abo!e command extracts #emo.class only from Cello.4ar file.
%dvanta-es of jar files > 9. -ith 4ar files, we can download many files with a sin"le re8uest.
:. &ecause files are compressed, the download time or transmission
time is drastically reduced
H. 5s the files are compressed, it ta2es less space on hard dis2
when stored.
7F! &isc"ss 6! instanceof 7! transient 8! volatile H! strictof B! native ?

6! instanceof > The instanceof 2eyword is a two,ar"ument operator that tests whether the type of its first ar"ument is
assi"nment compatible( that is, can be assi"ned or not ) with its second ar"ument.
instanceof is a 2eyword of Ja!a which can chec2 ( an ob4ect belon"s to a class or not ) both at a) compile,time
and b) run,time.
Copile N tie chec9in->
In the followin" pro"ram, instanceof chec2s whether an ob4ect belon"s to a class or not at compile time.
class $ < A
interface 5 < A
class & implements 5 < A
public class 6 extends & <
public static !oid main( )trin" ar"s= > ) <
6 c9 ? new 6( ) @
)ystem.out.println( c9 instanceof 6 ) @ EE prints true
3
EN if( c9 instanceof 5 )
)ystem.out.println( 'c9 is an instace of class 6' ) @
else
)ystem.out.println( 'c9 is not an instace of class 6' ) @
NE
)ystem.out.println( c9 instanceof & ) @ EE prints true, means & can be assi"ned
EE with c9 li2e & b9 ? c9
)ystem.out.println( c9 instanceof 5 ) @ EE prints true
EE )ystem.out.println( c9 instanceof $ ) @ EE compilation error ' Impossible to 6
EE to be instance of $ '
)ystem.out.println( c9 instanceof 0b4ect ) @ EE prints true as 0b4ect class is the
EE superclass of all classes
A
*"n N tie chec9in->
The primary use of instanceof is to chec2 at run time whether an ob4ect can be comparable ( or assi"nble, or
belon"s to ) to another ob4ect.
In the followin" pro"ram with one catch bloc2 we can catch many exceptions( loo2s stran"e and absurd ).
public class RunInstance#emo <
public static !oid main( )trin" ar"s= > ) <
int a ? J, b ? F, c, x= > ? < 9F, :F A @
try <
c ? a E b @
)ystem.out.println( x= 9F > ) @
A
catch( Runtimexception e ) <
if( e instanceof 5rithmeticxception )
)ystem.out.println( ' #onQt de!ide by 7ero sir ' B e ) @
else if ( e instanceof 5rrayIndex0ut0f&oundsxception )
)ystem.out.println( ' lement does not exist 'B e ) @
EN else if ( e instanceof Interruptedxception )
)ystem.out.println( 'lement does not exist'B e)@
NE EE raises an error as Runtimexception cannot be an instance of
EE Interruptedxception
A
A
A
In the abo!e pro"ram, the catch bloc2 is capable to catch both the exceptions( if one of the statements of try
bloc2 is 2ept in comments ). Cere instanceof chec2s at run,time.
7! transient >
transient is a Ja!a 2eyword used as modifier in distributed en!ironment in the applications
li2e J&, RMI, 60R&5 etc. -hen a !ariable is not to be transported throu"h remote ob4ects, we
declare the !ariable as transient. 5 transient !ariable is not persistent across networ2
public class #emo <
transient double x @
double y @
A
$
)ay, d6 is the ob4ect of #emo. If d9.x and d9.y are transported and sa!ed, d9.x is not sa!ed(
declared is transient) and d9.y is sa!ed( declared not transient).
8! volatile >
volatile is a Ja!a 2eyword used as modifier. If a !ariable is declared !olatile, it means that it
can be chan"ed unexpectedly by any part of the pro"ram. There may be a situation where many
threads of a Ja!a pro"ram may access a same !ariable. To a!oid inconsistency each thread may
maintain its own copy of the shared !ariable.
&ut the shared !ariable must reflect the actual state( or !alue ) to the whole class. -e
declare the !ariable as !olatile. If a !ariable is !olatile, compiler understands that it must use the
master copy always.
H! strictfp >
strictfp 2eyword "uarantees the precision of floatin",point !alues across different J#$
!ersions. strictfp maintains strictly the !alues of floatin" points. -hen a class is chan"ed by
usin" strictfp, all the remainin" methods of the whole class are modified.
public strictfp class Test <
EE code here
A
It is rarely used by pro"rammers as it sol!es !ery minimum problems.
B! native >
native 2eyword is used with methods as modifier. If we would li2e to write some other
lan"ua"e code in a Ja!a pro"ram, we use nati!e 2eyword. -hen a method in a Ja!a pro"ram is
nati!e, then the Ja!a pro"ram is not platform,independent. The nati!e code of the pro"ram, is
con!erted into a #DD that can be lin2ed dynamically at run,time.
8G! What is finali5e # ) ethod in Java ? ( 0ctober, :FFF )
-hen all references to an ob4ect are dropped, the ob4ect is no lon"er re8uired and becomes
eli"ible for "arba"e collection. &efore an ob4ect is "arba"e collected, the runtime system calls
finali5e# ) ethod to release system resources, if any, li2e operatin" system lin2s established by
the files opened by the pro"rammer or closin" soc2et connections systematically.
finali5e# ) ethod is defined in the 0b4ect class (as follows), so e!ery class can ma2e use of it.
protected void finali5e# ) throws java!lan-!$hrowableI
%i > to illustrate the use of finali7e( ) method.
public class *inali7e#emo <
static *inali7e#emo fd9 , fd: @
public !oid display( ) < )ystem.out.println( '0$5L ' ) @ A
$
protected !oid finali7e( ) throws Throwable <
if( fd9 R ? null ) <
)ystem.out.println( ' fd9 is not "arba"e collected and is ali!e ' ) @
fd9 ? null @
if (fd9 ? ? null )
)ystem.out.println( ' (ow fd9 is null and "ettin" "arba"e collected ' ) @
A
if ( fd: R ? null ) <
)ystem.out.println( 'fd: is not "arba"e collected and is ali!e ' ) @
fd: ? null@
if ( fd: ? ? null )
)ystem.out.println( ' (ow fd: is null and "ettin" "arba"e collected ' ) @
A
s"per!finali5e# ) I
A
public static !oid main( )trin" ar"s= > ) <
fd9 ? new *inali7e#emo( ) @ fd: ? new *inali7e#emo( ) @
fd9.display( ) @ fd:.display( ) @
Syste!r"n3inali5ersOn+:it# tr"e ) I
A
A
The statement s"per!finali5e# ) is called to clean up any resources that the ob4ect may ha!e
un2nowin"ly obtained throu"h methods inherited from the superclass. Lou can force ob4ect
finali7ation to occur by callin" )ystem;s followin" methods.
Syste!r"n3inali5ation# ) EE calls all ob4ects waitin" to be "arba"e collected
Syste!r"n3inali5ersOn+:it# tr"e ) JE finali7ers should run before the pro"ram exists
EE in J#$:.F, this method is deprecated
86! What is -c # ) ethod is Java ? or
Write abo"t -arba-e collection in Java ?
The Ja!a platform has a "arba"e collector runnin" at low priority that periodically
frees the memory used by ob4ects that are no lon"er needed. The Ja!a "arba"e collector is a ar9
sweep "arba"e collector. 5 mar2,sweep "arba"e collector scans dynamic memory areas for ob4ects
and mar2s those that are still referenced in the pro"ram. 5fter all possible paths to the ob4ects are
in!esti"ated, unmar2ed(unreferenced) ob4ects, 2nown as "arba"e, are collected and thereby
memory is freed.
The "arba"e collector re8uires time to complete its tas2. The amount of time !aries
dependin" on certain factors li2e, how bi" your heap is and how fast your processor is. Lou can
force the "arba"e collector to run when e!er you want by callin" -c# ) method of )ystem;s class+
Syste!-c# )
.erforance +nhanceents in 1arba-e Collection of J&, 7!G> The thread,local heap cache
eliminates the need of loc2in" for the ma4ority of heap collections. Memory allocation speed is
$
drastically increased. Garba"e collection pauses are shorter. The "arba"e collector no lon"er
excessi!ely consumes 6 stac2.
%rrays
87! &isc"ss 6! Creation of arrays 7! (nitiali5ation of arrays ?!
6! Creation of arrays>
5rrays are data structures that can store lar"e amount of information of the sae data type
"rouped to"ether and 2nown by a common name. ach member is called an element of the array.
5rrays are capable of storin" primiti!e data types as well as ob4ects. The elements of the array can
be accessed by its index !alue that starts from F. 0nce array is declared, its si7e cannot be altered
dynamically.
5rrays can be a) declared and later assi"ned or b) initiali7ed.
4 stu&ent can repeat the above para )or any 5uestion on arrays 6
int sub4ect= > ? new int= 9F > @ EE declaration of an array
)ystem.out.println( sub4ect= 9 > ) @ EE if not assi"ned, default F is assi"ned for int element
sub4ect= 9 > ? IJ @ EE assi-nin- a !alue to an element
)ystem.out.println( sub4ect= 9 > ) @ EE now, prints IJ
7! (nitiali5ation of arrays>
5rrays are data structures that can store lar"e amount of data of the sae type "rouped
to"ether and 2nown by a common name. ach member is called an element of the array. 5rrays
are capable of storin" primiti!e data types as well as ob4ects. The elements of the array are can be
accessed by its index !alue that starts from F. 0nce array is declared, its si7e cannot be altered
dynamically.
5rrays can be a) declared and assi"ned later or b) initiali7ed.
int sub4ect= > ? < :, J, S, M 9F A @ EE initiali7in" an array
)ystem.out.println( sub4ect = 9 > ) @ EE prints J
The si7e of the array should not be specified ( optional in 6 E 6B B ) at initiali7ation time. The
followin" raises a compilation error.
int sub4ect= J > ? < :, J, S, M 9F A @ EE si7e should not written, e!en if it is correct.
88! 2ow Java arrays of Java are different fro C J C + + ?
$
Siilarities>
5rrays are data structures that can store lar"e amount of data of the sae type
"rouped to"ether and 2nown by a common name. ach member is called an element of the array.
The elements of the array can be accessed by its index !alue that starts from F. 0nce array is
declared, its si7e cannot be altered dynamically.
&ifferences>
1 9. 5rrays are capable of storin" primiti!e data types as well as ob4ects.
( 6 stores primiti!e data types only )
:. 5rrays, in Ja!a, are ob4ects and can be passed by reference only( array elements can be passed by
!alue ).
H. 5rrays can not be manipulated by their base address( unli2e in 6 ).
2 I. In Ja!a, array si7e sho"ld not be entioned while initiali7in".
int sub4ect= B > ? < :, J, S, M 9F A @
The abo!e statement raises a compilation error as the si7e of the array J is specified
( e!en if it is correct also ). &ut in 6, it is optional.
J. In Ja!a, )trin" is an ob4ect and does not terminate with O G.. &ut in 6, it is an array of
characters terminatin" with O G.
K. In a two dimensional array, in 6, the second dimension cannot be chan"ed for each
row. &ut in Ja!a, the second dimension can be !aried, as per the need.
S. In Ja!a, array manipulation is easy due to predefined methods. *or example, array
can be copied easily into another, by Syste!arraycopy# ) method.
S t r i n - s
8H! &isc"ss briefly abo"t strin-s in Java! Write any fo"r ethods of Strin- class ?
or
2ow Java strin-s are different fro CJC+ + ?
or
Strin-s are i"table ? &isc"ss ?
5 se8uence of character data enclosed in double 8uotes is called a strin". )trin"s of Ja!a wor2 differently from
that of 6 and 6 B B. In 6, strin" is an array of characters with a terminatin" O G. &ut in Ja!a, strin" is an ob4ect of Strin-
class. That is manipulation of strin"s is 8uite different from 6 and in Ja!a, it is !ery easy due the rich methods of )trin"
class. *or example, we can concatenate strin"s with B operator.
Ja!a platform pro!ides two strin" classes to manipulate strin"s Strin-, for constant strin"s and Strin-B"ffer,
for strin"s that can chan"e.
)trin"s are immutable. That is, strin"s once created cannot be chan-ed at the sae eory location.
-hene!er a new !alue is assi"ned to a strin", a new memory location is created and the new !alue is stored in it and
the old location( with old !alue ) is "arba"e collected. It is definitely a o!erhead to the operatin" system. &ut this is
made to increase the performance and for the same reason )trin" class is declared as final.
The followin" the class si"nature of Strin- class defined in java!lan- pac2a"e+
$
public )inal class $trin# e,ten&s O7ject implements eriali<a7le2 Com+ara7le
To o!ercome the 0) o!erhead( due to immutable nature of strin"s), we can use )trin"&uffer
class.
)ome methods of )trin" class+
6! val"eOf# paraeter ) >
val"eOf# ) method is static and is o!erloaded many times in )trin" class. It;s 4ob is to
con!ert any priitive data type or object, passed as parameter, into a strin" form.
Its function similar to to)trin"( ) method of 0b4ect class. &ut to)trin"( ) method con!erts
only objects into strin" form.
+:aple6> convertin- a data type into strin->
int x ? 9F @
)trin" str ? )trin".val"eOf# : ) @
)ystem.out.println( str ) @ EE prints 9F
)ystem.out.println( str N str) @ EE raises compilation error as arithmetic
EE manipulations are not possible with ob4ects
+:aple7> convertin- an object into strin->
)trin"&uffer sb ? new )trin"&uffer( . )(Rao . ) @
sb.trim( ) @
The abo!e statement raises a compilation error as tri is not a method of )trin"&uffer class, but
is a method of )trin" class. )o, we must apply trim method to )trin"&uffer ob4ect after con!ertin" it
into strin".
)trin" str ? )trin".val"eOf# sb ) @
str.trim( ) @
7! len-th# ) >
len-th# ) is an instance method in )trin" class which returns an int !alue. It must be called
with an instance of )trin" class and returns the number of characters present in the strin" instance.
xample+
)trin" str9 ? . )(Rao . @
)trin" str: ? new )trin"( . *aculty . ) @
EE -e can create strin"s in either way.
)ystem.out.println( str9.len"th( ) ) @ EE prints J
)ystem.out.println( str:.len"th( ) ) @ EE prints S
8! e="als# ) >
$
e="als# ) method is inherited from 0b4ect class and is o!erridden in )trin" class. It returns a
boolean !alue of true if the strin"s are same or false, if the strin"s are different. In the comparison,
case( upper or lower) of the letters is considered.
xample+
)trin" str9 ? . )(Rao . @
)trin" str: ? . snrao . @
)ystem.out.println( str9.e8uals( str: ) ) @
The abo!e println statement prints false because case of letters is different. This can
o!ercome with e="als(-noreCase# ) method which does not consider case of the letters into
account in comparison. The followin" statement illustrates+
)ystem.out.println( str9.e8ualsI"nore6ase( str: ) ) @ EE prints tr"e
H! to;owerCase# ) and to@pperCase# ) >
to;owerCase# ) is an instance method and con!erts all uppercase letters of the strin"
into lowercase. to@pperCase# ) does in the re!erse way.
)trin" str9 ? . )(Rao . @
)trin" str: ? . )r.*aculty . @
)ystem.out.println( str9.toDower6ase( ) ) @ EE prints snrao
)ystem.out.println( str:.toPpper6ase( ) ) @ EE prints S*!3%C@;$P
8B! +:pain Strin- class in Java! 1ive s"itable e:aples for creatin- objects of
Strin- class ?
5 se8uence of character data enclosed in double 8uotes is called a strin". )trin"s of Ja!a wor2 differently from
that of 6 and 6 B B. In 6, strin" is an array of characters with a terminatin" O G. &ut in Ja!a, strin" is an ob4ect of Strin-
class. That is manipulation of strin"s is 8uite different from 6 and in Ja!a, it is !ery easy due the rich methods of )trin"
class. *or example, we can concatenate strin"s with B operator.
)trin"s are immutable. That is, strin"s once created cannot be chan-ed at the sae eory location.
-hene!er a new !alue is assi"ned to a strin", a new memory location is created and the new !alue is stored in it and
the old location( with old !alue ) is "arba"e collected. It is definitely a o!erhead to the operatin" system. &ut this is
made to increase the performance and for the same reason )trin" class is declared as final.
The followin" the class si"nature of Strin- class defined in java!lan- pac2a"e+
public )inal class $trin# e,ten&s O7ject implements eriali<a7le2 Com+ara7le
)trin"s are immutable. That is, strin"s once created cannot be chan-ed at the sae eory location.
-hene!er a new !alue is assi"ned to a strin", a new memory location is created and the new !alue is stored in it and
the old location( with old !alue ) is "arba"e collected.
The followin" the class si"nature of Strin- class defined in java!lan- pac2a"e+
public )inal class $trin# e,ten&s O7ject implements eriali<a7le2 Com+ara7le
$
)ome important methods of )trin" class are +
val"eOf# ) > 6on!erts all primiti!e data types and ob4ects into strin" form.
e="als(-noreCase# ) > 6ompares two strin"s while i"norin" their case.
tri# ) > Remo!es all prefix and suffix white spaces of the strin".
to@pperCase# ) and to;owerCase# ) > 6han"es the case of the letters of the strin".
)trin" ob4ects can be created in different ways.
9. )trin" str ? new )trin"( . hello . ) @
)ystem.out.println( str ) @
:. )trin" str ? . hello . @
)ystem.out.println( str ) @
H. char b= > ? < Q h Q, Q e Q, Q l Q, Q l Q, Q o Q A @
)trin" str ? new )trin"( b ) @
)ystem.out.println( str ) @
I. char b= > ? < Q h Q, Q e Q, Q l Q, Q l Q, Q o Q A @
)trin" str ? new )trin"( b, 9,H ) @ EE copies H characters startin" from index number 9
)ystem.out.println( str ) @ EE prints ell
J. char b= > ? < Q h Q, Q e Q, Q l Q, Q l Q, Q o Q A @
)trin" str ? )trin".copyValue0f( b ) @
)ystem.out.println( str ) @
K. )trin"&uffer sb ? new )trin"&uffer( ' hello ' ) @
)trin" str ? sb.to)trin"( ) @
)ystem.out.println( str ) @
1. What &oes a well7written .. pro#ram loo8 li8e*4&onate& in July2 '99:6
5 ;ellA;ritten OO +rogram e*hi7its rec/rring str/ct/res that +romote a7straction, 4le*i7ilit:, mod/larit: and
elegance.
7! Can yo" have virt"al f"nctions in Java? #donated in J"ly 7GGB)

Fes, all 4/nctions in &ava are virt/al 7: de4a/lt. !his is act/all: a +se/do tric) @/estion 7eca/se the ;ord
Evirt/alE is not +art o4 the naming convention in &ava 9 as it is in CXX, CAshar+ and DB.1E!8, so this ;o/ld 7e
a 4oreign conce+t 4or someone ;ho has onl: coded in &ava. Dirt/al 4/nctions or virt/al methods are 4/nctions
or methods that ;ill 7e rede4ined in derived classes.
8! What is ore advisable to create a thread4 by ipleentin- a *"nnable interface or by
e:tendin- $hread class?#donated in J"ne 7GGB)

$
trategicall: s+ea)ing, threads created 7: im+lementing V/nna7le inter4ace are more advisa7le. I4 :o/ create
a thread 7: e*tending a thread class, :o/ cannot e*tend an: other class. I4 :o/ create a thread 7:
im+lementing V/nna7le inter4ace, :o/ save a s+ace 4or :o/r class to e*tend another class no; or in 4/t/re.

H! %n application needs to load a library before it starts to r"n4 how to code?

One o+tion is to /se a static 7loc) to load a li7rar: 7e4ore an:thing is called. (or e*am+le,
class !est Q
static Q
:stem.loadHi7rar:9E+athAtoAli7rar:A4ileE8O
P
....
P
When :o/ call ne; !est 98, the static 7loc) ;ill 7e called 4irst 7e4ore an: initiali<ation ha++ens. 1ote that the
static 7loc) +osition ma: matter
seriali<a7le.
W+BS($+ N G7
htt+2??;;;.roseindia.net?intervie;@/estions?inde*.shtml
1. What is ollection API*
Answer: !he Collection 5PI is a set o4 classes and inter4aces that s/++ort o+eration on collections o4 o7jects.
!hese classes and inter4aces are more 4le*i7le, more +o;er4/l, and more reg/lar than the vectors, arra:s, and
hashta7les i4 e44ectivel: re+laces.
E,ample o) classes: 7ash5et, 7ash2ap, Arra%8ist, 8in&ed8ist, 4ree5et and 4ree2ap.
E,ample o) inter)aces: Collection, 5et, 8ist and 2ap
Is Iterator a lass or Inter)ace* What is its use*
Answer: Iterator is an inter4ace ;hich is /sed to ste+ thro/gh the elements o4 a Collection.
;. <ow to &e)ine an Abstract class*
Answer: 5 class containing a7stract method is called 57stract class. 5n 57stract class canLt 7e instantiated.
E*am+le o4 57stract class2
a7stract class test57stractClass Q
+rotected tring m:tringO
+/7lic tring getM:tring98 Q
ret/rn m:tringO
P
+/7lic a7stract string an:57stract(/nction98O
$
P
+. <ow to &e)ine an Inter)ace*
Answer: In &ava Inter4ace de4ines the methods 7/t does not im+lement them. Inter4ace can incl/de constants.
5 class that im+lements the inter4aces is 7o/nd to im+lement all the methods de4ined in Inter4ace.
Ema+le o4 Inter4ace2
+/7lic inter4ace sam+leInter4ace Q
+/7lic void 4/nctionOne98O
+/7lic long CO1!51!]O1E T 1###O
P
:. E,plain the user &e)ine& E,ceptions*
Answer: User de4ined E*ce+tions are the se+arate E*ce+tion classes de4ined 7: the /ser 4or s+eci4ic
+/r+osed. 5n /ser de4ined can created 7: sim+l: s/7Aclassing it to the E*ce+tion class. !his allo;s c/stom
e*ce+tions to 7e generated 9/sing thro;8 and ca/ght in the same ;a: as normal e*ce+tions.
E*am+le2
class m:C/stomE*ce+tion e*tends E*ce+tion Q
?? !he class sim+l: has to e*ist to 7e an e*ce+tion
P
6. E,plain the new !eatures o) JDB '.9 ore API*
Answer: !he &6BC 2.# 5PI incl/des the com+lete &6BC 5PI, ;hich incl/des 7oth core and O+tional
Pac)age 5PI, and +rovides ind/ctrialAstrength data7ase com+/ting ca+a7ilities.
1e; (eat/res in &6BC 2.# Core 5PI2
crolla7le res/lt setsA /sing ne; methods in the Ves/ltet inter4ace allo;s +rogrammaticall: move the
to +artic/lar ro; or to a +osition relative to its c/rrent +osition
&6BC 2.# Core 5PI +rovides the Batch U+dates 4/nctionalit: to the java a++lications.
&ava a++lications can no; /se the Ves/ltet./+date[[[ methods.
1e; data t:+es A inter4aces ma++ing the .H3 data t:+es
C/stom ma++ing o4 /serAde4ined t:+es 9U!6s8
Miscellaneo/s 4eat/res, incl/ding +er4ormance hints, the /se o4 character streams, 4/ll +recision 4or
java.math.Big6ecimal val/es, additional sec/rit:, and s/++ort 4or time <ones in date, time, and
timestam+ val/es.
1. E,plain #arba#e collection*
Answer: 3ar7age collection is one o4 the most im+ortant 4eat/re o4 &ava. 3ar7age collection is also called
a/tomatic memor: management as &DM a/tomaticall: removes the /n/sed varia7les?o7jects 9val/e is n/ll8
4rom the memor:. User +rogram cannLt directl: 4ree the o7ject 4rom memor:, instead it is the jo7 o4 the
gar7age collector to a/tomaticall: 4ree the o7jects that are no longer re4erenced 7: a +rogram. Ever: class
inherits )inali=e46 method 4rom 3ava.lan#..b3ect, the 4inali<e98 method is called 7: gar7age collector ;hen it
determines no more re4erences to the o7ject e*ists. In &ava, it is good idea to e*+licitl: assign null into a
$
varia7le ;hen no more in /se. I &ava on calling $ystem.#c46 and >untime.#c462 &DM tries to rec:cle the
/n/sed o7jects, 7/t there is no g/arantee ;hen all the o7jects ;ill gar7age collected.
?. <ow you can )orce the #arba#e collection*
Answer: 3ar7age collection a/tomatic +rocess and canLt 7e 4orced.
-. What is ..P$*
Answer: OOP is the common a77reviation 4or O7jectAOriented Programming
19. Describe the principles o) ..P$.
Answer: !here are three main +rinci+als o4 oo+s ;hich are called Pol:mor+hism, Inheritance and
Enca+s/lation
11. E,plain the Encapsulation principle.
Answer: Enca+s/lation is a +rocess o4 7inding or ;ra++ing the data and the codes that o+erates on the data
into a single entit:. !his )ee+s the data sa4e 4rom o/tside inter4ace and mis/se. One ;a: to thin) a7o/t
enca+s/lation is as a +rotective ;ra++er that +revents code and data 4rom 7eing ar7itraril: accessed 7: other
code de4ined o/tside the ;ra++er.
1'. E,plain the Inheritance principle.
Answer: Inheritance is the process by which one ob3ect ac5uires the properties o) another ob3ect
1;. E,plain the Polymorphism principle.
Answer: !he meaning o4 Pol:mor+hism is something li)e one name man: 4orms. Pol:mor+hism ena7les one
entit: to 7e /sed as as general categor: 4or di44erent t:+es o4 actions. !he s+eci4ic action is determined 7: the
e*act nat/re o4 the sit/ation. !he conce+t o4 +ol:mor+hism can 7e e*+lained as Eone inter4ace, m/lti+le
methodsE.
1+. E,plain the &i))erent )orms o) Polymorphism.
Answer: (rom a +ractical +rogramming vie;+oint, +ol:mor+hism e*ists in three distinct 4orms in &ava2
Method overloading
Method overriding thro/gh inheritance
Method overriding thro/gh the &ava inter4ace
1:. What are Access $peci)iers available in Java*
Answer2 5ccess s+eci4iers are )e:;ords that determines the t:+e o4 access to the mem7er o4 a class. !hese
are2
P/7lic
Protected
5
Private
6e4a/lts
16.Describe the wrapper classes in Java.
Answer: Wra++er class is ;ra++er aro/nd a +rimitive data t:+e. 5n instance o4 a ;ra++er class contains, or
;ra+s, a +rimitive val/e o4 the corres+onding t:+e.
(ollo;ing ta7le lists the +rimitive t:+es and the corres+onding ;ra++er classes2
.riitive
Wrapper
Boolean java.lang.Boolean
Byte java.lang.B:te
har java.lang.Character
Double java.lang.6o/7le
!loat java.lang.(loat
Int java.lang.Integer
"on# java.lang.Hong
$hort java.lang.hort
%oi& java.lang.Doid
11. >ea& the )ollowin# pro#ram:
+/7lic class test Q
+/7lic static void main9tring RS args8 Q
int * T 3O
int : T 1O
i4 9* T :8
:stem.o/t.+rintln9E1ot e@/alE8O
else
:stem.o/t.+rintln9EE@/alE8O
P
P
What is the res/ltM
5. !he o/t+/t is BE@/alC
B. !he o/t+/t in B1ot E@/alC
C. 5n error at E i4 9* T :8E ca/ses com+ilation to 4all.
6. !he +rogram e*ec/tes 7/t no o/t+/t is sho; on console.
Answer:
1?. an a private metho& o) a superclass be &eclare& within a subclass*
Answer: /re. 5 +rivate 4ield or method or inner class 7elongs to its declared class and hides 4rom its
s/7classes. !here is no ;a: 4or +rivate st/44 to have a r/ntime overloading or overriding 9+ol:mor+hism8
4eat/res.
5
11. Why Java &oes not support multiple inheritence*
Answer: &ava 6OE s/++ort m/lti+le inheritance via inter4ace im+lementation
1?. What is the &i))erence between )inal2 )inally an& )inali=e*
Answer: o 4inal A declare constant
o 4inall: A handles e*ce+tion
o 4inali<e A hel+s in gar7age collection
1-. where an& how can you use a private constructor.
Answer: Private constr/ctor can 7e /sed i4 :o/ do not ;ant an: other class to instanstiate the o7ject , the
instantiation is done 4rom a static +/7lic method, this method is /sed ;hen dealing ;ith the 4actor: method
+attern ;hen the designer ;ants onl: one controller 94ator: method 8 to create the o7ject.
'9. In $ystem.out.println462what is $ystem2out an& println2pls e,plain*
Answer: System is a +rede4ined 4inal class,out is a Printtream o7ject and println is a 7/iltAin overloaded
method in the out o7ject.
'1What is meant by @Abstract Inter)ace@*
Answer: (irst, an inter4ace is a7stract. !hat means :o/ cannot have an: im+lementation in an inter4ace. 5ll
the methods declared in an inter4ace are a7stract methods or signat/res o4 the methods.
''an you ma8e an instance o) an abstract class* !or e,ample 7 3ava.util.alen&er is an abstract class
with a metho& #etInstance46 which returns an instance o) the alen&er class.
Answer: 1oY Fo/ cannot ma)e an instance o4 an a7stract class. 5n a7stract class has to 7e s/7Aclassed. I4 :o/
have an a7stract class and :o/ ;ant to /se a method ;hich has 7een im+lemented, :o/ ma: need to s/7class
that a7stract class, instantiate :o/r s/7class and then call that method.
';. What is the output o) ,Ay* a:b B pC5 when ,B12yB'2pB;25B+*
Answer: When this )ind o4 @/estion has 7een as)ed, 4ind the +ro7lems :o/ thin) is necessar: to as) 7e4ore
:o/ give an ans;er. 5s) i4 varia7les a and 7 have 7een declared or initiali<ed. I4 the ans;er is :es. Fo/ can
sa: that the s:nta* is ;rong. I4 the statement is re;ritten as2 *=:M a297T+Z@8O the ret/rn val/e ;o/ld 7e
varia7le a 7eca/se the * is 1 and less than : T 2O the * = : statement ret/rn tr/e and varia7le a is ret/rned.
'+. What is the &i))erence between $win# an& AWD components*
Answer: 5W! com+onents are heav:A;eight, ;hereas ;ing com+onents are light;eight. ,eav: ;eight
com+onents de+end on the local ;indo;ing tool)it. (or e*am+le, java.a;t.B/tton is a heav: ;eight
com+onent, ;hen it is r/nning on the &ava +lat4orm 4or Uni* +lat4orm, it ma+s to a real Moti4 7/tton.
':. Why Java &oes not support pointers*
Answer: Beca/se +ointers are /nsa4e. &ava /ses re4erence t:+es to hide +ointers and +rogrammers 4eel easier
to deal ;ith re4erence t:+es ;itho/t +ointers. !his is ;h: &ava and C^ shine.
'6. Parsers* D./ vs $A0 parser
5
Answer: +arsers are 4/ndamental *ml com+onents, a 7ridge 7et;een [MH doc/ments and a++lications that
+rocess that [MH. !he +arser is res+onsi7le 4or handling *ml s:nta*, chec)ing the contents o4 the doc/ment
against constraints esta7lished in a 6!6 or chema.
'1. <ow many metho&s in the $eriali=able inter)ace*
Answer: !here is no method in the eriali<a7le inter4ace. !he eriali<a7le inter4ace acts as a mar)er, telling
the o7ject seriali<ation tools that :o/r class is seriali<a7le.
'?. <ow many metho&s in the E,ternali=able inter)ace*
Answer: !here are t;o methods in the E*ternali<a7le inter4ace. Fo/ have to im+lement these t;o methods in
order to ma)e :o/r class e*ternali<a7le. !hese t;o methods are readE*ternal98 and ;riteE*ternal98.
'-. What is the &i))erence between $eriali=alble an& E,ternali=able inter)ace*
Answer: When :o/ /se eriali<a7le inter4ace, :o/r class is seriali<ed a/tomaticall: 7: de4a/lt. B/t :o/ can
override ;riteO7ject98 and readO7ject98 t;o methods to control more com+le* o7ject seraili<ation +rocess.
When :o/ /se E*ternali<a7le inter4ace, :o/ have a com+lete control over :o/r classLs seriali<ation +rocess.
;9. What is a transient variable*
Answer: A transient varia7le is a varia7le that ma: not 7e seriali<ed. I4 :o/ donLt ;ant some 4ield to 7e
seriali<ed, :o/ can mar) that 4ield transient or static.
;1. Which containers use a bor&er layout as their &e)ault layout*
Answer: !he Windo;, (rame and 6ialog classes /se a 7order la:o/t as their de4a/lt la:o/t.
;'. What are synchroni=e& metho&s an& synchroni=e& statements*
Answer: :nchroni<ed methods are methods that are /sed to control access to an o7ject. 5 thread onl:
e*ec/tes a s:nchroni<ed method a4ter it has ac@/ired the loc) 4or the methodLs o7ject or class. :nchroni<ed
statements are similar to s:nchroni<ed methods. 5 s:nchroni<ed statement can onl: 7e e*ec/ted a4ter a thread
has ac@/ired the loc) 4or the o7ject or class re4erenced in the s:nchroni<ed statement.
;;. What are three ways in which a threa& can enter the waitin# state*
Answer: 5 thread can enter the ;aiting state 7: invo)ing its slee+98 method, 7: 7loc)ing on I?O, 7:
/ns/ccess4/ll: attem+ting to ac@/ire an o7jectLs loc), or 7: invo)ing an o7jectLs ;ait98 method. It can also
enter the ;aiting state 7: invo)ing its 9de+recated8 s/s+end98 method.
;+. an a loc8 be ac5uire& on a class*
Answer: Fes, a loc) can 7e ac@/ired on a class. !his loc) is ac@/ired on the classLs Class o7ject
5
;:. WhatEs new with the stop462 suspen&46 an& resume46 metho&s in JDF 1.'*
Answer: !he sto+98, s/s+end98 and res/me98 methods have 7een de+recated in &6_ 1.2.
+1. What is the %ector class*
Answer: !he Dector class +rovides the ca+a7ilit: to im+lement a gro;a7le arra: o4 o7jects ;hat modi4iers
ma: 7e /sed ;ith an inner class that is a mem7er o4 an o/ter classM 5 9nonAlocal8 inner class ma: 7e declared
as +/7lic, +rotected, +rivate, static, 4inal, or a7stract.
+'. I) a metho& is &eclare& as protecte&2 where may the metho& be accesse&*
Answer: 5 +rotected method ma: onl: 7e accessed 7: classes or inter4aces o4 the same +ac)age or 7:
s/7classes o4 the class in ;hich it is declared.
+;. What is an Iterator inter)ace*
Answer: !he Iterator inter4ace is /sed to ste+ thro/gh the elements o4 a Collection.
++. <ow many bits are use& to represent Gnico&e2 A$II2 GD!7162 an& GD!7? characters*
Answer: Unicode re@/ires 1' 7its and 5CII re@/ire % 7its. 5ltho/gh the 5CII character set /ses onl: % 7its,
it is /s/all: re+resented as - 7its. U!(A- re+resents characters /sing -, 1', and 1- 7it +atterns. U!(A1' /ses
1'A7it and larger 7it +atterns.
+:. What is the &i))erence between yiel&in# an& sleepin#*
Answer: When a tas) invo)es its :ield98 method, it ret/rns to the read: state. When a tas) invo)es its slee+98
method, it ret/rns to the ;aiting state.
+?. Is si=eo) a 8eywor&*
Answer: !he si<eo4 o+erator is not a )e:;ord.
+-. What are wrappe& classes*
Answer: Wra++ed classes are classes that allo; +rimitive t:+es to 7e accessed as o7jects.
:9. Does #arba#e collection #uarantee that a pro#ram will not run out o) memory*
Answer: 1o, it doesnLt. It is +ossi7le 4or +rograms to /se /+ memor: reso/rces 4aster than the: are gar7age
collected. It is also +ossi7le 4or +rograms to create o7jects that are not s/7ject to gar7age collection
:1. What is the &i))erence between preemptive sche&ulin# an& time slicin#*
Answer: Under +reem+tive sched/ling, the highest +riorit: tas) e*ec/tes /ntil it enters the ;aiting or dead
states or a higher +riorit: tas) comes into e*istence. Under time slicing, a tas) e*ec/tes 4or a +rede4ined slice
o4 time and then reenters the +ool o4 read: tas)s. !he sched/ler then determines ;hich tas) sho/ld e*ec/te
ne*t, 7ased on +riorit: and other 4actors.
5
:'. Hame omponent subclasses that support paintin#.
Answer: !he Canvas, (rame, Panel, and 5++let classes s/++ort +ainting
:;. What is a native metho&*
Answer: 5 native method is a method that is im+lemented in a lang/age other than &ava
:+. <ow can you write a loop in&e)initely*
Answer: 4or9OO8AA4or loo+O ;hile9tr/e8AAal;a:s tr/e, etc.
::. an an anonymous class be &eclare& as implementin# an inter)ace an& e,ten&in# a class*
Answer: 5n anon:mo/s class ma: im+lement an inter4ace or e*tend a s/+erclass, 7/t ma: not 7e declared to
do 7oth.
:6. What is the purpose o) )inali=ation*
Answer: !he +/r+ose o4 4inali<ation is to give an /nreacha7le o7ject the o++ort/nit: to +er4orm an: clean/+
+rocessing 7e4ore the o7ject is gar7age
:1. Which class is the superclass )or every class*
Answer: O7ject.
:?. What is the &i))erence between the Boolean I operator an& the II operator*
Answer: I4 an e*+ression involving the Boolean W o+erator is eval/ated, 7oth o+erands are eval/ated. !hen
the W o+erator is a++lied to the o+erand. When an e*+ression involving the WW o+erator is eval/ated, the 4irst
o+erand is eval/ated. I4 the 4irst o+erand ret/rns a val/e o4 tr/e then the second o+erand is eval/ated. !he WW
o+erator is then a++lied to the 4irst and second o+erands. I4 the 4irst o+erand eval/ates to 4alse, the eval/ation
o4 the second o+erand is s)i++ed.
O+erator W has no chance to s)i+ 7oth sides eval/ation and WW o+erator does. I4 as)ed ;h:, give details as
a7ove.
:-. What is the Jre#orianalen&ar class*
Answer: !he 3regorianCalendar +rovides s/++ort 4or traditional Western calendars
69. What is the $impleDimeKone class*
Answer: !he im+le!ime`one class +rovides s/++ort 4or a 3regorian calendar.
61. Which ontainer metho& is use& to cause a container to be lai& out an& re&isplaye&*
Answer: validate98
6'. What is the Properties class*
5
Answer: !he +ro+erties class is a s/7class o4 ,ashta7le that can 7e read 4rom or ;ritten to a stream. It also
+rovides the ca+a7ilit: to s+eci4: a set o4 de4a/lt val/es to 7e /sed.
6;. What is the purpose o) the >untime class*
Answer: !he +/r+ose o4 the V/ntime class is to +rovide access to the &ava r/ntime s:stem.
6+. What is the purpose o) the $ystem class*
Answer:!he +/r+ose o4 the :stem class is to +rovide access to s:stem reso/rces.
6:. What is the purpose o) the )inally clause o) a try7catch7)inally statement*
Answer: !he 4inall: cla/se is /sed to +rovide the ca+a7ilit: to e*ec/te code no matter ;hether or not an
e*ce+tion is thro;n or ca/ght.
66. What is the "ocale class*
Answer: !he Hocale class is /sed to tailor +rogram o/t+/t to the conventions o4 a +artic/lar geogra+hic,
+olitical, or c/lt/ral region.
CD! What "st a class do to ipleent an interface?
Answer: It m/st +rovide all o4 the methods in the inter4ace and identi4: the inter4ace in its im+lements cla/se.
CE! What is an abstract ethod?
Answer: 5n a7stract method is a method ;hose im+lementation is de4erred to a s/7class. Or, a method that
has no im+lementation 9an inter4ace o4 a method8.
6-. What is a static metho&*

Answer: 5 static method is a method that 7elongs to the class rather than an: o7ject o4 the class and doesnLt
a++l: to an o7ject or even re@/ire that an: o7jects o4 the class have 7een instantiated.
DG! What is a protected ethod?
Answer: 5 +rotected method is a method that can 7e accessed 7: an: method in its +ac)age and inherited 7:
an: s/7class o4 its class.
D6! What is the difference between a static and a non?static inner class?
Answer: 5 nonAstatic inner class ma: have o7ject instances that are associated ;ith instances o4 the classLs
o/ter class. 5 static inner class does not have an: o7ject instances.
D7! What is an objectQs loc9 and which objectQs have loc9s?
Answer: 5n o7jectLs loc) is a mechanism that is /sed 7: m/lti+le threads to o7tain s:nchroni<ed access to
the o7ject. 5 thread ma: e*ec/te a s:nchroni<ed method o4 an o7ject onl: a4ter it has ac@/ired the o7jectLs
loc). 5ll o7jects and classes have loc)s. 5 classLs loc) is ac@/ired on the classLs Class o7ject
5
D8! When can an object reference be cast to an interface reference?
Answer: 5n o7ject re4erence 7e cast to an inter4ace re4erence ;hen the o7ject im+lements the re4erenced
inter4ace.
1+. What is the &i))erence between a Win&ow an& a !rame*
Answer: !he (rame class e*tends Windo; to de4ine a main a++lication ;indo; that can have a men/ 7ar.
1:.What &o heavy wei#ht components mean*
Answer: ,eav: ;eight com+onents li)e 57stract Windo; !ool)it 95W!8, de+end on the local ;indo;ing
tool)it. (or e*am+le, java.a;t.B/tton is a heav: ;eight com+onent, ;hen it is r/nning on the &ava +lat4orm
4or Uni* +lat4orm, it ma+s to a real Moti4 7/tton. In this relationshi+, the Moti4 7/tton is called the +eer to the
java.a;t.B/tton. I4 :o/ create t;o B/ttons, t;o +eers and hence t;o Moti4 B/ttons are also created. !he &ava
+lat4orm comm/nicates ;ith the Moti4 B/ttons /sing the &ava 1ative Inter4ace. (or each and ever:
com+onent added to the a++lication, there is an additional overhead tied to the local ;indo;ing s:stem, ;hich
is ;h: these com+onents are called heav: ;eight.
16. Which pac8a#e has li#ht wei#ht components*
Answer: java*.;ing +ac)age. 5ll com+onents in ;ing, e*ce+t &5++let, &6ialog, &(rame and &Windo; are
light;eight com+onents.
11. What are peerless components*
Answer: !he +eerless com+onents are called light ;eight com+onents.
1?. What is the &i))erence between the !ont an& !ont/etrics classes*
Answer: !he (ontMetrics class is /sed to de4ine im+lementationAs+eci4ic +ro+erties, s/ch as ascent and
descent, o4 a (ont o7ject.
1-. What happens when a threa& cannot ac5uire a loc8 on an ob3ect*
Answer: I4 a thread attem+ts to e*ec/te a s:nchroni<ed method or s:nchroni<ed statement and is /na7le to
ac@/ire an o7jectLs loc), it enters the ;aiting state /ntil the loc) 7ecomes availa7le.
?9. What is the &i))erence between the >ea&er(Writer class hierarchy an& the
Input$tream(.utput$tream class hierarchy*
Answer: !he Veader?Writer class hierarch: is characterAoriented, and the In+/ttream?O/t+/ttream class
hierarch: is 7:teAoriented.
?1. What classes o) e,ceptions may be cau#ht by a catch clause*
5
Answer: 5 catch cla/se can catch an: e*ce+tion that ma: 7e assigned to the !hro;a7le t:+e. !his incl/des
the Error and E*ce+tion t:+es.
?'.What is the &i))erence between throw an& throws 8eywor&s*
Answer: !he throw )e:;ord denotes a statement that ca/ses an e*ce+tion to 7e initiated. It ta)es the
E*ce+tion o7ject to 7e thro;n as arg/ment. !he e*ce+tion ;ill 7e ca/ght 7: an immediatel: encom+assing
tr:Acatch constr/ction or +ro+agated 4/rther /+ the calling hierarch:. !he throws )e:;ord is a modi4ier o4 a
method that designates that e*ce+tions ma: come o/t o4 the mehtod, either 7: virt/e o4 the method thro;ing
the e*ce+tion itsel4 or 7eca/se it 4ails to catch s/ch e*ce+tions that a method it calls ma: thro;.
?;. I) a class is &eclare& without any access mo&i)iers2 where may the class be accesse&*
Answer: 5 class that is declared ;itho/t an: access modi4iers is said to have +ac)age or 4riendl: access. !his
means that the class can onl: 7e accessed 7: other classes and inter4aces that are de4ined ;ithin the same
+ac)age.
?+. What is the /ap inter)ace*
Answer: !he Ma+ inter4ace re+laces the &6_ 1.1 6ictionar: class and is /sed associate )e:s ;ith val/es.
?:. Does a class inherit the constructors o) its superclass*
Answer: 5 class does not inherit constr/ctors 4rom an: o4 its s/+erclasses.
?6. Hame primitive Java types.
Answer: !he +rimitive t:+es are 7:te, char, short, int, long, 4loat, do/7le, and 7oolean.
?1. Which class shoul& you use to obtain &esi#n in)ormation about an ob3ect*
Answer: !he Class class is /sed to o7tain in4ormation a7o/t an o7jectLs design.
??. <ow can a JGI component han&le its own events*
Answer: 5 com+onent can handle its o;n events 7: im+lementing the re@/ired eventAlistener inter4ace and
adding itsel4 as its o;n event listener.
?-. <ow are the elements o) a Jri&Ba#"ayout or#ani=e&*
Answer:!he elements o4 a 3ridBagHa:o/t are organi<ed according to a grid. ,o;ever, the elements are o4
di44erent si<es and ma: occ/+: more than one ro; or col/mn o4 the grid. In addition, the ro;s and col/mns
ma: have di44erent si<es.
5
-9. What a&vanta#e &o JavaEs layout mana#ers provi&e over tra&itional win&owin# systems*
Answer: &ava /ses la:o/t managers to la: o/t com+onents in a consistent manner across all ;indo;ing
+lat4orms. ince &avaLs la:o/t managers arenLt tied to a7sol/te si<ing and +ositioning, the: are a7le to
accommodate +lat4ormAs+eci4ic di44erences among ;indo;ing s:stems.
-1. What are the problems )ace& by Java pro#rammers who &onEt use layout mana#ers*
Answer: Witho/t la:o/t managers, &ava +rogrammers are 4aced ;ith determining ho; their 3UI ;ill 7e
dis+la:ed across m/lti+le ;indo;ing s:stems and 4inding a common si<ing and +ositioning that ;ill ;or)
;ithin the constraints im+osed 7: each ;indo;ing s:stem.
-'. What is the &i))erence between static an& non7static variables*
Answer: 5 static varia7le is associated ;ith the class as a ;hole rather than ;ith s+eci4ic instances o4 a class.
1onAstatic varia7les ta)e on /ni@/e val/es ;ith each o7ject instance.
-;. What is the &i))erence between the paint46 an& repaint46 metho&s*
Answer: !he +aint98 method s/++orts +ainting via a 3ra+hics o7ject. !he re+aint98 method is /sed to ca/se
+aint98 to 7e invo)ed 7: the 5W! +ainting thread.
-+. What is the purpose o) the !ile class*
Answer: !he (ile class is /sed to create o7jects that +rovide access to the 4iles and directories o4 a local 4ile
s:stem.
-:. What restrictions are place& on metho& overloa&in#*
Answer: !;o methods ma: not have the same name and arg/ment list 7/t di44erent ret/rn t:+es.
-6. What restrictions are place& on metho& overri&in#*
Answer: Overridden methods m/st have the same name, arg/ment list, and ret/rn t:+e. !he overriding
method ma: not limit the access o4 the method it overrides. !he overriding method ma: not thro; an:
e*ce+tions that ma: not 7e thro;n 7: the overridden method.
-1. What is castin#*
Answer: !here are t;o t:+es o4 casting, casting 7et;een +rimitive n/meric t:+es and casting 7et;een o7ject
re4erences. Casting 7et;een n/meric t:+es is /sed to convert larger val/es, s/ch as do/7le val/es, to smaller
val/es, s/ch as 7:te val/es. Casting 7et;een o7ject re4erences is /sed to re4er to an o7ject 7: a com+ati7le
class, inter4ace, or arra: t:+e re4erence.
199. Hame ontainer classes.
5
Answer: Windo;, (rame, 6ialog, (ile6ialog, Panel, 5++let, or crollPane
191. What class allows you to rea& ob3ects &irectly )rom a stream*
Answer: !he O7jectIn+/ttream class s/++orts the reading o4 o7jects 4rom in+/t streams.
19'. <ow are this46 an& super46 use& with constructors*
Answer: this98 is /sed to invo)e a constr/ctor o4 the same class. s/+er98 is /sed to invo)e a s/+erclass
constr/ctor.
19;. <ow is it possible )or two $trin# ob3ects with i&entical values not to be e5ual un&er the BB
operator*
Answer: !he TT o+erator com+ares t;o o7jects to determine i4 the: are the same o7ject in memor:. It is
+ossi7le 4or t;o tring o7jects to have the same val/e, 7/t located indi44erent areas o4 memor:.
19+. What an I(. )ilter*
Answer: 5n I?O 4ilter is an o7ject that reads 4rom one stream and ;rites to another, /s/all: altering the data
in some ;a: as it is +assed 4rom one stream to another.
19:. What is the $et inter)ace*
Answer: !he et inter4ace +rovides methods 4or accessing the elements o4 a 4inite mathematical set. ets do
not allo; d/+licate elements.
196. What is the "ist inter)ace*
Answer: !he Hist inter4ace +rovides s/++ort 4or ordered collections o4 o7jects.
191. What is the purpose o) the enableEvents46 metho&*
Answer: !he ena7leEvents98 method is /sed to ena7le an event 4or a +artic/lar o7ject. 1ormall:, an event is
ena7led ;hen a listener is added to an o7ject 4or a +artic/lar event. !he ena7leEvents98 method is /sed 7:
o7jects that handle events 7: overriding their eventAdis+atch methods.
19?. What is the &i))erence between the !ile an& >an&omAccess!ile classes*
Answer: !he (ile class enca+s/lates the 4iles and directories o4 the local 4ile s:stem. !he Vandom5ccess(ile
class +rovides the methods needed to directl: access data contained in an: +art o4 a 4ile.
19-. What inter)ace must an ob3ect implement be)ore it can be written to a stream as an ob3ect*
'
Answer: 5n o7ject m/st im+lement the eriali<a7le or E*ternali<a7le inter4ace 7e4ore it can 7e ;ritten to a
stream as an o7ject.
119. What is the >esourceBun&le class*
Answer: !he Veso/rceB/ndle class is /sed to store localeAs+eci4ic reso/rces that can 7e loaded 7: a +rogram
to tailor the +rogramLs a++earance to the +artic/lar locale in ;hich it is 7eing r/n.
111. What is the &i))erence between a $crollbar an& a $crollPane*
Answer: 5 croll7ar is a Com+onent, 7/t not a Container. 5 crollPane is a Container. 5 crollPane handles
its o;n events and +er4orms its o;n scrolling.
11'. What is a Java pac8a#e an& how is it use&*
Answer: 5 &ava +ac)age is a naming conte*t 4or classes and inter4aces. 5 +ac)age is /sed to create a se+arate
name s+ace 4or gro/+s o4 classes and inter4aces. Pac)ages are also /sed to organi<e related classes and
inter4aces into a single 5PI /nit and to control accessi7ilit: to these classes and inter4aces.
11;. What are the .b3ect an& lass classes use& )or*
Answer: !he O7ject class is the highestAlevel class in the &ava class hierarch:. !he Class class is /sed to
re+resent the classes and inter4aces that are loaded 7: a &ava +rogram.
11+. What is $eriali=ation an& &eseriali=ation*
Answer: eriali<ation is the +rocess o4 ;riting the state o4 an o7ject to a 7:te stream. 6eseriali<ation is the
+rocess o4 restoring these o7jects.
11:. what is tunnellin#*
Answer: !/nnelling is a ro/te to some;here. (or e*am+le, VMI t/nnelling is a ;a: to ma)e VMI a++lication
get thro/gh 4ire;all. In C ;orld, t/nnelling means a ;a: to trans4er data.
116. Does the co&e in )inally bloc8 #et e,ecute& i) there is an e,ception an& a return statement in a catch
bloc8*
Answer: I4 an e*ce+tion occ/rs and there is a ret/rn statement in catch 7loc), the 4inall: 7loc) is still
e*ec/ted. !he 4inall: 7loc) ;ill not 7e e*ec/ted ;hen the :stem.e*it918 statement is e*ec/ted earlier or the
s:stem sh/t do;n earlier or the memor: is /sed /+ earlier 7e4ore the thread goes to 4inall: 7loc).
111. <ow you restrict a user to cut an& paste )rom the html pa#e*
Answer: Using javacri+t to loc) )e:7oard )e:s. It is one o4 sol/tions.
11?. Is Java a super set o) Java$cript*
'
Answer: 1o. !he: are com+letel: di44erent. ome s:nta* ma: 7e similar.
11-.What is a ontainer in a JGI*
Answer: 5 Container contains and arranges other com+onents 9incl/ding other containers8 thro/gh the /se o4
la:o/t managers, ;hich /se s+eci4ic la:o/t +olicies to determine ;here com+onents sho/ld go as a 4/nction o4
the si<e o4 the container.
1'9. <ow the ob3ect oriente& approach helps us 8eep comple,ity o) so)tware &evelopment un&er
control*
Answer:
We can disc/ss s/ch iss/e 4rom the 4ollo;ing as+ects2
o O7jects allo; +roced/res to 7e enca+s/lated ;ith their data to red/ce +otential inter4erence.
o Inheritance allo;s ;ellAtested +roced/res to 7e re/sed and ena7les changes to ma)e once and have e44ect in
all relevant +laces.
o !he ;ellAde4ined se+arations o4 inter4ace and im+lementation allo;s constraints to 7e im+osed on
inheriting classes ;hile still allo;ing the 4le*i7ilit: o4 overriding and overloading.
1'1. What is polymorphism*
Answer: Pol:mor+hism allo;s methods to 7e ;ritten that neednLt 7e concerned a7o/t the s+eci4ics o4 the
o7jects the: ;ill 7e a++lied to. !hat is, the method can 7e s+eci4ied at a higher level o4 a7straction and can 7e
co/nted on to ;or) even on o7jects o4 :et /nconceived classes.
1''. What is &esi#n by contract*
Answer: !he design 7: contract s+eci4ies the o7ligations o4 a method to an: other methods that ma: /se its
services and also theirs to it. (or e*am+le, the +reconditions s+eci4: ;hat the method re@/ired to 7e tr/e ;hen
the method is called. ,ence ma)ing s/re that +reconditions are. imilarl:, +ostconditions s+eci4: ;hat m/st
7e tr/e ;hen the method is 4inished, th/s the called method has the res+onsi7ilit: o4 satis4:ing the +ost
conditions.
In &ava, the e*ce+tion handling 4acilities s/++ort the /se o4 design 7: contract, es+eciall: in the case o4
chec)ed e*ce+tions. !he assert )e:;ord can 7e /sed to ma)e s/ch contracts.
1';. What are use cases*
Answer: 5 /se case descri7es a sit/ation that a +rogram might enco/nter and ;hat 7ehavior the +rogram
sho/ld e*hi7it in that circ/mstance. It is +art o4 the anal:sis o4 a +rogram. !he collection o4 /se cases sho/ld,
ideall:, antici+ate all the standard circ/mstances and man: o4 the e*traordinar: circ/mstances +ossi7le so that
the +rogram ;ill 7e ro7/st.
'
1'+. What is the &i))erence between inter)ace an& abstract class*
Answer:
o inter4ace contains methods that m/st 7e a7stractO a7stract class ma: contain concrete methods.
o inter4ace contains varia7les that m/st 7e static and 4inalO a7stract class ma: contain nonA4inal and 4inal
varia7les.
o mem7ers in an inter4ace are +/7lic 7: de4a/lt, a7stract class ma: contain nonA+/7lic mem7ers.
o inter4ace is /sed to Eim+lementsEO ;hereas a7stract class is /sed to Ee*tendsE.
o inter4ace can 7e /sed to achieve m/lti+le inheritanceO a7stract class can 7e /sed as a single inheritance.
o inter4ace can Ee*tendsE another inter4ace, a7stract class can Ee*tendsE another class and Eim+lementsE
m/lti+le inter4aces.
o inter4ace is a7sol/tel: a7stractO a7stract class can 7e invo)ed i4 a main98 e*ists.
o inter4ace is more 4le*i7le than a7stract class 7eca/se one class can onl: Ee*tendsE one s/+er class, 7/t
Eim+lementsE m/lti+le inter4aces.
o I4 given a choice, /se inter4ace instead o4 a7stract class.
Java Basics
1.!he &ava inter+reter is /sed 4or the e*ec/tion o4 the so/rce code.
!r/e
(alse
5ns2 a.
28 On s/ccess4/l com+ilation a 4ile ;ith the class e*tension is created.
a8 !r/e
78 (alse
5ns2 a.
38 !he &ava so/rce code can 7e created in a 1ote+ad editor.
a8 !r/e
78 (alse
5ns2 a.
$8 !he &ava Program is enclosed in a class de4inition.
a8 !r/e
78 (alse
5ns2 a.
58 What declarations are re@/ired 4or ever: &ava a++licationM
5ns2 5 class and the main9 8 method declarations.
'8 What are the t;o +arts in e*ec/ting a &ava +rogram and their +/r+osesM
5ns2 !;o +arts in e*ec/ting a &ava +rogram are2
&ava Com+iler and &ava Inter+reter.
'
!he &ava Com+iler is /sed 4or com+ilation and the &ava Inter+reter is /sed 4or e*ec/tion o4 the a++lication.
%8 What are the three OOPs +rinci+les and de4ine themM
5ns 2 Enca+s/lation, Inheritance and Pol:mor+hism are the three OOPs
Princi+les.
Enca+s/lation2
Is the Mechanism that 7inds together code and the data it mani+/lates, and )ee+s 7oth sa4e 4rom o/tside
inter4erence and mis/se.
Inheritance2
Is the +rocess 7: ;hich one o7ject ac@/ires the +ro+erties o4 another o7ject.
Pol:mor+hism2
Is a 4eat/re that allo;s one inter4ace to 7e /sed 4or a general class o4 actions.


-8 What is a com+ilation /nitM
5ns 2 &ava so/rce code 4ile.
08 What o/t+/t is dis+la:ed as the res/lt o4 e*ec/ting the 4ollo;ing statementM
:stem.o/t.+rintln9E?? Hoo)s li)e a comment.E8O
?? Hoo)s li)e a comment
!he statement res/lts in a com+ilation error
Hoo)s li)e a comment
1o o/t+/t is dis+la:ed
5ns 2 a.
1#8 In order 4or a so/rce code 4ile, containing the +/7lic class !est, to s/ccess4/ll: com+ile, ;hich o4 the
4ollo;ing m/st 7e tr/eM
It m/st have a +ac)age statement
It m/st 7e named !est.java
It m/st im+ort java.lang
It m/st declare a +/7lic class named !est
5ns 2 7
118 What are identi4iers and ;hat is naming conventionM
5ns 2 Identi4iers are /sed 4or class names, method names and varia7le names. 5n identi4ier ma: 7e an:
descri+tive se@/ence o4 /++er case W lo;er case letters,n/m7ers or /nderscore or dollar sign and m/st not
7egin ;ith n/m7ers.
128 What is the ret/rn t:+e o4 +rogramKs main9 8 methodM
5ns 2 void
138 What is the arg/ment t:+e o4 +rogramKs main9 8 methodM
5ns 2 string arra:.
1$8 Which characters are as 4irst characters o4 an identi4ierM
5ns 2 5 " `, a " <, ] ,a
158 What are di44erent commentsM
5ns 2 18 ?? AA single line comment
28 ?Z AA
Z? m/lti+le line comment
38 ?ZZ AA
Z? doc/mentation
1'8 What is the di44erence 7et;een constr/ctor method and methodM
5ns 2 Constr/ctor ;ill 7e a/tomaticall: invo)ed ;hen an o7ject is created. Whereas method has to 7e call
e*+licitl:.
1%8 What is the /se o4 7in and li7 in &6_M
5ns 2 Bin contains all tools s/ch as javac, a++let vie;er, a;t tool etc., ;hereas Hi7
'
contains all +ac)ages and varia7les.


Data types2variables an& Arrays
18 What is meant 7: varia7leM
5ns2 Daria7les are locations in memor: that can hold val/es. Be4ore assigning an: val/e to a varia7le, it m/st
7e declared.
28 What are the )inds o4 varia7les in &avaM What are their /sesM
5ns2 &ava has three )inds o4 varia7les namel:, the instance varia7le, the local varia7le and the class varia7le.
Hocal varia7les are /sed inside 7loc)s as co/nters or in methods as tem+orar: varia7les and are /sed to store
in4ormation needed 7: a single method.
Instance varia7les are /sed to de4ine attri7/tes or the state o4 a +artic/lar o7ject and are /sed to store
in4ormation needed 7: m/lti+le methods in the o7jects.
Class varia7les are glo7al to a class and to all the instances o4 the class and are /se4/l 4or comm/nicating
7et;een di44erent o7jects o4 all the same class or )ee+ing trac) o4 glo7al states.
38 ,o; are the varia7les declaredM
5ns2 Daria7les can 7e declared an:;here in the method de4inition and can 7e initiali<ed d/ring their
declaration.!he: are commonl: declared 7e4ore /sage at the 7eginning o4 the de4inition.
Daria7les ;ith the same data t:+e can 7e declared together. Hocal varia7les m/st 7e given a val/e 7e4ore
/sage.
$8 What are varia7le t:+esM
5ns2 Daria7le t:+es can 7e an: data t:+e that java s/++orts, ;hich incl/des the eight +rimitive data t:+es, the
name o4 a class or inter4ace and an arra:.
58 ,o; do :o/ assign val/es to varia7lesM
5ns2 Dal/es are assigned to varia7les /sing the assignment o+erator T.
'8 What is a literalM ,o; man: t:+es o4 literals are thereM
5ns2 5 literal re+resents a val/e o4 a certain t:+e ;here the t:+e descri7es ho; that val/e 7ehaves.
!here are di44erent t:+es o4 literals namel: n/m7er literals, character literals,
7oolean literals, string literals,etc.
%8 What is an arra:M
5ns2 5n arra: is an o7ject that stores a list o4 items.
-8 ,o; do :o/ declare an arra:M
5ns2 5rra: varia7le indicates the t:+e o4 o7ject that the arra: holds.
E*2 int arrRSO
08 &ava s/++orts m/ltidimensional arra:s.
a8!r/e
78(alse
5ns2 a.
1#8 5n arra: o4 arra:s can 7e created.
a8!r/e
78(alse
5ns2 a.
118 What is a stringM
5ns2 5 com7ination o4 characters is called as string.
128 trings are instances o4 the class tring.
a8!r/e
78(alse
5ns2 a.
138 When a string literal is /sed in the +rogram, &ava a/tomaticall: creates instances o4 the string class.
a8!r/e
'
78(alse
5ns2 a.
1$8 Which o+erator is to create and concatenate stringM
5ns2 5ddition o+erator9X8.
158 Which o4 the 4ollo;ing declare an arra: o4 string o7jectsM
tringR S sO
tring R Ss2
tringR sS2
tring sR S2
5ns 2 a, 7 and d
1'8 What is the val/e o4 aR3S as the res/lt o4 the 4ollo;ing arra: declarationM
1
2
3
$
5ns 2 d
1%8 Which o4 the 4ollo;ing are +rimitive t:+esM
7:te
tring
integer
(loat
5ns 2 a.
1-8 What is the range o4 the char t:+eM
# to 2
1'
# to 2
15
# to 2
1'
A1
# to 2
15
A1
5ns. d
108 What are +rimitive data t:+esM
5ns 2 7:te, short, int, long
4loat, do/7le
7oolean
char
2#8 What are de4a/lt val/es o4 di44erent +rimitive t:+esM
5ns 2 int A #
short A #
7:te A #
long A # l
4loat A #.# 4
do/7le A #.# d
7oolean A 4alse
char A n/ll
218 Converting o4 +rimitive t:+es to o7jects can 7e e*+licitl:.
a8!r/e
78(alse
5ns2 7.
228 ,o; do ;e change the val/es o4 the elements o4 the arra:M
5ns 2 !he arra: s/7scri+t e*+ression can 7e /sed to change the val/es o4 the elements o4 the arra:.
238 What is 4inal varai7leM
5ns 2 I4 a varia7le is declared as 4inal varia7le, then :o/ can not change its val/e. It 7ecomes constant.
'
2$8 What is static varia7leM
5ns 2 tatic varia7les are shared 7: all instances o4 a class.



.perators
18 What are o+erators and ;hat are the vario/s t:+es o4 o+erators availa7le in &avaM
5ns2 O+erators are s+ecial s:m7ols /sed in e*+ressions.
!he 4ollo;ing are the t:+es o4 o+erators2
5rithmetic o+erators,
5ssignment o+erators,
Increment W 6ecrement o+erators,
Hogical o+erators,
Bi;ise o+erators,
Com+arison?Velational o+erators and
Conditional o+erators
28 !he XX o+erator is /sed 4or incrementing and the AA o+erator is /sed 4or
decrementing.
a8!r/e
78(alse
5ns2 a.
38 Com+arison?Hogical o+erators are /sed 4or testing and magnit/de.
a8!r/e
78(alse
5ns2 a.
$8 Character literals are stored as /nicode characters.
a8!r/e
78(alse
5ns2 a.
58 What are the Hogical o+eratorsM
5ns2 OV9b8, 5169W8, [OV9G8 516 1O!9c8.
'8 What is the d o+eratorM
5ns 2 d o+erator is the mod/lo o+erator or reminder o+erator. It ret/rns the reminder o4 dividing the 4irst
o+erand 7: second o+erand.
%8 What is the val/e o4 111 d 13M
3
5
%
0
5ns 2 c.
-8 Is WWT a valid o+eratorM
5ns 2 1o.
08 Can a do/7le val/e 7e cast to a 7:teM
5ns 2 Fes
1#8 Can a 7:te o7ject 7e cast to a do/7le val/e M
5ns 2 1o. 5n o7ject cannot 7e cast to a +rimitive val/e.
118 What are order o4 +recedence and associativit:M
5ns 2 Order o4 +recedence the order in ;hich o+erators are eval/ated in e*+ressions.
5ssociativit: determines ;hether an e*+ression is eval/ated le4tAright or rightAle4t.
128 Which &ava o+erator is right associativit:M
'
5ns 2 T o+erator.
138 What is the di44erence 7et;een +re4i* and +ost4i* o4 AA and XX o+eratorsM
5ns 2 !he +re4i* 4orm ret/rns the increment or decrement o+eration and ret/rns the val/e o4 the increment or
decrement o+eration.
!he +ost4i* 4orm ret/rns the c/rrent val/e o4 all o4 the e*+ression and then
+er4orms the increment or decrement o+eration on that val/e.
1$8 What is the res/lt o4 e*+ression 5.$5 X E3,2EM
!he do/7le val/e -.'
!he string EE-.'E
!he long val/e -.
!he tring E5.$53.2E
5ns 2 d
158 What are the val/es o4 * and : M
* T 5O : T XX*O
5ns 2 * T 'O : T '
1'8 What are the val/es o4 * and <M
* T 5O < T *XXO
5ns 2 * T 'O < T 5






ontrol $tatements
18 What are the +rogramming constr/ctsM
5ns2 a8 e@/ential
78 election AA i4 and s;itch statements
c8 Iteration AA 4or loo+, ;hile loo+ and doA;hile loo+
28 class conditional Q
+/7lic static void main9tring argsRS8 Q
int i T 2#O
int j T 55O
int < T #O
< T i = j M i 2 jO ?? ternar: o+erator
:stem.o/t.+rintln9E!he val/e assigned is E X <8O
P
P
What is o/t+/t o4 the a7ove +rogramM
5ns2 !he val/e assigned is 2#
38 !he s;itch statement does not re@/ire a 7rea).
a8!r/e
78(alse
5ns2 7.
$8 !he conditional o+erator is other;ise )no;n as the ternar: o+erator.
a8!r/e
78(alse
5ns2 a.
58 !he ;hile loo+ re+eats a set o4 code ;hile the condition is 4alse.
a8!r/e
'
78(alse
5ns2 7.
'8 !he doA;hile loo+ re+eats a set o4 code atleast once 7e4ore the condition is tested.
a8!r/e
78(alse
5ns2 a.
%8 What are di44erence 7et;een 7rea) and contin/eM
5ns2 !he 7rea) )e:;ord halts the e*ec/tion o4 the c/rrent loo+ and 4orces control o/t o4 the loo+.
!he contin/e is similar to 7rea), e*ce+t that instead o4 halting the e*ec/tion o4 the loo+, it starts the ne*t
iteration.

-8 !he 4or loo+ re+eats a set o4 statements a certain n/m7er o4 times /ntil a condition is matched.
a8!r/e
78(alse
5ns2 a.
08 Can a 4or statement loo+ inde4intel:M
5ns 2 Fes.
1#8 What is the di44erence 7et;een ;hile statement and a do statement?
5ns 2 5 ;hile statement chec)s at the 7eginning o4 a loo+ to see ;hether the ne*t loo+ iteration sho/ld occ/r.
5 do statement chec)s at the end o4 a loo+ to see ;hether the ne*t iteration o4 a loo+ sho/ld occ/r. !he do
statement ;ill al;a:s e*ec/te the 7od: o4 a loo+ at least once.


Intro&uction to lasses an& /etho&s
18 Which is /sed to get the val/e o4 the instance varia7lesM
5ns2 6ot notation.
28 !he ne; o+erator creates a single instance named class and ret/rns a
re4erence to that o7ject.
a8!r/e
78(alse
5ns2 a.
38 5 class is a tem+late 4or m/lti+le o7jects ;ith similar 4eat/res.
a8!r/e
78(alse
5ns2 a.
$8 What is mean 7: gar7age collectionM
5ns2 When an o7ject is no longer re4erred to 7: an: varia7le, &ava a/tomaticall:
reclaims memor: /sed 7: that o7ject. !his is )no;n as gar7age collection.
58 What are methods and ho; are the: de4inedM
5ns2 Methods are 4/nctions that o+erate on instances o4 classes in ;hich the: are de4ined.O7jects can
comm/nicate ;ith each other /sing methods and can call methods in other classes.
Method de4inition has 4o/r +arts. !he: are name o4 the method, t:+e o4 o7ject or +rimitive t:+e the method
ret/rns, a list o4 +arameters and the 7od: o4 the method.
5 methodLs signat/re is a com7ination o4 the 4irst three +arts mentioned a7ove.
'8 What is calling methodM
5ns2 Calling methods are similar to calling or re4erring to an instance varia7le. !hese methods are accessed
/sing dot notation.
E*2 o7j.methodname9+aram1,+aram28
%8 Which method is /sed to determine the class o4 an o7jectM
'
5ns2 getClass9 8 method can 7e /sed to 4ind o/t ;hat class the 7elongs to. !his class is de4ined in the o7ject
class and is availa7le to all o7jects.
-8 5ll the classes in java.lang +ac)age are a/tomaticall: im+orted ;hen
a +rogram is com+iled.
a8!r/e
78(alse
5ns2 a.
08 ,o; can class 7e im+orted to a +rogramM
5ns2 !o im+ort a class, the im+ort )e:;ord sho/ld 7e /sed as sho;n.O
im+ort classnameO
1#8 ,o; can class 7e im+orted 4rom a +ac)age to a +rogramM
5ns2 im+ort java . +ac)agename . classname 9or8 im+ort java.+ac)age name.ZO
118 What is a constr/ctorM
5ns2 5 constr/ctor is a s+ecial )ind o4 method that determines ho; an o7ject is
initiali<ed ;hen created.
128 Which )e:;ord is /sed to create an instance o4 a classM
5ns2 ne;.
138 Which method is /sed to gar7age collect an o7jectM
5ns2 4inali<e 98.
1$8 Constr/ctors can 7e overloaded li)e reg/lar methods.
a8!r/e
78(alse
5ns2 a.
158 What is castingM
5ns2 Casting is 7/sed to convert the val/e o4 one t:+e to another.



1'8 Casting 7et;een +rimitive t:+es allo;s conversion o4 one +rimitive t:+e to another.
a8!r/e
78(alse
5ns2 a.
1%8 Casting occ/rs commonl: 7et;een n/meric t:+es.
a8!r/e
78(alse
5ns2 a.
1-8 Boolean val/es can 7e cast into an: other +rimitive t:+e.
a8!r/e
78(alse
5ns2 7.
108 Casting does not a44ect the original o7ject or val/e.
a8!r/e
78(alse
5ns2 a.
2#8 Which cast m/st 7e /sed to convert a larger val/e into a smaller oneM
5ns2 E*+licit cast.
218 Which cast m/st 7e /sed to cast an o7ject to another classM
5ns2 +eci4ic cast.
228 Which o4 the 4ollo;ing 4eat/res are common to 7oth &ava W CXXM
5.!he class declaration
%
7.!he access modi4iers
c.!he enca+s/lation o4 data W methods ;ith in o7jects
d.!he /se o4 +ointers
5ns2 a,7,c.
238 Which o4 the 4ollo;ing statements acc/ratel: descri7e the /se o4 access modi4iers ;ithin a class
de4initionM
a.!he: can 7e a++lied to 7oth data W methods
7.!he: m/st +recede a classLs data varia7les or methods
c.!he: can 4ollo; a classLs data varia7les or methods
d.!he: can a++ear in an: order
e.!he: m/st 7e a++lied to data varia7les 4irst and then to methods
5ns2 a,7,d.
2$8 /++ose a given instance varia7le has 7een declared +rivate.
Can this instance varia7le 7e mani+/lated 7: methods o/t side its classM
a.:es
7.no
5ns2 7.
258 Which o4 the 4ollo;ing statements can 7e /sed to descri7e a +/7lic methodM
a.It is accessi7le to all other classes in the hierarch:
7.It is accessa7lde onl: to s/7classes o4 its +arent class
c.It re+resents the +/7lic inter4ace o4 its class
d.!he onl: ;a: to gain access to this method is 7: calling one o4 the +/7lic class
methods
5ns2 a,c.
2'8 Which o4 the 4ollo;ing t:+es o4 class mem7ers can 7e +art o4 the internal +art o4 a classM
a.P/7lic instance varia7les
7.Private instance varia7les
c.P/7lic methods
d.Private methods
5ns2 7,d.
2%8 Fo/ ;o/ld /se the ]]]] o+erator to create a single instance o4 a named class.
a.ne;
7.dot
5ns2 a.
2-8 Which o4 the 4ollo;ing statements correctl: descri7es the relation 7et;een an o7ject and the instance
varia7le it storesM
a.Each ne; o7ject has its o;n distinctive set o4 instance varia7les
7.Each o7ject has a co+: o4 the instance varia7les o4 its class
c.the instance varia7le o4 each o7ject are se+erate 4rom the varia7les o4 other o7jects
d.!he instance varia7les o4 each o7ject are stored together ;ith the varia7les o4 other o7jects
5ns2 a,7,c.
208 I4 no in+/t +arameters are s+eci4ied in a method declaration then the declaration ;ill incl/de ]].
a.an em+t: set o4 +arantheses
7.the term void
5ns2 a.
3#8 What are the 4/nctions o4 the dot9.8 o+eratorM
a.It ena7les :o/ to access instance varia7les o4 an: o7jects ;ithin a class
7.It ena7les :o/ to store val/es in instance varia7les o4 an o7ject
c.It is /sed to call o7ject methods
d.It is to create a ne; o7ject
%
5ns2 a,7,c.
318 Which o4 the 4ollo;ing can 7e re4erenced 7: this varia7leM
a.!he instance varia7les o4 a class onl:
7.!he methods o4 a class onl:
c.!he instance varia7les and methods o4 a class
5ns2 c.
328 !he this re4erence is /sed in conj/nction ;ith ]]]methods.
a.static
7.nonAstatic
5ns2 7.
338 Which o4 the 4ollo;ing o+erators are /sed in conj/nction ;ith the this and s/+er re4erencesM
a.!he ne; o+erator
7.!he instanceo4 o+erator
c.!he dot o+erator
5ns2 c.
3$8 5 constr/ctor is a/tomaticall: called ;hen an o7ject is instantiated
a. tr/e
7. 4alse
5ns2 a.
358 When ma: a constr/ctor 7e called ;itho/t s+eci4:ing arg/mentsM
a. When the de4a/lt constr/ctor is not called
7. When the name o4 the constr/ctor di44ers 4rom that o4 the class
c. When there are no constr/ctors 4or the class
5ns2 c.
3'8 Each class in java can have a 4inali<er method
a. tr/e
7.4alse
5ns2 a.
3%8 When an o7ject is re4erenced, does this mean that it has 7een identi4ied 7: the 4inali<er method 4or
gar7age collectionM
a.:es
7.no
5ns2 7.
3-8 Beca/se 4inali<e 98 7elongs to the java.lang.O7ject class, it is +resent in all ]]].
a.o7jects
7.classes
c.methods
5ns2 7.
308 Identi4: the tr/e statements a7o/t 4inali<ation.
a.5 class ma: have onl: one 4inali<e method
7.(inali<ers are mostl: /sed ;ith sim+le classes
c.(inali<er overloading is not allo;ed
5ns2 a,c.
$#8 When :o/ ;rite 4inali<e98 method 4or :o/r class, :o/ are overriding a 4inali<er
inherited 4rom a s/+er class.
a.tr/e
7.4alse
5ns2 a.
$18 &ava memor: management mechanism gar7age collects o7jects ;hich are no longer re4erenced
a tr/e
%
7.4alse
5ns2 a.
$28 are o7jects re4erenced 7: a varia7le candidates 4or gar7age collection ;hen the varia7le goes o/t o4
sco+eM
a :es
7. no
5ns2 a.
$38 &avaLs gar7age collector r/ns as a ]]] +riorit: thread ;aiting 4or ]]+riorit: threads to relin@/ish the
+rocessor.
a.high
7.lo;
5ns2 a,7.
$$8 !he gar7age collector ;ill r/n immediatel: ;hen the s:stem is o/t o4 memor:
a.tr/e
7.4alse
5ns2 a.
$58 Fo/ can e*+licitl: dro+ a o7ject re4erence 7: setting the val/e o4 a varia7le ;hose data t:+e is a re4erence
t:+e to ]]]
5ns2 n/ll
$'8 When might :o/r +rogram ;ish to r/n the gar7age collecterM
a. 7e4ore it enters a com+/teAintense section o4 code
7. 7e4ore it enters a memor:Aintense section o4 code
c. 7e4ore o7jects are 4inali<ed
d. ;hen it )no;s there ;ill 7e some idle time
5ns2 a,7,d
$%8 (or e*ternali<a7le o7jects the class is solel: res+onsi7le 4or the e*ternal 4ormat o4 its contents
a.tr/e
7.4alse
5ns2 a
$-8 When an o7ject is stored, are all o4 the o7jects that are reacha7le 4rom that o7ject stored as ;ellM
a.tr/e
7.4alse
5ns2 a
$08 !he de4a/lt]] o4 o7jects +rotects +rivate and trancient data, and s/++orts the ]] o4 the classes
a.evol/tion
7.encoding
5ns2 7,a.
5#8 Which are )e:;ords in &avaM
a8 1UHH
78 si<eo4
c8 4riend
d8 e*tends
e8 s:nchroni<ed
5ns 2 d and e
518 When m/st the main class and the 4ile name coincideM
5ns 2When class is declared +/7lic.
528 What are di44erent modi4iersM
5ns 2 +/7lic, +rivate, +rotected, de4a/lt, static, trancient, volatile, 4inal, a7stract.
538 What are access modi4iersM
5ns 2 +/7lic, +rivate, +rotected, de4a/lt.
%
5$8 What is meant 7: EPassing 7: val/eE and E Passing 7: re4erenceEM
5ns 2 o7jects " +ass 7: re4errence
Methods A +ass 7: val/e
558 Is a class a s/7class o4 itsel4M
5ns 2 5 class is a s/7class itsel4.

5'8 What modi4iers ma: 7e /sed ;ith to+Alevel classM
5ns 2 +/7lic, a7stract, 4inal.
5%8 What is an e*am+le o4 +ol:mor+hismM
Inner class
5non:mo/s classes
Method overloading
Method overriding
5ns 2 c


Pac8a#es an& inter)ace
18 What are +ac)ages M ;hat is /se o4 +ac)ages M
5ns 2!he +ac)age statement de4ines a name s+ace in ;hich classes are stored.I4 :o/ omit the +ac)age, the
classes are +/t into the de4a/lt +ac)age.
ignat/re... +ac)age +)gO
Gse: Z It s+eci4ies to ;hich +ac)age the classes de4ined in a 4ile 7elongs to. Z Pac)age is 7oth naming and a
visi7ilit: control mechanism.
28 What is di44erence 7et;een im+orting Ejava.a++let.5++letE and Ejava.a++let.ZOE M
5ns 2Ejava.a++let.5++letE ;ill im+ort onl: the class 5++let 4rom the +ac)age java.a++let
Where as Ejava.a++let.ZE ;ill im+ort all the classes 4rom java.a++let +ac)age.
38 What do :o/ /nderstand 7: +ac)age access s+eci4ierM
5ns 2 +/7lic2 5n:thing declared as +/7lic can 7e accessed 4rom an:;here
+rivate2 5n:thing declared in the +rivate canKt 7e seen o/tside o4 its class.
de4a/lt2 It is visi7le to s/7classes as ;ell as to other classes in the same +ac)age.
$8 What is inter4aceM What is /se o4 inter4aceM
5ns 2 It is similar to class ;hich ma: contain methodKs signat/re onl: 7/t not 7odies.
Methods declared in inter4ace are a7stract methods. We can im+lement man: inter4aces on a class ;hich
s/++ort the m/lti+le inheritance.
58 Is it is necessar: to im+lement all methods in an inter4aceM
5ns 2 Fes. 5ll the methods have to 7e im+lemented.
'8 Which is the de4a/lt access modi4ier 4or an inter4ace methodM
5ns 2 +/7lic.
%8 Can ;e de4ine a varia7le in an inter4ace Mand ;hat t:+e it sho/ld 7e M
5ns 2 Fes ;e can de4ine a varia7le in an inter4ace. !he: are im+licitl: 4inal and static.
-8 What is di44erence 7et;een inter4ace and an a7stract classM
5ns 2 5ll the methods declared inside an Inter4ace are a7stract. Where as a7stract class m/st have at least one
a7stract method and others ma: 7e concrete or a7stract.
In Inter4ace ;e need not /se the )e:;ord a7stract 4or the methods.
08 B: de4a/lt, all +rogram im+ort the java.lang +ac)age.
!r/e?(alse
5ns 2 !r/e
1#8 &ava com+iler stores the .class 4iles in the +ath s+eci4ied in CH5P5!,
environmental varia7le.
!r/e?(alse
%
5ns 2 (alse

118 UserAde4ined +ac)age can also 7e im+orted j/st li)e the standard +ac)ages.
!r/e?(alse
5ns 2 !r/e
128 When a +rogram does not ;ant to handle e*ce+tion, the ]]]]]]class is /sed.
5ns 2 !hro;s
138 !he main s/7class o4 the E*ce+tion class is ]]]]]]] class.
5ns 2 V/ntimeE*ce+tion
1$8 Onl: s/7classes o4 ]]]]]]class ma: 7e ca/ght or thro;n.
5ns 2 !hro;a7le
158 5n: /serAde4ined e*ce+tion class is a s/7class o4 the ]]]]] class.
5ns 2 E*ce+tion
1'8 !he catch cla/se o4 the /serAde4ined e*ce+tion class sho/ld ]]]]]] its
Base class catch cla/se.
5ns 2 E*ce+tion
1%8 5 ]]]]]]] is /sed to se+arate the hierarch: o4 the class ;hile declaring an
Im+ort statement.
5ns 2 Pac)age

1-8 5ll standard classes o4 &ava are incl/ded ;ithin a +ac)age called ]]]]].
5ns 2 java.lang
108 5ll the classes in a +ac)age can 7e sim/ltaneo/sl: im+orted /sing ]]]].
5ns 2 Z
2#8 Can :o/ de4ine a varia7le inside an Inter4ace. I4 no, ;h:M I4 :es, ho;M
5ns.2 FE. 4inal and static
218 ,o; man: concrete classes can :o/ have inside an inter4aceM
5ns.2 1one
228 Can :o/ e*tend an inter4aceM
5ns.2 Fes
238 Is it necessar: to im+lement all the methods o4 an inter4ace ;hile im+lementing the inter4aceM
5ns.2 1o
2$8 I4 :o/ do not im+lement all the methods o4 an inter4ace ;hile im+lementing , ;hat s+eci4ier sho/ld :o/
/se 4or the class M
5ns.2 a7stract
258 ,o; do :o/ achieve m/lti+le inheritance in &avaM
5ns2 Using inter4aces.
2'8 ,o; to declare an inter4ace e*am+leM
5ns 2 access class classname im+lements inter4ace.
2%8 Can :o/ achieve m/lti+le inter4ace thro/gh inter4aceM
a8!r/e
78 4alse
5ns 2 a.
2-8 Can varia7les 7e declared in an inter4ace M I4 so, ;hat are the modi4iersM
5ns 2 Fes. 4inal and static are the modi4iers can 7e declared in an inter4ace.
208 What are the +ossi7le access modi4iers ;hen im+lementing inter4ace methodsM
5ns 2 +/7lic.
3#8 Can anon:mo/s classes 7e im+lemented an inter4aceM
5ns 2 Fes.
318 Inter4aces canKt 7e e*tended.
%
a8!r/e
78(alse
5ns 2 7.
328 1ame inter4aces ;itho/t a methodM
5ns 2 eriali<a7le, Clone7le W Vemote.
338 Is it +ossi7le to /se 4e; methods o4 an inter4ace in a class M I4 so, ho;M
5ns 2 Fes. 6eclare the class as a7stract.
%

Collections 3rae Wor9
Collection classes Collection Inter4aces Hegac: classes Hegac: inter4ace
57stract collection Collection 6ictionar: En/merator
57stract Hist Hist ,ash !a7le
57stract et et tac)
5rra: Hist orted et Dector
Hin)ed Hist Ma+ Pro+erties
,ash set Iterator
!ree et
,ash Ma+
!ree Ma+
57stract e@/ential
Hist
Wh: hashset is not allo;ing d/+licate elementM
9)&ecause set internally used Tree hierarchy that follows binary tree al"orithm thatQs why it doesnQt allow duplicate
!alue. :) It uses e8uals method for all ob4ect that we are storin" in set.
Collection Classes
57stract collection Im+lements most o4 the collection inter4aces.
57stract Hist E*tends 57stract collection W Im+lements Hist Inter4ace.
57stract Hist allo; Brandom accessC.
Methods>> void add 9int inde*, O7ject element8, 7oolean add9O7ject o8, 7oolean add5ll9Collection c8,
7oolean add5ll9int inde*, Collection c8, O7ject remove9int inde*8, void clear98, Iterator iterator98.
57stract et E*tends 57stract collection W Im+lements et inter4ace.
Array "ist 5rra: Hist e*tends 57stractHist and im+lements the Hist inter4ace. 5rra:Hist is a varia7le
length o4 arra: o4 o7ject re4erences, 5rra:Hist s/++ort d:namic arra: that gro; as needed. 5.H allo;
ra+id random access to element 7/t slo; 4or insertion and deletion 4rom the middle o4 the list. It ;ill allo;
d/+licate elements. earching is ver: 4aster.
5rra: Hist9 5.H8 internal node traversal 4rom the start to the end o4 the collection is signi4icantl: 4aster
than Hin)ed Hist traversal.
5.H is a re+lacement 4or Dector.
Methods>>void add 9int inde*, O7ject element8, 7oolean add9O7ject o8, 7oolean add5ll9Collection c8,
7oolean add5ll9int inde*, Collection c8, O7ject remove9int inde*8, void clear98, o7ject get9int inde*8, int
inde*O49O7ject element8, int latInde*O49O7ject element8, int si<e98, O7ject RS to5rra:98.
%
"in8e& "ist E*tends 57stacte@/entialHist and im+lements Hist inter4ace.
H.H +rovide o+timal se@/ence access, in e*+ensive insertion and deletion 4rom the middle o4 the list,
relativel: slo; 4or random access. When ever there is a lot o4 insertion W deletion ;e have to go 4or H.H.
H.H is accessed via a re4erence to the 4irst node o4 the list. Each s/7se@/ent node is accessed via a
re4erence to the 4irst node o4 the list. Each s/7se@/ent node is accessed via the lin)Are4erence n/m7er
stored in the +revio/s node.
Methods>> void add(irst9O7ject o7j8, addHast9O7ject o7j8, O7ject get(irst98, O7ject getHast98,void add
9int inde*, O7ject element8, 7oolean add9O7ject o8, 7oolean add5ll9Collection c8, 7oolean
add5ll9int inde*, Collection c8, O7ject remove9int inde*8, O7ject remove9O7ject o8, void clear98, o7ject
get9int inde*8, int inde*O49O7ject element8, int latInde*O49O7ject element8, int si<e98, O7ject RS to5rra:98.
,ash et E*tends 57stractet W Im+lements et inter4ace, it creates a collection that /ses ,ash!a7le
4or storage, ,. does not g/arantee the order o4 its elements, i4 / need storage go 4or !reeet. It ;ill not
allo; d/+licate elements
Methods>>7oolean add9O7ject o8, Iterator iterator98, 7oolean remove9O7ject o8, int si<e98.
!ree et E*tends 57stract et W Im+lements et inter4ace. O7jects are stored in sorted, ascending
order. 5ccess and retrial times are @/ite 4ast. It ;ill not allo; d/+licate elements. Dhis wont allow null.
Methods>> 7oolean add9O7ject o8, 7oolean add5ll9Collection c8, O7ject 4irst98, O7ject last98, Iterator
iterator98, 7oolean remove9O7ject o8.
<ash /ap E*tends 57stract Ma+ and im+lements Ma+ inter4ace. ,.M does not g/arantee the order o4
elements, so the order in ;hich the elements are added to a ,.M is not necessar: the order in ;hich the:
are read: 7: the iterate. ,.M +ermits onl: one n/ll val/es in it ;hile ,.! does not
,ashMa+ is similar to ,ashta7le.
!ree Ma+ im+lements Ma+ inter4ace, a !reeMa+ +rovides an e44icient means o4 storing )e:?val/e +airs
in sorted order and allo; ra+id retrieval.

57stract e@/ential Hist E*tends 57stract collectionO /se se@/ential access o4 its elements.
Collection Inter4aces
Collection Collection is a gro/+ o4 o7jects, collection does not allo; d/+licate elements.
Methods >> 7oolean add9O7ject o7j8, 7oolean add5ll9c8, int i<e98, O7jectRS to5rra:98, Boolean
isEm+t:98, O7ject RS to5rra:98, void clear98.Collection c8, Iterator iterator98,
7oolean remove9O7ject o7j8, 7oolean remove5ll9Collection
E*ce+tions >> Un/++ortedPointerE*ce+tion, ClassCastE*ce+tion.
Hist Hist ;ill e*tend Collection Inter4ace, list stores a se@/ence o4 elements that can contain d/+licates,
elements can 7e accessed their +osition in the list /sing a <ero 7ased inde*, 9it can access o7jects 7:
inde*8.
%
Methods >> void add9int inde*, O7ject o7j8, 7oolean add5ll9int inde*, Collection c8, O7ject get9int
inde*8, int inde*O49O7ject o7j8, int lastInde*O49O7ject o7j8, HistIterator iterator98, O7ject remove9int
inde*8, O7ject remove5ll9Collection c8, O7ject set9int inde*, O7ject o7j8.
et et ;ill e*tend Collection Inter4ace, et cannot contain d/+licate elements. et stored elements in
an /nordered ;a:. 9it can access o7jects 7: val/e8.
orted et E*tends et to handle sorted sets, orted et elements ;ill 7e in ascending order.
Methods >> O7ject last98, O7ject 4irst98, com+actor com+actor98.
E*ce+tions >> 1/llPointerE*ce+tion, ClassCastE*ce+tion, 1o/chElementE*ce+tion.
Ma+ Ma+ ma+s /ni@/e )e: to val/e in a ma+ 4or ever: )e: there is a corres+onding val/e and :o/ ;ill
loo)/+ the val/es /sing )e:s. Ma+ cannot contain d/+licate B)e:C and Bval/eC. In ma+ 7oth the B)e:C W
Bval/eC are o7jects.

Methods >> O7ject get9O7ject )8, O7ject +/t9O7ject ), O7ject v8, int si<e98, remove9O7ject o7ject8,
7oolean isEm+t:98
Iterator Iterator ma)es it easier to traverse thro/gh the elements o4 a collection. It also has an e*tra
4eat/re not +resent in the older En/meration inter4ace A the a7ilit: to remove elements. !his ma)es it eas:
to +er4orm a search thro/gh a collection, and stri+ o/t /n;anted entries.
Be4ore accessing a collection thro/gh an iterator :o/ m/st o7tain one i4 the collection classes +rovide
an iterator98 method that ret/rns an iterator to the start o4 the collection. B: /sing iterator o7ject :o/ can
access each element in the collection, one element at a time.
Methods >> 7oolean has1e*t98, o7ject ne*t98,void remove98
E*2A 5ra:Hist arr T ne; 5rra:Hist98O
5rr.add9BcC8O
Iterator itr T arr.iterator98O
While9itr.hash1e*t988
Q
O7ject element T itr.ne*t98O
P
Hist Iterator Hist Iterator gives the a7ilit: to access the collection, either 4or;ard?7ac);ard direction
Hegac: Classes
6ictionar: is an a7stract class that re+resent )e:?val/e storage re+ositor: and o+erates m/ch li)e
BMa+C once the val/e is stored :o/ can retrieve it 7: /sing )e:.
,ash !a7le ,ash!a7le stores )e:?val/e +airs in hash ta7le, ,ash!a7le is s:nchroni<ed ;hen /sing hash
ta7le :o/ have to s+eci4: an o7ject that is /sed as a )e:, and the val/e that :o/ ;ant to lin)ed to that )e:.
!he )e: is then hashed, and the res/lting hash code is /sed as the inde* at ;hich the val/e is stored ;ith
the ta7le. Use ,.! to store large amo/nt o4 data, it ;ill search as 4ast as vector. ,.! store the data in
se@/ential order.
%
Methods>> 7oolean contains_e:9O7ject )e:8, 7oolean containsDal/e9O7ject val/e8, O7ject get9O7ject
)e:8, O7ject +/t9O7ject )e:, O7ject val/e8
tac) is a s/7 class o4 vector, stac) incl/des all the methods de4ined 7: vector and adds several o4 its
o;n.
Dector Dector holds an: t:+e o4 o7jects, it is not 4i*ed length and vector is s:nchroni<ed. We can store
+rimitive data t:+es as ;ell as o7jects. 6e4a/lt length o4 vector is /+ to 1#.
Methods>> 4inal void addElement9O7ject element8, 4inal int si<e98, 4inal int ca+acit:98, 4inal 7oolean
removeElement5t9int inde*8, 4inal void remove5llElements98.
Pro+erties is a s/7class o4 ,ash!a7le, it is /sed to maintain the list o4 val/es in ;hich the B)e:?val/eC
is tring.
Hegac: Inter4aces
+n"eration #efine methods by which you can enumerate the elements in a collection of ob4ects. numeration
is synchroni7ed.
MethodsTT hasMorelements(),0b4ect nextlement().
Q) Which is the preferred collection class to "se for storin- database res"lt sets?
58 Hin)edHist is the 7est one, 7ene4its incl/de2
1. Vetains the original retrieval order. 2. ,as @/ic) insertion at the head?tail 3. 6oesnLt have an internal si<e
limitation li)e a Dector ;here ;hen the si<e is e*ceeded a ne; internal str/ct/re is created. $. Permits /serA
controlled s:nchroni<ation /nli)e the +reACollections Dector ;hich is al;a:s s:nchroni<ed
Ves/ltet res/lt T stmt.e*ec/te./er:9E...E8O
Hist list T ne; Hin)edHist98O
;hile9res/lt.ne*t988 Q
list.add9res/lt.gettring9EcolE88O
P
I4 there are m/lti+le col/mns in the res/lt set, :o/Lll have to com7ine them into their o;n data str/ct/re 4or
each ro;. 5rra:s ;or) ;ell 4or that as :o/ )no; the si<e, tho/gh a c/stom class might 7e 7est so :o/ can
convert the contents to the +ro+er t:+e ;hen e*tracting 4rom data7se, instead o4 later.
.8 E44icienc: o4 ,ash!a7le A I4 hash ta7le is so 4ast, ;h: donLt ;e /se it 4or ever:thingM
58 One reason is that in a hash ta7le the relations among )e:s disa++ear, so that certain o+erations 9other than
search, insertion, and deletion8 cannot 7e easil: im+lemented. (or e*am+le, it is hard to traverse a hash ta7le
according to the order o4 the )e:. 5nother reason is that ;hen no good hash 4/nction can 7e 4o/nd 4or a
certain a++lication, the time and s+ace cost is even higher than other data str/ct/res 9arra:, lin)ed list, or tree8.
,ashta7le has t;o +arameters that a44ect its e44icienc:2 its ca+acit: and its load 4actor. !he load 4actor
sho/ld 7e 7et;een #.# and 1.#. When the n/m7er o4 entries in the hashta7le e*ceeds the +rod/ct o4 the load
4actor and the c/rrent ca+acit:, the ca+acit: is increased 7: calling the rehash method. Harger load 4actors /se
memor: more e44icientl:, at the e*+ense o4 larger e*+ected time +er loo)/+.
I4 man: entries are to 7e +/t into a ,ashta7le, creating it ;ith a s/44icientl: large ca+acit: ma: allo; the
entries to 7e inserted more e44icientl: than letting it +er4orm a/tomatic rehashing as needed to gro; the ta7le.
.8 ,o; does a ,ashta7le internall: maintain the )e:Aval/e +airsM
58 !he ,ashta7le class /ses an internal 9+rivate8 class named Entr: to hold the )e:Aval/e +airs. 5ll entries o4
the ,ashta7le are stored in an arra: o4 Entr: o7jects ;ith the hash val/e o4 the )e: serving as the inde*. I4 t;o
or more di44erent )e:s have the same hash val/e these entries are stored as a lin)ed list /nder the same inde*.
-
.8 5rra:
5rray of fixed len"th of same data type@ we can store primiti!e data types as well as class ob4ects.
5rra:s are initiali<ed to the de4a/lt val/e o4 their t:+e ;hen the: are created, not declared, even i4 the: are
local varia7les
.8 6i44 Iterator W En/meration W Hist Iterator
Iterator is not s:nchroni<ed and en/meration is s:nchroni<ed. Both are inter4ace, Iterator is collection
inter4ace that e*tends 4rom IHistK inter4ace. En/meration is a legac: inter4ace, En/meration having 2 methods
IBoolean hasMoreElements98K W IO7ject 1e*tElement98K. Iterator having 3 methods I7oolean has1e*t98K,
Io7ject ne*t98K, Ivoid remove98K. Iterator also has an e*tra 4eat/re not +resent in the older En/meration
inter4ace A the a7ilit: to remove elements there is one method Bvoid remove98C.
Hist Iterator
It is an inter4ace, Hist Iterator e*tends Iterator to allo; 7iAdirectional traversal o4 a list and
modi4ication o4 the elements. Methods are Ihas1e*t98K, I hasPrevio/s98K.
.8 6i44 ,ash!a7le W ,ashMa+
&oth pro!ide 2eyE!alue to access the data. The C.T is one of the collection ori"inal collection classes in 4a!a. C.% is
part of new collection framewor2.
,.! is s:nchroni<ed and ,.M is not.
,.M +ermits n/ll val/es in it ;hile ,.! does not.
Iterator in the ,.P is 4ailAsa4e ;hile the en/merator 4or the ,.! is not.
.8 Converting 4rom a Collection to an arra: A and 7ac) againM
!he collection inter4ace de4ine the to5rra:98 method, ;hich ret/rns an arra: o4 o7jects. I4 :o/ ;ant to convert
7ac) to a collection im+lementation, :o/ co/ld man/all: traverse each element o4 the arra: and add it /sing
the add9O7ject8 method.
?? Convert 4rom a collection to an arra:
O7jectRS arra: T c.to5rra:98O
?? Convert 7ac) to a collection
Collection c2 T ne; ,ashet98O
4or9int i T #O i = arra:.lengthO iXX8
Q
c2.add9arra:RiS8O
P
.8 ,o; do I loo) thro/gh each element o4 a ,ashMa+M
58 =select idTEs;4E nameTEs;4E onChangeTEsho;tandardW(98E st:leTE;idth21%5+*OE>
=o+tion val/eTEE>WltOelect tandard Wor)(lo;WgtO=?o+tion>
=d
hma+ T9,ashMa+8re@/est.get5ttri7/te9Estd;4E8O
i49 hma+.si<e98 YT #8Q
int len T hma+.si<e98O
et set T hma+.)e:et98O
Iterator it T set.iterator98O
;hile9it.has1e*t988
-
Q
Integer )e: T 9Integer8it.ne*t98O
d>
=o+tion val/eTE=dT)e:d>E>=dT9tring8hma+.get9)e:8d>=?o+tion>
=d
P
P
d>
=?select>
.8 Vetrieving data 4rom a collectionM
+/7lic class Iterator6emo
Q
+/7lic static void main9tring argsRS8
Q
Collection c T ne; 5rra:Hist98O
?? 5dd ever: +arameter to o/r arra: list
4or 9int ind* T #O ind* = args.lengthO ind*XX8
Q
c.add9argsRind*S8O
P
?? E*amine onl: those +arameters that start ;ith A
Iterator i T c.iterator98O
?? PVE 2 Collection has all +arameters
;hile 9i.has1e*t988
Q
tring +aram T 9tring8 i.ne*t98O
?? Use the remove method o4 iterator
i4 9Y +aram.startsWith9EAE8 8
i.remove98O
P
?? PO!2 Collection onl: has +arameters that start ;ith A
?? 6emonstrate 7: d/m+ing collection contents
Iterator i2 T c.iterator98O
;hile 9i2.has1e*t988
Q
:stem.o/t.+rintln 9EParam 2 E X i2.ne*t988O
P
P
P
.8 ,o; do I sort an arra:M
-
5) 5rrays class pro!ides a series of sort() methods for sortin" arrays. If the array is an array of primiti!es (or) an array
of a class that implements 6omparable then you can 4ust call the method directly+
5rra:s.sort9the5rra:8O
If, howe!er, it is an array of ob4ects that donQt implement the 6omparable interface then you need to pro!ide a custom
6omparator to help you sort the elements in the array.
5rra:s.sort9the5rra:, theCom+arator8O
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
-
+:ception 2andlin-
Object

Throwable
rror xception
5-T rror Virtual Machine rror
6ompile time x. Runtime xception
(chec2ed) (Pnchec2ed)
0ut0fMemory. )tac20!er*low. 0*. *ilenot*ound.
5rithmetic. (ull%ointer. Indexoutof
&ound.
5rrayIndexout0f&ound. )tirn"Indexout0f&ound
+:ceptions
8C! What is an e:ception ? Write briefly abo"t 6! try 7! catch 8! finally ?
5n exception is an e!ent that occurs durin" the execution( or run time ) of a pro"ram that disrupts( stop ) the
normal flow of control.
If an exception is raised( at run time ), the pro"ram terminates by displayin" the cause of
exception. If we handle the exception properly, the pro"ram flow will be normal and continues
further. This facility is not a!ailable in 6 lan"ua"e.
Aote> -rite the followin" pro"ram in the examination for explainin" try, catch and finally bloc2s.
public class xceptionCandled <
public static !oid main()trin" ar"s= > ) <
int a ? J, b ? F, c @
try <
c ? a E b @
)ystem.out.println( c ) @
<
catch( 5rithmeticxception e ) <
)ystem.out.println( .#on;t di!ide by 7ero sir . B e ) @
A
finally <
)ystem.out.println( .Guaranteed execution . ) @
A
A
-
try >
try is a 2eyword in Ja!a that defines a bloc2 of statements. *irst, we must identify the
statements, in a pro"ram, that may raise the exception. Then place those statements in the try
bloc9. That is, the statements that are placed in the try bloc9, may cause( throw ) the exception. If
exception is not raised, the system simply i"nores the try bloc2.
catch>
catch is a 2eyword in Ja!a and denotes a bloc2 of statements. !ery try bloc9 should be
followed by a catch bloc9. The exception thrown by the try bloc2 is cau"ht( or handled ) by the
catch bloc2. -e must pro!ide a suitable exception class that can handle( or catch) the exception
thrown by the try bloc2. That is, catch bloc2 contains the e:ception handler. -hen an exception
handler present in the catch bloc2 successfully catches the exception, the pro"ram execution "oes
in a normal way and continues further.
0ne pro"ram can contain any number of try 1 catch bloc2s. 5 try bloc2 can ha!e any
number of catch bloc2s.
finally>
finally is a 2eyword in Ja!a and denotes a bloc2 of statements. The statements placed in
the finally bloc2 are definitely e:ec"ted whether catch bloc2 successfully catches the exception or
not. Generally, we write clean up statements in this bloc2, li2e closin" of streams or closin" of
soc2ets etc. finally bloc2 is optional.
8D! Write abo"t chec9ed e:ceptions and "nchec9ed e:ceptions ?
5ll exceptions can be broadly di!ided into two cate"ories+ 9. 6hec2ed exceptions
:. Pnchec2ed exceptions.
@nchec9ed e:ceptions>
5ll the subclasses of *"ntie+:ception are called "nchec9ed e:ceptions. )ome
examples are 5rithmeticxception and 5rrayIndex0ut0f&oundsxception. These exceptions are
called unchec2ed for the reason, e!en if the pro"rammer does not pro!ide any try 1 catch
mechanism, the pro-ra copiles. )ystem chec2s them at runtime and if an exception occurs
pro"ram terminates. If a try 1 catch bloc2 is pro!ided for these exceptions, pro"ram execution
continues further when exception really occurs.
Chec9ed e:ceptions>
5ll the subclasses of xception class except Runtimexception are called chec9ed
e:ceptions. *or these exceptions, pro"rammer should pro!ide a try 1 catch bloc2 whether really
exception raises or not, else pro"ram does not copile. Generally, these exceptions are written in
the method si"nature itself with throws clause. *ollowin" are the examples from Ja!a 5%I+
-
public *ileInput)tream( )trin" filename ) throws *ile(ot*oundxception
public !oid sleep( int milliseconds ) throws Interruptedxception
In the abo!e statements, *ile(ot*oundxception and Interruptedxception are chec2ed
exceptions. That is, when *ileInput)tream( )trin" filename ) constructor is used by the
pro"rammer, he should write a try 1 catch mechanism for *ile(ot*oundxception whether the file
passed as parameter really exists in the hard dis2 or not.
8E! Write briefly abo"t 6! %rithetic+:ception
7! %rray(nde:O"tOfBo"nds+:ception ?
6! %rithetic+:ception>
5rithmeticxception is a subclass of Runtimexception and is an unchec2ed exception.
That is, pro"ram compiles and runs e!en if the pro"rammer does not pro!ide a try 1 catch
mechanism for this exception.
This exception is raised by the system when we try to di!ide an inte"er !alue with 7ero
( floatin",point !alue di!ision with 7ero( li2e I.J E F ) prints (nfinity and not an exception ). *ollowin"
example illustrates+
public class xceptionCandled <
public static !oid main( )trin" ar"s= > ) <
int a ? J, b ? F, c @
try <
c ? a E b @ EE here b is 7ero
)ystem.out.println( c ) @
A
catch( 5rithmeticxception e ) <
)ystem.out.println( .#on;t di!ide by 7ero sir . B e ) @
A
)ystem.out.println( . Cello . ) @
A
A
In the abo!e pro"ram, the !alue of a J b is not e!aluated by the system and thereby
throws 5rithmeticxception. This exception is cau"ht by the catch bloc2. 5s the exception raised
by the try bloc2 is successfully handled by the catch bloc2, pro"ram execution continues further and
prints 2ello.
7! %rray(nde:O"tOfBo"nds+:ception>
5rrayIndex0ut0f&oundsxception is a subclass of Runtimexception and is an
unchec2ed exception. That is, pro"ram compiles and runs e!en if the pro"rammer does not pro!ide
a try 1 catch mechanism for this exception.
This exception is raised by the system when we try to access an index number that does not
exist in the array. *ollowin" example illustrates+
public class xceptionCandled <
-
public static !oid main( )trin" ar"s= > ) <
int x = > ? < 9F, :F, HF A @
try <
)ystem.out.println( x= J > ) @ EE Jth element does not exist
A
catch( 5rrayIndex0ut0f&oundsxception e ) <
)ystem.out.println( .#on;t cross the si7e of array . B e ) @
A
)ystem.out.println( . Cello . ) @
A
A
In the abo!e pro"ram, J
th
element does not exist in the array and the system, thereby,
throws 5rrayIndex0ut0f&oundsxception. This exception is cau"ht by the catch bloc2. 5s the
exception raised by the try bloc2 is successfully handled by the catch bloc2, pro"ram execution
continues further and prints 2ello.
8F! &isc"ss briefly ? 6! throws 7! throw ?
throws >
5ll the subclasses of xception class except Runtimexception are called chec9ed
e:ceptions. *or these exceptions, pro"rammer should pro!ide a try 1 catch bloc2 whether really
exception raises or not, else pro"ram does not copile. Generally, these exceptions are written in
the method si"nature itself with throws clause. *ollowin" are the examples from Ja!a 5%I+
public *ileInput)tream( )trin" filename ) throws *ile(ot*oundxception
public !oid sleep( int milliseconds ) throws Interruptedxception
-hen a pro"rammer uses the abo!e statements in his code, he must pro!ide a try 1
catch bloc2 or he must throw it bac2 to the system with throws clause. If not, pro"ram does not
compile. *ollowin" is the code to explain the abo!e+
public !oid display( ) <
try <
*ileInput)tream fis ? new *ileInut)tream( . a.txt . ) @
)ystem.out.println( . Cello . ) @
A
catch( *ile(ot*oundxception e ) <
)ystem.out.println( .The file does not exist in hard dis2 . B e ) @
A
A
In the abo!e code, if try N catch is not provided, the pro"ram does not copile, e!en if
a!t:t file exists in your current directory. &ecause you are pro!idin" a try 1 catch bloc2, if a!t:t file
exists or not, 2ello is printed.
-
5nother way of "ettin" the abo!e code compiled, without usin" try 1 catch bloc2, is by
throwin" the exception bac2 to the system with throws clause.
public !oid display( ) throws *ile(ot*oundxception <
*ileInput)tream fis ? new *ileInut)tream( . a.txt . ) @
)ystem.out.println( . Cello . ) @
A
In the abo!e pro"ram, instead of usin" a try 1 catch mechanism, we pro!ided throws clause.
That is, the exception raised by the system, when a!t:t file not does not exist, is thrown bac2 to the
)ystem. This helps the pro"ram to copile only. If really, the file a!t:t does not exist in the
current directory, 2ello is not printed.
throw >
throw is a 9eyword in Ja!a which we "enerally use with user defined exceptions. The throw
clause should be used with Throwable ob4ect( or ob4ects of it;s subclasses ). That is why, we extend
either Throwable or xception class for our user defined exception class. The followin" code
illustrates+
In the followin" pro"ram, user defined exception, (oMoneyxception is created and
used. If ban2 customer, tries to withdraw more amount then what balance he "ot, it throw the user
define exception.
class (oMoneyxception e:tends +:ception <
public (oMoneyxception( )trin" messa"e ) <
super( messa"e ) @ EE call superclass constructor
A
A
public class &an2 <
public static !oid main( )trin" ar"s= > ) <
int balance ? JFF, withdraw ? 9FFF @
if ( balance U withdraw )
throw new (oMoneyxception( . Insufficient funds please . ) @
A
A
In the abo!e pro"ram, the messa"e, (ns"fficient f"nds please is flashed as an
exception whene!er the balance is less than the withdraw amount. The same messa"e is informed
to the user throu"h a printf statement in a non ob4ect,oriented lan"ua"e li2e 6.
HG! What is *"ntie e:ception ? 1ive three e:aples ?
5ll the exceptions are deri!ed from the class Throwable. Throwable class has "ot two
subclasses 1 rror and xception. 5ll the subclasses of xception class can be di!ided broadly into
two cate"ories + 6hec2ed exceptions and Pnchec2ed exceptions.
*"ntie+:ception is a subclass of xception class. 5ll the subclasses of
Runtimexception class are called Pnchec2ed exceptions. These exceptions whether cau"ht or not
-
pro-ra will copile. &ut if really problem occurs at runtime, pro"ram terminates. This in
contrast with chec2ed exceptions.
)ome examples of Runtimexceptions are a) 5rithmeticxception b)
5rrayIndex0ut0f&oundsxception c) (umber*ormatxception etc.
a) %rithetic+:ception
5n error caused by di!idin" 7ero is called %rithetic+:ception( exception is a runtime
error where pro"ram terminates when not handled properly ).
-hether exception is handled or not the followin" pro"ram compiles. &ut does not print
Cello as exception is not cau"ht.
public class xceptionPnhandled <
public static !oid main( )trin" ar"s= > ) <
int a ? J, b ? F, c @
c ? a E b @
)ystem.out.println( c ) @
)ystem.out.println( . Cello . ) @
A
A
The followin" pro"ram compiles, runs and prints Cello as exception is handled.
public class xceptionCandled <
public static !oid main( )trin" ar"s= > ) <
int a ? J, b ? F, c @
try <
c ? a E b @
)ystem.out.println( c ) @
catch( 5rithmeticxception e ) <
)ystem.out.println( . #on;t enter 7ero for 8uantity .B e ) @
A
)ystem.out.println( . Cello . ) @
A
A
b) %rray(nde:O"tOfBo"nds+:ception >
This exception is raised at run,time when we try to access an array element that does
not exists. That is, when write an index number more than the array si7e, this exception is raised.
The followin" snippet of code illustrates +
int x= > ? < 9F, :F, HF A @
)ystem.out.println( x= J > ) @
The abo!e statement raises an exception called 5rrayIndex0ut0f&oundsxception as J
th

element does not exist in the array.
c) A"ber3orat+:ception >
-
The abo!e exception is raised when a strin" !alue is not parsed successfully at run,time.
The followin" code illustrates +
)trin" str ? 'J.:' @
int x ? Inte"er.parseInt( str ) @
If J.: is replaced with J, it wor2s.
.8 6i44 7?; E*ce+tion W Error
E*ce+tion and Error 7oth are s/7classes o4 the !hro;a7le class.

E*ce+tionE*ce+tion is generated 7: java r/ntime s:stem 9or8 7: man/all:. 5n e*ce+tion is a a7normal
condition that trans4er +rogram e*ec/tion 4rom a thro;er to catcher.
Error Will sto+ the +rogram e*ec/tion, Error is a a7normal s:stem condition ;e cannot handle these.
.8 Can an e*ce+tion 7e rethro;nM
58 Fes, an e*ce+tion can 7e rethro;n.
.8 tr:, catch, thro;, thro;s
tr: !his is /sed to 4i* /+ the error, to +revent the +rogram 4rom a/tomaticall: terminating, tr:Acatch is
/sed to catching an e*ce+tion that are thro;n 7: the java r/ntime s:stem.
!hro; is /sed to thro; an e*ce+tion e*+licitl:.
Throws 5 Throws clause list the type of exceptions that a methods mi"ht throu"h.
.8 What ha++ens i4 an e*ce+tion is not ca/ghtM
5) 5n uncau"ht exception results in the uncau"htxception() method of the threadQs ThreadGroup bein" in!o2ed, which
e!entually results in the termination of the pro"ram in which it is thrown.
.8 What ha++ens i4 a tr:AcatchA4inall: statement does not have a catch cla/se to handle an e*ce+tion that is
thro;n ;ithin the 7od: o4 the tr: statementM
!he e*ce+tion +ro+agates /+ to the ne*t higher level tr:Acatch statement 9i4 an:8 or res/lts in the +rogramLs
termination.
.8 Chec)ed W UnChec)ed E*ce+tion 2A
Chec)ed e*ce+tion is some s/7class o4 E*ce+tion. Ma)ing an e*ce+tion chec)ed 4orces client
+rogrammers to deal ;ith the +ossi7ilit: that the e*ce+tion ;ill 7e thro;n. eg, IOE*ce+tion thro;n 7:
java.io.(ileIn+/ttreamLs read98 methode

Unchec)ed e*ce+tions are V/ntimeE*ce+tion and an: o4 its s/7classes. Class Error and its s/7classes
also are /nchec)ed. With an /nchec)ed e*ce+tion, ho;ever, the com+iler doesnLt 4orce client +rogrammers
either to catch the e*ce+tion or declare it in a thro;s cla/se. In 4act, client +rogrammers ma: not even )no;
that the e*ce+tion co/ld 7e thro;n. eg, tringInde*O/tO4Bo/ndsE*ce+tion thro;n 7: tringLs char5t98
methode Chec)ed e*ce+tions m/st 7e ca/ght at com+ile time. V/ntime e*ce+tions do not need to 7e. Errors
o4ten cannot 7e.
Chec)ed E*ce+tions Un chec)ed e*ce+tion
Class9ot:oundException ArithmeticException
9o5uch2ethodException Arra%ndex)ut)f1oundException
1o/ch(ieldE*ce+tion ClasscastE*ce+tion
Interr/+tedE*ce+tion Illegal5rg/mentE*ce+tion
0
llegalAccessException
IllegalMonitorateE*ce+tion
Clone9ot5upportedException
Illegal!hreadtateE*ce+tion
Inde*O/tO4Bo/ndE*ce+tion
1/llPointerE*ce+tion
1/m7er(ormatE*ce+tion
tringInde*O/tO4Bo/nds
O/tO4Memor:Error AA> ignals that &DM has r/n o/t o4 memor: and that the gar7age collector is /na7le to
claim an: more 4ree memor:.
tac)Over(lo; AA> ignals that a stac) O.( in the inter+reter.
5rra:Inde*O/tO47o/nd AA> (or accessing an arra: element 7: +roviding an inde* val/es =# or > or e@/al to
the arra: si<e.
tringInde*O/tO47o/nd AA> (or accessing character o4 a string or string 7/44er ;ith inde* val/es =# or > or
e@/al to the arra: si<e.
5rithmetic E*ce+tion AA> s/ch as divide 7: <ero.
5rra:tore E*ce+tion AA> 5ssignment to an arra: element o4 an incom+ati7le t:+es.
ClasscastE*ce+tion AA> Invalid casting.
Illegal5rg/ment E*ce+tion AA> Illegal arg/ment is /sed to invo)e a method.
1/ll+ointer E*ce+tion AA> I4 attem+t to made to /se a n/ll o7ject.
1/m7er(ormat E*ce+tion AA> Invalid conversition o4 string to n/meric 4ormat.
Class1ot4o/nd E*ce+tion AA> class not 4o/nd.
Instantion E*ce+tion AA> 5ttem+t to create an o7ject o4 an 57stract class or Inter4ace.
1os/ch(ield E*ce+tion AA> 5 re@/est 4ield does not e*ist.
1os/chMethod E*ce+tion AA> 5 re@/est method does not e*ist.
.8 Methods in E*ce+tionsM
58 getMessage98, totring98, +rinttac)!race98, getHocali<edMessage98,
.8 What is e*ce+tion chainingM
5) 5n exception chain is a list of all the exceptions "enerated in response to a sin"le root exception. 5s
each exception is cau"ht and con!erted to a hi"her,le!el exception for rethrowin", itQs added to the chain.
This pro!ides a complete record of how an exception is handled The chained exception 5%I was introduced in 9.I. Two
methods and two constructors were added to Throwable.
!hro;a7le getCa/se98
!hro;a7le initCa/se9!hro;a7le8
!hro;a7le9tring, !hro;a7le8
!hro;a7le9!hro;a7le8
!he !hro;a7le arg/ment to initCa/se and the !hro;a7le constr/ctors is the e*ce+tion that ca/sed the c/rrent
e*ce+tion. getCa/se ret/rns the e*ce+tion that ca/sed the c/rrent e*ce+tion, and initCa/se ret/rns the c/rrent
e*ce+tion.
.8 Primitive m/lti tas)ing
,f the threads of different priorities shifting the control depend on the priority i.e.- a thread with
higher priority is executed first than the thread with lower priority. his process of shifting control is
&nown as primitive multi tas&ing.
.8 ,tt+ tat/s Codes
!o in4orm the client o4 a +ro7lem at the server end, :o/ call the BsendErrorC method. !his ca/ses the
server to res+ond ;ith stat/s line, ;ith +rotocol version and a s/ccess or error code.
!he 4irst digit o4 the stat/s code de4ines the class o4 res+onse, ;hile the last t;o digits do not have categories
0
9um"er 4%pe ;escription
<xx nformation
al
Re=uested received3 continuing to process
>xx 5uccess 4he action $as successfull% received3 understood3
and accepted
?xx Redirection :urther action must "e ta&en in order to complete
the re=uest
@xx Client
Error
4he re=uest contains "ad s%ntax or cannot "e
fulfilled
Axx 5erver
Error
4he server failed to fulfil valid re=uest
( O Streas
H6! What are 6! Byte Streas 7! Character Streas 8! 3ilter Streas ?
6! Byte Streas>
Generally, all the low,le!el streams, li2e 2eyboard input or output to a monitor or soc2et le!el
data transmission "oes by byte streams. In java!io pac2a"e, the subclasses of Input and 0utput
streams support these byte streams. *ileInpust)tream is "enerally used to read byte by byte from
a file and *ile0utput)tream is used to write byte by byte to a file.
7! Character Streas>
jd9 6!6 !ersion, introduces character based streams. 6haracter,based input and output
streams( subclasses of Reader and -riter classes) pro!ide se!eral ad!anta"es. -hile byte
streams( subclasses of Input)tream and 0utput)tream classes) reads M,bit 5)6II byte at a time,
character,based streams reads 9K,bit Pnicode characters. These are introduced to support Ja!a;s
internationali5ation.
*ileReader, an indirect subclass of Reader class, is a prominent class to read characters
from a file.
*ileReader fr ? new *ileReader( . #emo.txt . ) @
fr.read( ) @
8! 3ilter StreasI
The java!io pac2a"e pro!ides two abstract classes that define filter streams ,,,
*ilterInput)tream and *ilter0utput)tream for byte streams and *ilterReader and *ilter-riter for
character streams.
5 filter stream is a stream that filters data while readin" and writin" and adds some e:tra
f"nctionality which does not exist in the ori"inal source file. xample of filter streams+
Dine(umberInput)tream, #ataInput)tream, and %ushbac2Input)tream etc. The extra functionality
"i!en by the Dine(umberInput)tream is, it adds line numbers in the destination file that does not
exist in the source file. %ushbac2Input)tream pushes bac2 the extra unwanted character bac2 to
the system and is "enerally used in compilers and parsers etc.
0
*ilter streams does not read or write to a file directly. 5lways input for a hi"h,le!el stream is
a low,le!el stream. 5nd also a hi"h le!el stream can be lin2ed to another hi"h,le!el stream. The
followin" code snippet illustrates+
Connectin- a low?level strea to a hi-h?level strea>
*ileInput)tream fis ? new *ileInput)tream( . a.4a!a . ) @ EE a low,le!el stream
#ataInput)tream dis ? new #ataInput)tream( fis ) @ EE a hi"h,le!el stream
In the abo!e code, fis, a low,le!el input stream is passed as parameter to a hi"h,le!el
stream, #ataInput)tream.
Connectin- a hi-h?level strea to another hi-h?level strea>
*ileInput)tream fis ? new *ileInput)tream( . a.4a!a . ) @ EE a low,le!el stream
&ufferedInput)tream bis ? new &ufferedInput)tream( fis ) @ EE a hi"h,le!el stream
#ataInput)tream dis ? new #ataInput)tream( bis ) @ EE a hi"h,le!el stream
In the abo!e code, bis, a hi"h,le!el stream ob4ect is passed as a parameter to another hi"h,
le!el stream, #ataInput)tream.
H7! Write notes on read# ) and read;ine# ) ethods ?
6! read# ) ethod>
read# ) method is defined as an abstract method in Input)tream class and is
implemented by all its subclasses. read( ) method reads a byte from a file and returns an inte"er
!alue 1 the 5)6II !alue of the byte it is read. This method returns 19 when 0* is encountered
while readin" a file. read( ) method throws a chec2ed exception 1 I0xception. *ollowin" is the
method si"nature+
public abstract int read( ) throws I0xception EE as defined in Input)tream class
public int read( ) throws I0xception EE o!erridden in *ileInput)tream class
7! read;ine# ) ethod>
read;ine# ) method is defined in #ataInput interface. #ataInput interface is implemented by
#ataInput)tream. The abstract readDine( ) method of #ataInput interface is implemented("i!en a
body) by #ataInput)tream.
readDine( ) method reads a line( character by character until On is encountered ) from the
source file and returns a strin". This method throws I0xception, a chec2ed exception.
readDine( ) method is also a!ailable in &ufferedInput)tream on character streams side.
readDine( ) method of #ataInput)tream is deprecated, but the readDine( ) method of
&ufferedInput)tream is not. The followin" is the method si"nature+
public )trin" readDine( ) throws I0xception
0
H8! Write short notes on 6! (np"tStrea 7! 3ile(np"tStrea 8! 3ileO"tp"tStrea
H! &ata(np"tStrea B! 3ile*eader C! *ando%ccess3ile D! 3ile
E! B"ffered(np"tStrea F! .rintStrea ?
6! (np"tStrea >
5n Input)tream can be thou"ht of li2e a physical stream of water flowin" from a source to
destination. The only difference is, instead of water bytes will be flowin". The data in an input
stream is transmitted one byte at a time.
Ja!a uses input streams as a means of readin- data from an input source li2e 2eyboard, a
file or a soc2et.
The Input)tream class is an abstract class that ser!es as the base class for many input
stream classes li2e *ileInput)tream, )e8uenceInput)tream, 0b4ectInpust)tream etc. It defines
many abstract methods that are useful for all its subclasses li2e read( ), s2ip( ) and a!ailable( ) etc.
7! 3ile(np"tStrea >
0f all the subclasses of abstract Input)tream class, *ileInput)tream class is "enerally
used for performin" simple file input operations. To wor2 with *ileInput)tream class, there are three
steps to perform +
9. 0pen a file+ 5 file can be opened in readin" mode by usin" *ileInput)tream constructor
as follows+
*ileInput)tream fis ? new *ileInput)tream( . a.4a!a V ) @
EE throws *ile(ot*oundxception
:. Read from the file+ &yte by byte can be read from the file by usin" read( ) method of the
*ileInput)tream class as follows+
fis.read( ) @ EE throws I0xception
H. 6lose the file+ &y closin" the file, we can return the resources that are no lon"er
needed to the system and can be done as follows+
fis.close( ) @ EE throws I0xception
8! 3ileO"tp"tStrea >
0f all subclasses of 0utput)tream class, *ile0utput)tream class is "enerally used for
performin" simple file output operations. To wor2 with *ile0utput)tream class, there are three
steps to perform+
9. 0pen a file+ 5 file can be opened in writin" mode by usin" *ile0utput)tream constructor
as follows+
*ile0utput)tream fos ? new *ile0utput)tream( . b.4a!a V ) @
0
If the file, b!java does not exist in the current directory, a new one is created.
: -rite to the file+ &yte by byte can be written to a file by usin" write( ) method of the
*ile0utput)tream class as follows+
fos.write( 2 ) @ EE where 9 is an 5)6II int returned by the read( ) method
EE throws I0xception
H. 6lose the file+ &y closin" the file, we can return the resources that are no lon"er
needed to the system and can be done as follows+
fos.close( ) @ EE throws I0xception
H! &ata(np"tp"tStrea >
#ataInput)tream is a hi"h,le!el stream and is a subclass of *ilterInput)tream.
#ataInput)tream also implements #ataInput interface. #ataInput)tream includes special methods
li2e readInt( ) and read#ouble( ) etc., that reads the binary representation of data types int and
do"ble.
This input stream includes a special method readDine( ) method which reads a line as a
whole and returns a strin". readDine( ) method of #ataInput)tream is deprecated, but the
readDine( ) method of &ufferedInput)tream is not.
#ataInput)tream, bein" a hi"h le!el stream, can not read and write directly and to be lin2ed
to a low le!el stream. #ataInput)tream can also be lin2ed to another hi"h le!el stream for extra
functionality. *ollowin" illustrates+
*ileInput)tream fis ? new *ileInput)tream( . a.4a!a . ) @ EE a low,le!el stream
&ufferedInput)tream bis ? new &ufferedInput)tream( fis ) @ EE a hi"h,le!el stream
#ataInput)tream dis ? new #ataInput)tream( bis ) @ EE a hi"h,le!el stream
5n example usin" #ataInput)tream+ ( readin" 2eyboard input )
import 4a!a.io.N @
public class Ja!a)canf <
public static !oid main()trin" ar"s=>) throws I0xception <
#ataInput)tream dis ? new #ataInput)tream( )ystem.in ) @
)ystem.out.println( ' nter somethin"+' ) @
)trin" str ? dis.readDine( ) @
)ystem.out.println( ' Lou enetered+ ' B str ) @
A
A
B! 3ile*eader >
jd9 6!6 !ersion, introduces character based streams. 6haracter,based input and output
streams( subclasses of Reader and -riter classes) pro!ide se!eral ad!anta"es. -hile byte
streams( subclasses of Input)tream and 0utput)tream classes) reads M,bit 5)6II byte at a time,
0
character,based streams( subclasses of Reader and -riter classes) reads 9K,bit Pnicode
characters.
Cierarchy+
0b4ect Reader Input)treamReader *ileReader
*ileReader, an indirect subclass of Reader class, is a prominent class to read characters
from a file.
*ileReader fr ? new *ileReader( . #emo.txt . ) @
C! *ando%ccess3ile >
Pnli2e all other I E 0 streams, Random5ccess*ile can read from a file and write to a file.
&ecause it can both read and write, we must specify in which mode we are openin" the file. This
class constructor( also o!erloaded) ta2es two strin" ar"uments. The first one specifies the file
nae and the second one, the ode. 0nly two modes are supported 1 r # only for readin- ) and
rw # for readin- and writin- ). Just li2e in *ileInput)tream, the specified file does not exist, a new
one is created. The followin" statement opens a file in both readin" and writin" modes+
Random5ccess*ile raf ? new Random5ccess*ile( .#emo.txt ., . rw V ) @
Pnli2e all input stream classes, we can read and write to a file at any specified position with
its see9# ) method. The see2( ) method specifies the byte offset from the be"innin" of the file. This
stream is used mainly in on?line applications li2e airport reser!ation and super ba7ar systems
where random access of records is re8uired.
D! 3ile >
Ja!a supports files in two different classes+ 9. *ile :. Random5ccess*ile. &oth are subclasses of 0b4ect. -here
we re8uire a file name as ob4ect, we use *ile class.
*ile f9 ? new *ile( .a.4a!a . ) @
*ileInput)tream constructor will accept this ob4ect also as follows+
*ileInput)tream fis ? new *ileInput)tream( f6 ) @
In the abo!e statement, f6 is the ob4ect that represents the file, a.4a!a. The file ob4ect f6,
2eeps all the information about the file, a!java, includin" its location in the hard dis2 and its
accessibility permissions. It includes many 8uery methods with which we can "et a lot of
information about the file. *ile class constructor is o!erloaded where we can specify the class path
also( if the file is not in current directory). The *ile constructor can refer a directory also. The *ile
class pro!ides a number of methods for manipulatin" files and directories. The methods include li2e
canRead( ), can-rite( ), "et%arent( ), "et5bsolute%ath( ), len"th( ) etc.
E! B"ffered(np"tStrea >
&ufferin" is specific to the &ufferedInput)tream and &uffered0utput)tream classes.
&ufferin" speeds up input and output operations, by storin" data. 5 buffered input stream reads as
much data as possible e!en before we re8uest for it. That is &ufferedInput)tream uses bufferin"
effect.
0
&ufferedInput)tream is a hi"h le!el stream as it is a subclass of *ilterInput)tream. &ein" a
hi"h le!el stream, it cannot read a file directly. 5lways it re8uires a low le!el stream li2e
*ileInput)tream ob4ect as a parameter. The followin" is the code snippet+
*ileInput)tream fis ? new *ileInput)tream( ' a.4a!a ' ) @
&ufferedInput)tream bis ? new &ufferedInput)tream( fis ) @
The followin" full pro"ram illustrates the use of &ufferedInput)tream+
( in this pro"ram a file is copied to monitor)
import 4a!a.io.N @
public class Psin"&uffer <
public static !oid main()trin" ar"s=>) throws I0xception <
*ileInput)tream fis ? new *ileInput)tream( ' a.4a!a ' ) @
&ufferedInput)tream bis ? new &ufferedInput)tream( fis ) @
int 2 ? F @ EE 4ust initiali7e as it is a local !ariable for compiler satisfaction
)trin"&uffer sb ? new )trin"&uffer( ) @
while( ( 2 ? bis.read( ) ) R ? ?9 ) <
sb.append( ( char ) 2 ) @
A
)ystem.out.println( sb ) @
A
A
F! .rintStrea >
%rint)tream class belon"s to byte streams. 5 %rint)tram adds functionality to another output
stream. )pecial features of %rint)tream are +
9. Pnli2e other output streams, a %rint)tream ne!er throws an I0xception@ instead, in
exceptional situations merely set an internal fla" that can be tested !ia the chec2rror
method.
:. %rint)tream flushes the stream of bytes automatically. That is, the flush method is
automatically in!o2ed after a byte array is written or one of the println methods is in!o2ed
or a newline character or byte ( Q Wn Q ) is written.
The %rint-riter is e8ui!alent to %rint)tream in character streams. %rint-riter class should
be used in situations that re8uire writin" characters rather than bytes.
The followin" is the hierarchy.
0b4ect 0utput)tream *ilter0utput)tream %rint)tream
The followin" code illustrates+
import 4a!a.io.N@
public class %rint)tream#emo <
public static !oid main( )trin" ar"s= > ) <
0
%rint)tream ps ? new %rint)tream( )ystem.out ) @
ps.println('hello')@
ps.println(:J)@
ps.println(IJ.KS)@
ps.println(false)@
A
A
HH! Write a pro-ra that co"nts the n"ber of words in a file "sin- Strea$o9eni5er class "sin- whitespace
as deliiter ?
)treamTo2eni7er is a class defined 4a!a.io pc9a-e! It is a direct descendent( subclass ) of
0b4ect class. The )treamTo2eni7er class ta2es an input stream and parses it into 'to2ens', allowin"
the to2ens to be read one at a time. The parsin" process is controlled by a table and a number of
fla"s( li2e TTX-0R#, TTX0*, TTX0D etc, all representin" some inte"er !alue) that can be set to
!arious states. The )treamTo2eni7er can reco"ni7e identifiers, numbers, 8uoted strin"s and !arious
comment styles.
import 4a!a.io.N @
public class )treamTo2eni7er#emo <
static int words ? F @
public static !oid word6ount( Reader r ) throws I0xception <
)treamTo2eni7er st ? new )treamTo2eni7er( r ) @
st.word6hars( HH, :JJ ) @
while( st.nextTo2en( ) R ? st.TTX0*) < EE if to2en is not 0*
if( st.ttype ? ? st.TTX-0R# ) EE if to2en is a word
words B B @
A
A
public static !oid main()trin" ar"s= > ) throws I0xception <
*ileReader fr ? new *ileReader( ar"s= F > ) @ EE pass
word6ount( fr ) @
)ystem.out.println( ' Total words in file+ ' B words) @
A
A
Method si"nature of word6hars( ) +
public !oid word6hars( int low, int hi"h )+
+eci4ies that all characters 7et;een the range lo; and high are ;ord constit/ents. 5 ;ord to)en consists
o4 a ;ord constit/ent 4ollo;ed 7: <ero or more ;ord constit/ents or n/m7er constit/ents.
33 to 255 in the a7ove +rogram indicates that a ;ord can contain the characters l:ing
7et;een 5CII range 33 to 255. !his incl/des all s+ecial characters9 li)e Y, X, Z etc8,
al+ha7ets, digits etc.
HB! &escribe the "se of &ata(np"tStrea with an e:aple ?
#ataInput)tream is a byte stream. It is a hi"h,le!el stream and a subclass of
*ilterInput)tream. #ataInput)tream implements #ataInput interface. The followin" is the hierarchy.
0b4ect Input)tream *ilterInput)tream #ataInput)tream
5s it is a hi"h,le!el stream it cannot read directly a source( a file or 2eyboard input etc. ). It
must be lin2ed to a low,le!el stream. *or additional functionality, it can be lin2ed to another hi"h,
le!el stream also.
0
#ataInput)tream defines methods li2e readInt( ), read#ouble( ) and readDine( ) etc., that
reads an inte"er, a double and a line as a whole. This speeds up the readin" and thereby increases
the performance. The followin" pro"ram describes its usa"e +
import 4a!a.io.N @
public class #ata)tream#emo <
public static !oid main( )trin" ar"s= > ) <
try <
*ileInput)tream fis ? new *ileInput)tream( ' Cello.4a!a ' ) @ EE low,le!el stream
#ataInput)tream dis ? new #ataInput)tream( fis ) @ EE hi"h,le!el stream
)trin" str @ EE a temporary strin" !ariable
while( ( str ? dis.readDine( ) ) R ? null )
)ystem.out.println( str ) @
dis.close( ) @ fis.close( ) @ EE close the streams in re!erse order
A
catch( I0xception e ) <
e.print)tac2Trace( ) @
A
A
A
In the abo!e pro"ram readDine( ) method reads a line as a whole and returns as a strin". It returns
null when 0* is encountered. The followin" are the exceptions raised in the pro"ram.
)ethod J Constr"ctor +:ception
*ileInpust)tream( ) *ile(ot*oundxception
readDine( ) I0xception
close( ) I0xception
18 What is the di44erence 7et;een Ithro;K and Ithro;sK M5nd itKs a++licationM
5ns 2 E*ce+tions that are thro;n 7: java r/ntime s:stems can 7e handled 7: !r: and catch 7loc)s. With thro;
e*ce+tion ;e can handle the e*ce+tions thro;n 7: the +rogram itsel4. I4 a method is ca+a7le o4 ca/sing an
e*ce+tion that it does not
handle, it m/st s+eci4: this 7ehavior so the callers o4 the method can g/ard
against that e*ce+tion.
28 What is the di44erence 7et;een IE*ce+tionK and IerrorK in javaM
5ns 2 E*ce+tion and Error are the s/7classes o4 the !hro;a7le class. E*ce+tion class is /sed 4or e*ce+tional
conditions that /ser +rogram sho/ld catch. With e*ce+tion class ;e can s/7class to create o/r o;n c/stom
e*ce+tion.
Error de4ines e*ce+tions that are not e*ce+ted to 7e ca/ght 7: :o/ +rogram. E*am+le is tac) Over4lo;.
38 What is IVeso/rce lea)KM
5ns 2 (reeing /+ other reso/rces that might have 7een allocated at the 7eginning o4 a method.
$8What is the I4inall:K 7loc)M
5ns 2 (inall: 7loc) ;ill e*ec/te ;hether or not an e*ce+tion is thro;n. I4 an e*ce+tion is thro;n, the 4inall:
7loc) ;ill e*ec/te even i4 no catch statement match the e*ce+tion. 5n: time a method is a7o/t to ret/rn to the
caller 4rom inside tr:?catch 7loc), via an /nca/ght e*ce+tion or an e*+licit ret/rn statement, the 4inall: cla/se
is also e*ec/te.
0
58 Can ;e have catch 7loc) ;ith o/t tr: 7loc)M I4 so ;henM
5ns 2 1o. !r:?Catch or !r:?4inall: 4orm a /nit.
'8 What is the di44erence 7et;een the 4ollo;ing statementsM
Catch 9E*ce+tion e8,
Catch 9Error err8,
Catch 9!hro;a7le t8
5ns 2



%8 What ;ill ha++en to the E*ce+tion o7ject a4ter e*ce+tion handlingM
5ns 2 It ;ill go 4or 3ar7age Collector. 5nd 4rees the memor:.
-8 ,o; man: E*ce+tions ;e can de4ine in Ithro;sK cla/seM
5ns 2 We can de4ine m/lti+le e*ce+tions in thro;s cla/se.
ignat/re is..
t:+e methodAname 9+arameterAlist8 thro;s e*ce+tionAlist

08 !he 4inall: 7loc) is e*ec/ted ;hen an e*ce+tion is thro;n, even i4 no catch matches it.
!r/e?(alse
5ns 2 !r/e
1#8 !he s/7class e*ce+tion sho/ld +recede the 7ase class e*ce+tion ;hen /sed ;ithin the catch cla/se.
!r/e?(alse
5ns 2 !r/e
118 E*ce+tions can 7e ca/ght or rethro;n to a calling method.
!r/e?(alse
5ns 2 !r/e
128 !he statements 4ollo;ing the thro; )e:;ord in a +rogram are not e*ec/ted.
!r/e?(alse
5ns 2 !r/e
138 !he totring 9 8 method in the /serAde4ined e*ce+tion class is overridden.
!r/e?(alse
5ns 2 !r/e
1
$hreadin- Q"estions
What happens if a start method is not invoked and the run method is directly invoked?
(ns# ,f a thread has been instantiated but not started its is said to be in new state. 9nless until a start"# method is invo&ed on the instance of the
thread, it will not said to be alive. ,f you do not call a start"# method on the newly created thread instance thread is not considered to be alive. ,f the
start"# method is not invo&ed and the run"# method is directly called on the hread instance, the code inside the run"# method will not run in a
separate new thread but it will start running in the existing thread.
Can the variables or classes be Synchronized?
(ns# $o. %nly methods can be synchroni)ed.
9. -hat is the difference between %rocess and ThreadY
A process is a self contained execution environment and it can be seen as a program or application whereas
Thread is a single task of execution within the process. Java runtime environment runs as a single process which
contains diferent classes and programs as processes. Thread can be called lightweight process. Thread requires
less resources to create and exists in the process, thread shares the process resources.
:. -hat are the benefits of multi,threaded pro"rammin"Y
In ulti!Threaded programming, multiple threads are executing concurrentl" that improves the performance
because #$% is not idle incase some thread is waiting to get some resources. ultiple threads share the heap
memor", so it&s good to create multiple threads to execute some task rather than creating multiple processes.
'or example, (ervlets are better in performance than #)I because (ervlet support multi!threading but #)I
doesn&t.
H. -hat is difference between user Thread and daemon ThreadY
*hen we create a Thread in +ava program, it&s known as user thread. A daemon thread runs in background and
doesn&t prevent J, from terminating. *hen there are no user threads running, J, shutdown the program and
quits. A child thread created from daemon thread is also a daemon thread.
I. Cow can we create a Thread in Ja!aY
There are two wa"s to create Thread in Java - .rst b" implementing /unnable interface and then creating a
Thread ob+ect from it and second is to extend the Thread #lass. /ead this post to learn more about creating
threads in +ava.
J. -hat are different states in lifecycle of ThreadY
*hen we create a Thread in +ava program, its state is 0ew. Then we start the thread that change it&s state to
/unnable. Thread (cheduler is responsible to allocate #$% to threads in /unnable thread pool and change their
state to /unning. 1ther Thread states are *aiting, 2locked and 3ead. /ead this post to learn more about life
c"cle of thread.
K. 6an we call run() method of a Thread classY
1
4es, we can call run56 method of a Thread class but then it will behave like a normal method. To actuall" execute
it in a Thread, we need to start it using Thread.start() method.
S. Cow can we pause the execution of a Thread for specific timeY
*e can use Thread class sleep56 method to pause the execution of Thread for certain time. 0ote that this will not
stop the processing of thread for speci.c time, once the thread awake from sleep, it&s state gets changed to
runnable and based on thread scheduling, it gets executed.
M. -hat do you understand about Thread %riorityY
7ver" thread has a priorit", usuall" higher priorit" thread gets precedence in execution but it depends on Thread
(cheduler implementation that is 1( dependent. *e can specif" the priorit" of thread but it doesn&t guarantee
that higher priorit" thread will get executed before lower priorit" thread. Thread priorit" is an int whose value
varies from 8 to 89 where 8 is the lowest priorit" thread and 89 is the highest priorit" thread.
O. -hat is Thread )cheduler and Time )licin"Y
Thread (cheduler is the 1perating ("stem service that allocates the #$% time to the available runnable threads.
1nce we create and start a thread, it&s execution depends on the implementation of Thread (cheduler. Time
(licing is the process to divide the available #$% time to the available runnable threads. Allocation of #$% time
to threads can be based on thread priorit" or the thread waiting for longer time will get more priorit" in getting
#$% time. Thread scheduling can&t be controlled b" +ava, so it&s alwa"s better to control it from application itself.
9F. -hat is context,switchin" in multi,threadin"Y
#ontext (witching is the process of storing and restoring of #$% state so that Thread execution can be resumed
from the same point at a later point of time. #ontext (witching is the essential feature for multitasking operating
s"stem and support for multi!threaded environment.
99. Cow can we ma2e sure main() is the last thread to finish in Ja!a
%ro"ramY
*e can use Thread +oin56 method to make sure all the threads created b" the program is dead before .nishing
the main function. :ere is an article about Thread +oin method.
9:. Cow does thread communicate with each otherY
*hen threads share resources, communication between Threads is important to coordinate their eforts. 1b+ect
class wait56, notif"56 and notif"All56 methods allows threads to communicate about the lock status of a resource.
#heck this post to learn more about thread wait, notif" and notif"All.
9H. -hy thread communication methods wait(), notify() and notify5ll() are
in 0b4ect classY
In Java ever" 1b+ect has a monitor and wait, notif" methods are used to wait for the 1b+ect monitor or to notif"
other threads that 1b+ect monitor is free now. There is no monitor on threads in +ava and s"nchroni;ation can be
used with an" 1b+ect, that&s wh" it&s part of 1b+ect class so that ever" class in +ava has these essential methods
for inter thread communication.
1
9I. -hy wait(), notify() and notify5ll() methods ha!e to be called from
synchroni7ed method or bloc2Y
*hen a Thread calls wait56 on an" 1b+ect, it must have the monitor on the 1b+ect that it will leave and goes in
wait state until an" other thread call notif"56 on this 1b+ect. (imilarl" when a thread calls notif"56 on an" 1b+ect,
it leaves the monitor on the 1b+ect and other waiting threads can get the monitor on the 1b+ect. (ince all these
methods require Thread to have the 1b+ect monitor, that can be achieved onl" b" s"nchroni;ation, the" need to
be called from s"nchroni;ed method or block.
9J. Cow can we achie!e thread safety in Ja!aY
There are several wa"s to achieve thread safet" in +ava - s"nchroni;ation, atomic concurrent classes,
implementing concurrent <ock interface, using volatile ke"word, using immutable classes and Thread safe
classes. <earn more at thread safet" tutorial.
9K. -hat is !olatile 2eyword in Ja!a
*hen we use volatile ke"word with a variable, all the threads read it&s value directl" from the memor" and don&t
cache it. This makes sure that the value read is the same as in the memor".
9S. -hich is more preferred 1 )ynchroni7ed method or )ynchroni7ed
bloc2Y
("nchroni;ed block is more preferred wa" because it doesn&t lock the 1b+ect, s"nchroni;ed methods lock the
1b+ect and if there are multiple s"nchroni;ation blocks in the class, even though the" are not related, it will stop
them from execution and put them in wait state to get the lock on 1b+ect.
9M. Cow to create daemon thread in Ja!aY
Thread class set3aemon5true6 can be used to create daemon thread in +ava. *e need to call this method before
calling start56 method else it will throw IllegalThread(tate7xception.
9O. -hat is ThreadDocalY
Java Thread<ocal is used to create thread!local variables. *e know that all threads of an 1b+ect share it&s
variables, so if the variable is not thread safe, we can use s"nchroni;ation but if we want to avoid
s"nchroni;ation, we can use Thread<ocal variables.
7ver" thread has it&s own Thread<ocal variable and the" can use it&s get56 and set56 methods to get the default
value or change it&s value local to Thread. Thread<ocal instances are t"picall" private static .elds in classes that
wish to associate state with a thread. #heck this post for small example program showing Thread<ocal 7xample.
:F. -hat is Thread GroupY -hy it;s ad!ised not to use itY
Thread)roup is a class which was intended to provide information about a thread group. Thread)roup A$I is
weak and it doesn&t have an" functionalit" that is not provided b" Thread. Two of the ma+or feature it had are to
get the list of active threads in a thread group and to set the uncaught exception handler for the thread. 2ut Java
8.= has addedsetUncaughtExceptionHandler(UncaughtExceptionHandler eh) method using which we can add
uncaught exception handler to the thread. (o Thread)roup is obsolete and hence not advised to use an"more.
1
t8.set%ncaught7xception:andler5new %ncaught7xception:andler56>
?1verride
public void uncaught7xception5Thread t, Throwable e6 >
("stem.out.println5@exception occuredA@Be.getessage566C
D

D6C
:9. -hat is Ja!a Thread #ump, Cow can we "et Ja!a Thread dump of a
%ro"ramY
Thread dump is list of all the threads active in the J,, thread dumps are ver" helpful in anal";ing bottlenecks in
the application and anal";ing deadlock situations. There are man" wa"s using which we can generate Thread
dump - %sing $ro.ler, Eill !F command, +stack tool etc. I prefer +stack tool to generate thread dump of a program
because it&s eas" to use and comes with J3E installation. (ince it&s a terminal based tool, we can create script to
generate thread dump at regular intervals to anal";e it later on. /ead this post to know more about generating
thread dump in +ava.
::. -hat is #eadloc2Y Cow to analy7e and a!oid deadloc2 situationY
3eadlock is a programming situation where two or more threads are blocked forever, this situation arises with at
least two threads and two or more resources.
To anal";e a deadlock, we need to look at the +ava thread dump of the application, we need to look out for the
threads with state as 2<1#E73 and then the resources it&s waiting to lock, ever" resource has a unique I3 using
which we can .nd which thread is alread" holding the lock on the ob+ect.
Avoid 0ested <ocks, <ock 1nl" *hat is /equired and Avoid waiting inde.nitel" are common wa"s to avoid
deadlock situation, read this post to learn how to anal";e deadlock in +ava with sample program.
:H. -hat is Ja!a Timer 6lassY Cow to schedule a tas2 to run after specific
inter!alY
+ava.util.Timer is a utilit" class that can be used to schedule a thread to be executed at certain time in future.
Java Timer class can be used to schedule a task to be run one!time or to be run at regular intervals.
1
+ava.util.TimerTask is an abstract class that implements /unnable interface and we need to extend this class to
create our own TimerTask that can be scheduled using +ava Timer class.
#heck this post for +ava Timer example.
:I. -hat is Thread %oolY Cow can we create Thread %ool in Ja!aY
A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed.
A thread pool manages the collection of /unnable threads and worker threads execute /unnable from the queue.
+ava.util.concurrent.7xecutors provide implementation of +ava.util.concurrent.7xecutor interface to create the
thread pool in +ava. Thread $ool 7xample program shows how to create and use Thread $ool in +ava.
Ja!a 6oncurrency Inter!iew Zuestions
5nswers
9. -hat is atomic operationY -hat are atomic classes in Ja!a
6oncurrency 5%IY
Atomic operations are performed in a single unit of task without interference from other operations. Atomic
operations are necessit" in multi!threaded environment to avoid data inconsistenc".
intBB is not an atomic operation. (o b" the time one threads read it&s value and increment it b" one, other
thread has read the older value leading to wrong result.
To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using
("nchroni;ation but Java = +ava.util.concurrent.atomic provides wrapper classes for int and long that can be used
to achieve this atomicall" without usage of ("nchroni;ation. )o to this article to learn more about atomic
concurrent classes.
:. -hat is Doc2 interface in Ja!a 6oncurrency 5%IY -hat are it;s benefits
o!er synchroni7ationY
<ock interface provide more extensive locking operations than can be obtained using s"nchroni;ed methods and
statements. The" allow more Gexible structuring, ma" have quite diferent properties, and ma" support multiple
associated #ondition ob+ects.
The advantages of a lock are
it&s possible to make them fair
it&s possible to make a thread responsive to interruption while waiting on a <ock ob+ect.
it&s possible to tr" to acquire the lock, but return immediatel" or after a timeout if the lock can&t be
acquired
it&s possible to acquire and release locks in diferent scopes, and in diferent orders
H. -hat is xecutors *ramewor2Y
In Java =, 7xecutor framework was introduced with the +ava.util.concurrent.7xecutor interface.
1
The 7xecutor framework is a framework for standardi;ing invocation, scheduling, execution, and control of
as"nchronous tasks according to a set of execution policies.
#reating a lot man" threads with no bounds to the maximum threshold can cause application to run out of heap
memor". (o, creating a Thread$ool is a better solution as a .nite number of threads can be pooled and reused.
7xecutors framework facilitate process of creating Thread pools in +ava. #heck out this post to learn with
example code to create thread pool using 7xecutors framework.
I. -hat is &loc2in"ZueueY Cow can we implement %roducer,6onsumer
problem usin" &loc2in" ZueueY
+ava.util.concurrent.2lockingHueue is a Hueue that supports operations that wait for the queue to become non!
empt" when retrieving and removing an element, and wait for space to become available in the queue when
adding an element.
2lockingHueue doesn&t accept null values and throw 0ull$ointer7xception if "ou tr" to store null value in the
queue.
2lockingHueue implementations are thread!safe. All queuing methods are atomic in nature and use internal
locks or other forms of concurrenc" control.
2lockingHueue interface is part of +ava collections framework and it&s primaril" used for implementing producer
consumer problem.
#heck this post for producer!consumer problem implementation using 2lockingHueue.
J. -hat is 6allable and *utureY
Java = introduced +ava.util.concurrent.#allable interface in concurrenc" package that is similar to /unnable
interface but it can return an" 1b+ect and able to throw 7xception.
#allable interface use )eneric to de.ne the return t"pe of 1b+ect. 7xecutors class provide useful methods to
execute #allable in a thread pool. (ince callable tasks run in parallel, we have to wait for the returned 1b+ect.
#allable tasks return +ava.util.concurrent.'uture ob+ect. %sing 'uture we can .nd out the status of the #allable
task and get the returned 1b+ect. It provides get56 method that can wait for the #allable to .nish and then return
the result.
#heck this post for #allable 'uture 7xample.
K. -hat are 6oncurrent 6ollection 6lassesY
Java #ollection classes are fail!fast which means that if the #ollection will be changed while some thread is
traversing over it using iterator, the iterator.next56 will throw #oncurrentodi.cation7xception.
#oncurrent #ollection classes support full concurrenc" of retrievals and ad+ustable expected concurrenc" for
updates.
a+or classes are #oncurrent:ashap, #op"1n*riteArra"<ist and #op"1n*riteArra"(et, check this post to
learn how to avoid #oncurrentodi.cation7xception when using iterator.
S. -hat is xecutors 6lassY
7xecutors class provide utilit" methods for 7xecutor, 7xecutor(ervice, (cheduled7xecutor(ervice, Thread'actor",
and #allable classes.
1
7xecutors class can be used to easil" create Thread $ool in +ava, also this is the onl" class supporting execution
of #allable implementations.
)"ltithreadin-
HC! What is a thread ?
5 thread is a sin"le se8uential( separate ) flow of control within pro"ram.
)ometimes, it is called an e:ec"tion conte:t or li-ht wei-ht process. 5 thread itself is not a
pro"ram. 5 thread can not run on it;s own( as it is a part of a pro"ram ). Rather, it runs within a
pro"ram. 5 pro"ram can be di!ided into a number of pac2ets of code ,,,, each representin" a
thread ha!in" its own separate flow of control.
$wo threads r"nnin- conc"rrently in a sin-le pro-ra
;i-ht wei-ht process+ 5 thread is considered a li"ht wei"ht process because it runs within the
context of a pro"ram and ta2es ad!anta"e of the resources allocated to that pro"ram.
2eavy wei-ht process+ In the hea!y wei"ht process, the control chan"es in between threads
belon"in" to different processes. ( In li"ht wei"ht process, the control chan"es in between threads
belon"in" to same(one) process ).
+:ec"tion contest> 5 thread will ha!e its own execution stac2 and pro"ram counter. The code
runnin" within the thread wor2s only within that context.
0ne of the stren"ths of Ja!a is its support for multithreadin". 5ll the classes needed to write a multithreaded
pro"ram are included in the default imported pac2a"e java!lan- throu"h class Object, class $hread and interface
*"nnable.
HD! 2ow to create a thread and start r"nnin- ?
We can create a thread by instantiatin- $hread class# or of its s"bclasses) and invo9e start# ) on it!
5 thread is an instance of Thread class. To create a thread of a class, we must extend the class with Thread
class or Runnable interface.
public class #emo extends Thread <
public !oid run( ) <
1
5 PVOP3V5M
!;o
!hreads
for( int i ? F @ i U 9F @ i B B )
)ystem.out.println( i ) @ EE prints F to O numbers
A
public static !oid main( )trin" ar"s = > ) <
#emo d9 ? new #emo( ) @
d9.start( ) @ EE without this statement, run( ) method is not called
A
A
In the abo!e pro"ram, ob4ect d6, implicitly becomes a thread ob4ect( or to say, it can ma2e use of all the
methods of Thread class ). That is thread d6 is created. d6!start# ) ma2es thread to start functionin" by executin" the
code of run( ) method.
HE! Write briefly abo"t 6! r"n# ) 7! sleep# ) 8! stop# ) H! wait# ) B! notify# )
C! notify%ll# ) D! join# ) E! yield# ) ?
6! r"n# ) >
The run( ) method is a!ailable both in Thread class and Runnable interface. -e can
subclass a Thread class and o!erride the run( ) method. -e write the specific code, which we
would li2e to do by the thread, in the r"n# ) method. run( ) method is the heart of any Thread and
!ery important in its life cycle. It defines what the Thread should do when it is runnin".
-hen a thread comes out of the run( ) method, it dies. The followin" pro"ram illustrates+
public class #emo extends Thread <
p"blic void r"n# ) R
for# int i < G I i S 6G I i + + )
Syste!o"t!println# i ) I JJ prints G to F n"bers
T
public static !oid main( )trin" ar"s = > ) <
#emo d9 ? new #emo( ) @
d9.start( ) @
A
A
In the abo!e pro"ram, thread d9 starts the thread and prints F to O numbers by
executin" its run( ) method.
7! sleep# ) >
-e can temporarily stop a thread for some time from its acti!e( runnable ) state to a pause( bloc2ed ) state by
callin" sleep( ) method on it.
The followin" is the method si"nature of the sleep( ) method as defined in Thread class+
p"blic static void sleep# lon- illis ) throws Interruptedxception
-hen the thread is in sleep( ) condition, the thread scheduler bloc2s the microprocessor time to it. That is,
when sleep( ) method is called on the thread, it is not eli"ible for processor time, e!en if the processor is idle. sleep( )
method throws a chec2ed exception 1 Interruptedxception.
$he followin- pro-ra ill"strates the "sa-e of sleep# ) >
public class #emo extends Thread <
public !oid run( ) <
for( int i ? F @ i U 9F @ i B B ) <
)ystem.out.println( i ) @ EE prints F to O numbers
try R
$hread!sleep# 6GGG ) I
1
T
catch# (nterr"pted+:ception e ) R
Syste!o"t!println# L Soethin- happened to sleep L + e) I
T
A
A
public static !oid main( )trin" ar"s = > ) <
#emo d9 ? new #emo( ) @
d9.start( ) @
A
A
In the abo!e pro"ram, sleep( ) method is acti!ated for e!ery 9FFF milliseconds and for loop delays its
execution by 9FFF milliseconds for each iteration. That is, sleep( 9FFF ) ma2es thread inactive for 9FFF milliseconds.
8! stop# ) >
$hreadKs stop ethod stops a thread peranently! $he stopped thread cannot be restarted a-ain!
5 Thread instance has three main phases in its existence+
6! born > creation of thread, before bein" started.
$hread t < new $hread# ) I Thread t is in born state.
7! r"nnable > execution of code in run( ), after bein" started and before terminatin".
t!start# ) I when thread is started, it implicitly calls run( ) method.
8! death > after terminatin", but before bein" "arba"e collected.
6reatin" and startin" a thread instance brin"s a thread to life. 5 thread is in acti!e
condition until it executes its run( ) method or until stop( ) method is in!o2ed on it. stop# ) ethod 9ills a
thread and terinates it and the thread ob4ect is liable for "arba"e collection!
Restartin" a stopped thread is impossible. Instead, we can create a new thread to run the same code.
The followin" is the method si"nature defined in Thread class >
p"blic final void stop# )
This method is deprecated, as it is inherently unsafe.

H! wait# ) B! notofy# ) C! notify%ll# ) >
wait# ) >
This method is used in thread synchroni7ation. )ynchroni7ation helps inte"rity of data that is shared in between
concurrently runnin" threads. Doc2in" of a shared resource is necessary to ha!e consistent( or durable) data. In
monitors, when a thread tries to access an ob4ect which already bein" accessed, wait( ) method is called and thread
waits until notify( ) is called. The followin" is the method si"nature as defined in 0b4ect class+
p"blic final void wait# ) throws Interruptedxception
This method cannot be o!erridden in its subclasses as it final. wait( ) method is o!erloaded.
notify# ) and notify%ll# ) >
In thread synchroni7ation, notify( ) or notify5ll( ) is called on the waitin" thread(s) to "et access to the
synchroni7ed code. The followin" is the method si"nature as defined in 0b4ect class+
public final !oid notify( )
public final !oid notify%ll( )
1
notify( ) is called on a sin"le waitin" thread, notifyin" the thread that the condition of the
synchroni7ed code to be accessed is chan"ed. notify5ll( ) is called when threads are many waitin"
in the 8ueue
.
The abo!e methods cannot be o!erridden in the subclasses as they are final.
D! join# ) >
join# ) ethod a9es the thread to wait "ntil other threads finish their tas9!
Generally, threads are desi"ned to run independently of the other. join# ) method in!ol!es two threads. The
in!ocation of 4oin causes the currently executin" thread to suspend execution until tar"et thread finished its execution.
The followin" is the method si"nature+
p"blic final void join# ) throws (nterr"pted+:ception
4oin( ) method is o!erloaded. The difference between join# ) and wait# ) is 4oin( ) method does not in!ol!e in
synchroni7ation( that is, no loc2in" of data). wait( ) method is used by JVM in thread synchroni7ation. 0ther way, 4oin( )
and wait( ) methods are used in thread communication.
E! yeild# ) >
It is the thread scheduler to decide which thread should be "i!en next processor time.
This is decided by the waitin" time of the thread for processor and its priority. Threads with more priority will definitely
"et first preference than lower priority threads. If many threads of the same priority exist, they execute in round robin
fashion.
(f yield# ) ethod is called on a thread4 it vol"ntarily -ives off its processor tie to other threads!
yield# ) ethod yields its tie to other threads of sae priority only!
-hen the thread "i!es off its time, it is the thread scheduler to decide a"ain which thread is to be "i!en next slice of
processor time. The followin" is the method si"nature defined Thread class >
p"blic static void yield# )
HF! &isc"ss the life cycle of a thread ?
Just li2e an applet and ser!let, threads too "ot a life cycle between their birth and death.
s"spend# )4 wait# )4 sleep# )4 (JO bloc9in-
start# )

res"e# )4 notify# )4 sleep tie?o"t4 (JO finished
stop# ) stop# ) stop# )
$he $hread life Cycle
1
Runnable
B
l
o
c
9
e
d
Hewly
reate&
&
e
a
d
Born state > -hen a thread is created, the thread will be in born state. The thread in born state
is not eli-ible for processor tie.
Thread t9 ? new Thread( ) @
In the abo!e statement, thread t6 is created and is in born state.
*"nnable state > 5fter the creation of thread, when start( ) method is called, it comes into
r"nnable state. The thread in runnable state is eli"ible for processor time. In
the runnable state, the thread calls run( ) method and executes the code.
t6!start# ) I This method "ets the thread into r"nnable state.
Bloc9ed state > -e can bloc2 the microprocessor time for a thread by callin" sleep( ), wait( ) or
suspend( ) methods on it. The thread in bloc2ed state is alive and is not
eli"ible for processor time e!en if the processor is idle.
&ead state > The thread in dead state is liable for -arba-e collection.
!ents when a thread can come into dead state >
9. when stop( ) method is called on the thread.
:. -hen the thread completes the execution of run( ) method.
H. -hen the power supply to the system is cut off.
BG! What ethods can stop a thread ?
5 runnin" thread can be stopped with the followin" methods defined in Thread class.
9. sleep# ) method ma2es a runnin" thread inacti!e. That is the thread stops its functionin". The thread is not
"i!en any microprocessor time.
:. s"spend# ) method suspends( stops ) a thread execution for an indefinite time until resume( ) method is
called on it.
H. wait# ) method calls a runnin" thread to wait for some time until it calls notify( ) or notity5ll( ) method on it.
This method is used in synchroni7ation.
I. stop# ) method stops a thread;s execution permanently. -hen stop( ) is called on a runnin" thread, an
ob4ect of Thread#eath is called on it and the thread ob4ect is "arba"e collected. That is a stopped thread by
callin" stop( ) method can not be restarted a"ain.
B6! What is thread synchroni5ation ?
or
Write briefly abo"t synchroni5ed 9eyword ?
$hread synchroni5ation provides the tool for ens"rin- that different threads ta9e proper t"rns when
"sin- shared reso"rces!
Thread synchroni7ation is important in a multithreaded pro"ram to maintain the consistency and durability of
data that is accessed by different threads.
Multiple threads of a pro"ram run independently of one another. ach thread does not bother about the
acti!ities of other threads. -hen a thread wor2s on its own and on separate data( i.e., not shard ), the data will not be
in inconsistent state. The problem( due to inconsistency of data ) occurs when the sae data is accessed( or shared )
by different threads.
-hen the threads act on shared data, tiin- is an important issue. &y the process of synchroni7ation, we an
ensure only one thread can access the source at a time and other threads should wait in a 8ueue until the first thread
comes out after finishin" its execution. -e use synchroni5ed 2eyword to monitor the acti!ities of different threads. -e
can use synchroni5ed as an access modifier.
The followin" method is synchroni7ed >
1
public synchroni5ed !oid update( int amount ) <
balance ? < amount @
A
-hen a thread is accessin" the abo!e update( ) method, other thread is not allowed to access it.
J:. -hat is a ThreadGroup class Y xplain any three methods of this class Y
!ery thread belon"s to some "roup. That is no thread that exists without a thread
"roup ( li2e no file exists without a directory ). -hile creatin" a thread, if no "roup is specified, by
default it is put into ain thread -ro"p. 5 thread "roup can ha!e both threads and other thread
"roups as members( li2e a directory can include both directories( as sub,directories) and files).
p"blic class $hread1ro"p e:tends Object
Constr"ctors &escription
public ThreadGroup( )trin" name ) a thread "roup is created by a name
public ThreadGroup( ThreadGroup parent, )trin" name ) assi"nin" to a "roup with a name
)ethods &escription
public int acti!e6ount( ) retruns the no. of acti!e threads at the current time
public final "etMax%riority( ) returns the max. priority a thread can be assi"ned with
public )trin" "et(ame( ) returns the name of the thread "roup
%dvanta-es with thread -ro"ps >
5ll the threads in a thread "roup can be stopped to"ether by callin" t".stop( ) or can be
suspended by callin" t".suspend( ) or can be resumed by callin" t".resume( ) where t- is a thread
"roup. &ut we canKt start by callin" t".start( ). ach thread must be started indi!idually.
Soe ethods of $hread1ro"p >
-et$hread1ro"p# ) > This method returns an ob4ect ThreadGroup class. -ith this "roup we can
8uestion a thread to what "roup it belon"s.
-et.arent# ) > This method returns an ob4ect of ThreadGroup class. -ith this method, we can
2now the parent thread "roup to which a thread "roup belon"s.
activeCo"nt# ) > This method returns an int !alue. -ith this method we can 2now the number of
acti!e threads( the threads that are ali!e) in a "roup currently.
The followin" pro"ram illustrates +
I( TCI) %R0GR5M+ usin" thread priority and thread "roup.
3ile Aae> $hread1ro"p(nfo!java
public class ThreadGroupInfo extends Thread <
public static !oid main( )trin" ar"s = > ) <
1
Thread t9 ? new Thread( ) @ EE as no "roup is specified, it is put into main "roup
)ystem.out.println( 't9 thread name+ ' B t9."et(ame( ) ) @ EE Thread,F
)ystem.out.println( 't9 thread "roup name+ ' B t9."etThreadGroup( ) )@ EE main
ThreadGroup "roup ? new ThreadGroup( 'MyGroup' ) @
)ystem.out.println( 'Thread "roup name is ' B "roup."et(ame( ) ) @ EEMyGroup
)ystem.out.println('%arent "roup of MyGroup is 'B "roup."et%arent( ) )@ EEmain
)ystem.out.println( 'Thread "roup priority is ' B "roup."etMax%riority( ) ) @ EE9F
EE the root "roup of e!ery user defined thread "roup is main
)ystem.out.println( 'Wn5cti!e (umber of thrads in the "roup+ ' B
"roup.acti!e6ount( ) )@ EE returns F as no acti!e threads are runnin"
Thread t: ? new Thread( "roup, 'MyThread9' ) @
)ystem.out.println( 'Wnt: name is ' B t:."et(ame( ) ) @ EE MyThread9
)ystem.out.println( 't: belon"s to "roup ' B t:."etThreadGroup( ) )@ EEMyGroup
A EE If a thread is not "i!en a name, by default JVM "i!es Thread,(( where ( is
A EE an inte"er number startin" with F
ach thread carries with it three types of information+ a) Thread name b) Thread priority
and c) Thread "roup name. If priority is not specified, by default, the thread ac8uires the priority of
its "roup.
;6. <ow to create multithrea& in a pro#ram*
Answer: Fo/ have t;o ;a:s to do so. (irst, ma)ing :o/r class Ee*tendsE Thread class. econd, ma)ing :o/r
class Eim+lementsE Runnable inter4ace. P/t jo7s in a r/n98 method and call start98 method to start the thread.
;1. an Java ob3ect be loc8e& &own )or e,clusive use by a #iven threa&*
Answer: Fes. Fo/ can loc) an o7ject 7: +/tting it in a Es:nchroni<edE 7loc). !he loc)ed o7ject is inaccessi7le
to an: thread other than the one that e*+licitl: claimed it
;?. an each Java ob3ect 8eep trac8 o) all the threa&s that want to e,clusively access to it*
Answer: Fes
;-. What state &oes a threa& enter when it terminates its processin#*
Answer: When a thread terminates its +rocessing, it enters the dead state.
+9. What invo8es a threa&Es run46 metho&*
Answer: 54ter a thread is started, via its start98 method o4 the !hread class, the &DM invo)es the threadLs r/n98
method ;hen the thread is initiall: e*ec/ted.
B8! +:plain join# ) ethod with an e:aple ?
1
4oin( ) method ma2es the thread to wait until other threads finish therir tas2.
Generally, threads are desi"ned to run independently of the other, 4oin( ) method in!ol!es
two threads. The in!ocation of 4oin causes the currently executin" thread to suspend execution until
tar"et thread finished its execution. The followin" is the method si"nature +
4oin( ) method is o!erloaded. The difference between 4oin( ) and wait( ) is 4oin( ) method does
not in!ol!e in synchroni7ation( that is, no loc2in" of data ). wait( ) method is used by JVM in thread
synchroni7ation. 0ther way, 4oin( ) and wait( ) methods are used in thread communication. The
callin" thread waits until called thread completes its execution and dies. &y usin" 4oin( ), data
consistency can be maintained.
/G"DI D<>EADIHJ
18 What are the t;o t:+es o4 m/ltitas)ingM
5ns 2 1.+rocessA7ased
2.!hreadA7ased
28 What are the t;o ;a:s to create the threadM
5ns 2 1.7: im+lementing V/nna7le
2.7: e*tending !hread
38 What is the signat/re o4 the constr/ctor o4 a thread classM
5ns 2 !hread9V/nna7le threado7,tring thread1ame8
$8 What are all the methods availa7le in the V/nna7le Inter4aceM
5ns 2 r/n98
58 What is the data t:+e 4or the method is5live98 and this method is
availa7le in ;hich classM
5ns 2 7oolean, !hread
'8 What are all the methods availa7le in the !hread classM
5ns 2 1.is5live98
2.join98
3.res/me98
$.s/s+end98
5.sto+98
'.start98
%.slee+98
-.destro:98
%8 What are all the methods /sed 4or Inter !hread comm/nication and ;hat is the class in ;hich these
methods are de4inedM
5ns 21. ;ait98,noti4:98 W noti4:all98
2. O7ject class
-8 What is the mechanisam de4ind 7: java 4or the Veso/rces to 7e /sed 7: onl: one !hread at a timeM
5ns 2 :nchronisation
08 What is the +roced/re to o;n the moniter 7: man: threadsM
5ns 2 not +ossi7le
1#8 What is the /nit 4or 1### in the 7elo; statementM
o7.slee+91###8
5ns 2 long milliseconds
118 What is the data t:+e 4or the +arameter o4 the slee+98 methodM
5ns 2 long
128 What are all the val/es 4or the 4ollo;ing levelM
ma*A+riorit:
1
minA+riorit:
normalA+riorit:
5ns 2 1#,1,5
138 What is the method availa7le 4or setting the +riorit:M
5ns 2 setPriorit:98
1$8 What is the de4a/lt thread at the time o4 starting the +rogramM
5ns 2 main thread
158 !he ;ord s:nchroni<ed can 7e /sed ;ith onl: a method.
!r/e? (alse
5ns 2 (alse
1'8 Which +riorit: !hread can +rom+t the lo;er +rimar: !hreadM
5ns 2 ,igher Priorit:
1%8 ,o; man: threads at a time can access a monitorM
5ns 2 one
1-8 What are all the 4o/r states associated in the threadM
5ns 2 1. ne; 2. r/nna7le 3. 7loc)ed $. dead
108 !he s/s+end98method is /sed to teriminate a threadM
!r/e ?(alse
5ns 2 (alse
2#8 !he r/n98 method sho/ld necessar: e*ists in clases created as s/7class o4 threadM
!r/e ?(alse
5ns 2 !r/e
218 When t;o threads are ;aiting on each other and canLt +roceed the +rograme is said to 7e in a deadloc)M
!r/e?(alse
5ns 2 !r/e
228 Which method ;aits 4or the thread to die M
5ns 2 join98 method

238 Which o4 the 4ollo;ing is tr/eM
18 ;ait98,noti4:98,noti4:all98 are de4ined as 4inal W can 7e called onl: 4rom ;ith in a s:nchroni<ed method
28 5mong ;ait98,noti4:98,noti4:all98 the ;ait98 method onl: thro;s IOE*ce+tion
38 ;ait98,noti4:98,noti4:all98 W slee+98 are methods o4 o7ject class
1
2
3
1 W 2
1,2 W 3
5ns 2 6
2$8 3ar7age collector thread 7elongs to ;hich +riorit:M
5ns 2 lo;A+riorit:
258 What is meant 7: timeslicing or time sharingM
5ns 2 !imeslicing is the method o4 allocating CPU time to individ/al threads in a +riorit: sched/le.
2'8 What is meant 7: daemon threadM In java r/ntime, ;hat is itLs roleM
5ns 2 6aemon thread is a lo; +riorit: thread ;hich r/ns intermittentl: in the 7ac)gro/nd doing the gar7age
collection o+eration 4or the java r/ntime s:stem.
The followin" example illustrates+
%i> to obser!e the effect of 4oin( ) method in data inconsistency in output.
1
class (ewThread implements Runnable <
)trin" name @ EE name of a thread
Thread t @
(ewThread( )trin" threadname ) <
name ? threadname @
t ? new Thread( this, name ) @
)ystem.out.println('(ew thread+ ' B t ) @
t.start( ) @
A
public !oid run( ) <
try <
for( int i ? : @ i T F @ i ? ? ) <
)ystem.out.println( name B ' > ' B i ) @
Thread.sleep( 9FFF ) @
A
A
catch( Interruptedxception e ) <
e.print)tac2Trace( ) @
A
)ystem.out.println( name B ' exitin"' ) @
A
A
public class Join#emo <
public static !oid main( )trin" ar"s= > ) <
(ewThread ob9 ? new (ewThread( '0ne' ) @
(ewThread ob: ? new (ewThread( 'Two' ) @
(ewThread obH ? new (ewThread( 'Three' ) @
)ystem.out.println( 'Thread 0ne is ali!e+ ' B ob9.t.is5li!e( ) ) @
)ystem.out.println( 'Thread Two is ali!e+ ' B ob:.t.is5li!e( ) ) @
)ystem.out.println( 'Thread Three is ali!e+ ' B obH.t.is5li!e( ) ) @
try <
)ystem.out.println( '-aitin" for threads to finish.' ) @
ob9.t.4oin( ) @ ob:.t.4oin( ) @ obH.t.4oin( ) @
A
catch( Interruptedxception e ) <
e.print)tac2Trace( ) @
A
)ystem.out.println( 'Thread 0ne is ali!e+ ' B ob9.t.is5li!e( ) ) @
)ystem.out.println( 'Thread Two is ali!e+ ' B ob:.t.is5li!e( ) ) @
)ystem.out.println( 'Thread Three is ali!e+ ' B obH.t.is5li!e( ) ) @
)ystem.out.println( 'Main thread is exitin"' ) @
A
A
Typical output when 4oin( ) exists+
(ew thread+Thread= 0ne,J.main >
1
(ew thread+Thread= Two,J,main >
(ew thread+Thread= Three,J,main >
0ne+ :
Two+ :
Thread 0ne is ali!e+ true
Three+ :
Thread Two is ali!e+ true
Thread Three is ali!e+ true
-aitin" for threads to finish.
0ne+ 9
Two+ 9
Three+ 9
0ne exitin"
Three exitin"
Two exitin"
Thread one is ali!e+ false
Thread Two is ali!e+ false
Thread Three is ali!e+ false
)ain thread is e:itin-
Typical output when 4oin( ) 2ept in coents >
(ew thread+Thread= 0ne,J.main >
(ew thread+Thread= Two,J,main >
(ew thread+Thread= Three,J,main >
0ne+ :
Two+ :
Thread 0ne is ali!e+ true
Three+ :
Thread Two is ali!e+ true
Thread Three is ali!e+ true
Thread 0ne is ali!e+ true
Thread Two is ali!e+ true
Thread Three is ali!e+ true
)ain thread is e:itin-
0ne+ 9
Two+ 9
Three+ 9
0ne exitin"
Two exitin"
Three exitin"
In athe abo!e example, with 4oin( ) method, main( ) method( the callin" thread of ob9,
ob: and obH ) waits until ob9, ob: and obH( called threads ) executes their run method. That is why
second set of is5li!e( ) methods prints false. main( ) method is executed at last.
-hen 4oin( ) method is 2ept in comments, main( ) method exits e!en before ob9, ob: and
obH perform their tas2s. -hen callin" thread terminates first, the called threads are in a state of
inconsistency and prints erratic results. In the abo!e example, both sets of is5li!e( ) method prints
true.
BH! +:palin rethrowin- of an e:ception with an e:aple ?
1
*e?throwin- an +:ception >
In the followin" pro"ram, exception is raised in method c ( ) and handled in the same
method. 5fter handlin", it throw the exception ( this is done to illustrate the throw clause ) and search
continues in the hierarchy( that is, in callin" methods). In the hierarchy, the match is found in method a ( ) and is
executed( obser!e the output ).
Re,throwin" can be done for extra functionality from the callin" method. -e can ha!e
output from the catch methods of called and callin" methods.
class Rethrow#emo <
static int count @
static !oid a ( ) <
try <
b ( ) @
A
catch(5rithmeticxception e) <
)ystem.out.println( ' Module9. (umber of times exception raised + ' B
B B count ) @
A
A
static !oid b ( ) <
c ( ) @
A
static !oid c ( ) <
try <
int i ? J, 4 ? F @
)ystem.out.println( i E 4 ) @
A
catch(5rithmeticxception e) <
)ystem.out.println('xception is cau"ht in c ( )+ ' B e) @
throw e @
A
A
public static !oid main()trin" ar"s= > ) <
a ( ) @
A
A
O"tp"t>
xception is cau"ht in c( ). J!aa.lan".5rithmeticxception+ E by 7ero
Module9. (umber of times exception raised+ 9
.8 What threads ;ill start ;hen :o/ start the java +rogramM
58 (inali<er, Main, Ve4erence ,andler, ignal dis+atcher.
.8 !hread
Thread is a smallest unit of dispatchable code.
.8 6i44 +rocess and threadsM
1
58 !hread is a smallest /nit o4 dis+atcha7le code, Process is a s/7 +rogram ;ill +er4orm some s+eci4ic
actions.
9I8 Process is a heav: ;eight tas) and is more cost. 9ii8 !hread is a light;eight tas), ;hich is o4 lo; cost.
9iii8 5 Program can contain more than one thread. 9v8 5 +rogram /nder e*ec/tion is called as +rocess.
.8 lee+98, ;ait98, noti4:98, noti4:5ll98, sto+98, s/s+end98, res/me98
slee+ slee+ 4or a thread /ntil some s+eci4ic amo/nt o4 time.
;ait ;ait 4or a thread /ntil some s+eci4ic condition occ/rs 9Or8 !ells the calling thread to give /+ the
monitor and go to slee+ /ntil some other thread enters the same monitor and calls noti4:98.
noti4:9 8 ;a)es /+ the 4irst thread that called ;ait98 on the same o7ject.
noti4:5ll9 8 ;a)es /+ all the threads that called ;ait98 on the same o7ject, the highest +riorit: thread ;ill
r/n 4irst.
sto+9 8 !he thread move to dead state.
s/s+end9 8 W res/me9 8 !o +ass and restart the e*ec/tion o4 a thread. In case o4 s/s+end, thread ;ill 7e
s/s+ended 7: calling the loc) on the o7ject. Ves/me ;ill restart 4rom ;here it is s/s+ended.
join9 8 ;ait 4or a thread to terminate.
.8 Field9 8
Field method tem+oraril: sto+ the callers thread and +/t at the end o4 @/e/e to ;ait 4or another t/rn to
7e e*ec/ted. It is /sed to ma)e other threads o4 the same +riorit: have the chance to r/n.
!hread.slee+9milliseconds8O
!hread.slee+9milliseconds, nanoseconds8O
.8 M/lti !hreading
M/ltithreading is the mechanism in ;hich more than one thread r/n inde+endent o4 each other ;ithin
the +rocess.
.8 6aemon !hread
6aemon thread is one ;hich serves another thread, it has no other role normall: a daemon thread carr:
some 7ac)gro/nd +rogram. When daemon thread remains the +rogram e*ist.
.8 !hread Priorit:
MI1]PVIOVI!F T 1
1OVM]PVIOVI!F T 5
M5[]PVIOVI!F T 1#
.8 Can I restart a sto++ed threadM
58 Once a thread is sto++ed, it cannot 7e restarted. _ee+ in mind tho/gh that the /se o4 the sto+98 method o4
!hread is de+recated and sho/ld 7e avoided.
.8 !hread Priorities
Class 5 im+lements V/nna7leQ
!hread tO
P/7lic clic)er9int +8Q
! T ne; !hread9this8
t.setPriorit:9+8O
P
1
+/7lic void r/n98Q
P
+/7lic void sto+98Q
P
+/7lic void start98Q
t.start98O
P
tr:Q
thread.slee+91###8O
P
lo.sto+98O
hi.sto+98O
tr:Q
hi.t.join98O
lo.t.join98O
P
class ,iHoQ
+/7lic static void main9tirng argsRS8Q
!hread.c/rrent!hread98.setPriorit:9!hread.M5[]PVIOVI!F8O
Clic)er hi T ne; Clic)er9!hread.1OVM]PVIOVI!FX28O
Clic)er lo T ne; Clic)er9!hread.1OVM]PVIOVI!FA28O
Ho.start98O
,i.start98O
.8 What is the /se o4 start98 4/nction in starting a threadM ;h: ;e do not /se the r/n98 method directl: to r/n
the threadM
tart method tell the &DM that it needs to create a s:stem s+eci4ic thread. 54ter creating the s:stem
reso/rces it +asses the r/nna7le o7ject to it to e*ec/te the r/n98 method.
Calling r/n98 method directl: has the thread e*ec/te in the same as the calling o7ject, not a se+arate thread
o4 e*ec/tion.
.8 What are the di44erent levels o4 loc)ing /sing I:nchroni<eK )e: ;ordM
58 Class level, method level, o7ject level, 7loc) level
.8 Which attri7/te are thread sa4eM
Objective
M/lti !hreaded Model ingle threaded Model
Hocal varia7les F F
Instance varia7les 1 F
Class varia7les 1 1
Ve@/est attri7/tes F F
ession attri7/tes 1 1
Conte*t attri7/tes 1 1
Java Interview uestions
1
:uestion; <hat is the difference between an ,nterface and an (bstract class=

:uestion;
<hat is the purpose of garbage collection in Java, and when is it used=

:uestion; 7escribe synchroni)ation in respect to multithreading.
:uestion; 1xplain different way of using thread=
:uestion; <hat are pass by reference and passby value=
:uestion; <hat is >ashMap and Map=
:uestion; 7ifference between >ashMap and >ashable=
:uestion; 7ifference between Vector and (rray6ist=
:uestion; 7ifference between !wing and (wt=
:uestion; <hat is the difference between a constructor and a method=
:uestion; <hat is an ,terators=
:uestion; !tate the significance of public, private, protected, default modifiers
both singly and in combination and state the effect of pac&age
relationships on declared items ?ualified by these modifiers.
:uestion; <hat is an abstract class=
:uestion; <hat is static in java=
:uestion;
<hat is final=
!
What is the difference between an Interface and an "bstract class?
"!(n abstract class can have instance methods that implement a default
behavior. (n ,nterface can only declare constants and instance methods, but
cannot implement default behavior and all methods are implicitly abstract. (n
interface has all public members and no implementation. (n abstract class is a
class which may have the usual flavors of class members "private, protected,
etc.#, but has some abstract methods.
.
%@
!
What is the purpose of #arba#e collection in Java$ and when is it used?
"!he purpose of garbage collection is to identify and discard objects that are no
longer needed by a program so that their resources can be reclaimed and
reused. ( Java object is subject to garbage collection when it becomes
unreachable to the program in which it is used.
%@
!
%escribe synchronization in respect to multithreadin#&
"!<ith respect to multithreading, synchroni)ation is the capability to control the
access of multiple threads to shared resources. <ithout synchoni)ation, it is
possible for one thread to modify a shared variable while another thread is in
the process of using or updating same shared variable. his usually leads to
significant errors.
%@
!
Explain different way of usin# thread?
"!he thread could be implemented by using runnable interface or by inheriting
from the hread class. he former is more advantageous, .cause when you are
going for multiple inheritance..the only interface can help.
%@
1
!
What are pass by reference and pass by value?
"!@ass 8y Aeference means the passing the address itself rather than passing the
value. @ass by Value means passing a copy of the value to be passed.
%@
!
What is 'ash(ap and (ap?
"!Map is ,nterface and >ashmap is class that implements that.
%@
!
%ifference between 'ash(ap and 'ash)able?
"!he >ashMap class is roughly e?uivalent to >ashtable, except that it is
unsynchroni)ed and permits nulls. ">ashMap allows null values as &ey and
value whereas >ashtable doesnt allow#. >ashMap does not guarantee that the
order of the map will remain constant over time. >ashMap is non synchroni)ed
and >ashtable is synchroni)ed.
%@
!
%ifference between *ector and "rray+ist?
"!Vector is synchroni)ed whereas arraylist is not.
%@
!
%ifference between Swin# and "wt?
"!(< are heavy*weight componenets. !wings are light*weight components.
>ence swing wor&s faster than (<.
%@
!
What is the difference between a constructor and a method?
"!( constructor is a member function of a class that is used to create objects of
that class. ,t has the same name as the class itself, has no return type, and is
invo&ed using the new operator.
( method is an ordinary member function of a class. ,t has its own name, a
return type "which may be void#, and is invo&ed using the dot operator.
%@
!
What is an Iterators?
"!!ome of the collection classes provide traversal of their contents via a
java.util.,terator interface. his interface allows you to wal& a collection of
objects, operating on each object in turn. Aemember when using ,terators that
they contain a snapshot of the collection at the time the ,terator was obtained-
generally it is not advisable to modify the collection itself while traversing an
,terator.
%@
1
!
State the si#nificance of public$ private$ protected$ default modifiers both sin#ly and
in combination and state the effect of packa#e relationships on declared items
,ualified by these modifiers&
"!public : @ublic class is visible in other pac&ages, field is visible everywhere
"class must be public too#
private : @rivate variables or methods may be used only by an instance of the
same class that declares the variable or method, ( private feature may only be
accessed by the class that owns the feature.
protected : ,s available to all classes in the same 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 from the class
that owns the protected feature.
default :<hat you get by default ie, without any access modifier "ie, public
private or protected#.,t means that it is visible to all within a particular
pac&age.
%@
!
What is an abstract class?
"!(bstract class must be extendedBsubclassed "to be useful#. ,t serves as a
template. ( class that is abstract may not be instantiated "ie, you may not call
its constructor#, abstract class may contain static data. (ny class with an
abstract method is automatically abstract itself, and must be declared as such.
( class may be declared abstract even if it has no abstract methods. his
prevents it from being instantiated.
%@
!
What is static in -ava?
"!!tatic means one per class, not one for each object no matter how many
instance of a class might exist. his means that you can use them without
creating an instance of a class. !tatic methods are implicitly final, because
overriding is done based on the type of the object, and static methods are
attached to a class, not an object. ( static method in a superclass can be
shadowed by another static method in a subclass, as long as the original
method was not declared final. >owever, you can.t override a static method
with a nonstatic method. ,n other words, you can.t change a static method into
an instance method in a subclass.
%@
!
What is final?
"!( final class can.t be extended ie., final class may not be subclassed. ( final
method can.t be overridden when its class is inherited. 5ou can.t change value
of a final variable "is a constant

Java Interview uestions
1
:uestion; <hat if the main method is declared as private=
:uestion; <hat if the static modifier is removed from the signature of the main
method=
:uestion; <hat if , write static public void instead of public static void=
:;:uestion;<hat if , do not provide the !tring array as the argument to the
method=
:uestion; <hat is the first argument of the !tring array in main method=
:uestion; ,f , do not provide any arguments on the command line, then the
!tring array of Main method will be empty of null=
:uestion; >ow can one prove that the array is not null but empty=
:uestion; <hat environment variables do , need to set on my machine in order
to be able to run Java programs=
:uestion; Can an application have multiple classes having main method=
:uestion; Can , have multiple main methods in the same class=
:uestion; 7o , need to import java.lang pac&age any time= <hy =
:uestion; Can , import same pac&ageBclass twice= <ill the JVM load the
pac&age twice at runtime=
:uestion; <hat are Chec&ed and 9nChec&ed 1xception=
:uestion; <hat is %verriding=
:uestion; <hat are different types of inner classes=
!
What if the main method is declared as private?
"!he program compiles properly but at runtime it will give +Main method not
public.+ message.
C Aeceived from !andesh !adhaleD %@
!
What if the static modifier is removed from the si#nature of the main method?
"!@rogram compiles. 8ut at runtime throws an error +$o!uchMethod1rror+.
C Aeceived from !andesh !adhaleD %@
!
What if I write static public void instead of public static void?
"!@rogram compiles and runs properly.
C Aeceived from !andesh !adhaleD %@
!
What if I do not provide the Strin# array as the ar#ument to the method?
"!@rogram compiles but throws a runtime error +$o!uchMethod1rror+.
C Aeceived from !andesh !adhaleD %@
!
What is the first ar#ument of the Strin# array in main method?
"!he !tring array is empty. ,t does not have any element. his is unli&e CBCEE
where the first element by default is the program name.
C Aeceived from !andesh !adhaleD %@
!
If I do not provide any ar#uments on the command line$ then the Strin# array of
(ain method will be empty of null?
"!,t is empty. 8ut not null.
C Aeceived from !andesh !adhaleD %@
!
'ow can one prove that the array is not null but empty?
"!@rint args.length. ,t will print F. hat means it is empty. 8ut if it would have
been null then it would have thrown a $ull@ointer1xception on attempting to
print args.length.
C Aeceived from !andesh !adhaleD %@
1
!
What environment variables do I need to set on my machine in order to be able to
run Java pro#rams?
"!C6(!!@(> and @(> are the two variables.
C Aeceived from !andesh !adhaleD %@
!
Can an application have multiple classes havin# main method?
"!5es it is possible. <hile starting the application we mention the class name to
be run. he JVM will loo& for the Main method only in the class whose name
you have mentioned. >ence there is not conflict amongst the multiple classes
having main method.
C Aeceived from !andesh !adhaleD %@
!
Can I have multiple main methods in the same class?
"!$o the program fails to compile. he compiler says that the main method is
already defined in the class.
C Aeceived from !andesh !adhaleD %@
!
%o I need to import -ava&lan# packa#e any time? Why ?
"!$o. ,t is by default loaded internally by the JVM.
C Aeceived from !andesh !adhaleD %@
!
Can I import same packa#e.class twice? Will the J*( load the packa#e twice at
runtime?
"!%ne can import the same pac&age or same class multiple times. $either
compiler nor JVM complains abt it. (nd the JVM will internally load the class
only once no matter how many times you import the same class.
C Aeceived from !andesh !adhaleD %@
!
What are Checked and /nChecked Exception?
"!( chec&ed exception is some subclass of 1xception "or 1xception itself#,
excluding class Auntime1xception and its subclasses.
Ma&ing an exception chec&ed forces client programmers to deal with the
possibility that the exception will be thrown. eg, ,%1xception thrown by
java.io.'ile,nput!tream.s read"# methodG
9nchec&ed exceptions are Auntime1xception and any of its subclasses. Class
1rror and its subclasses also are unchec&ed. <ith an unchec&ed exception,
however, the compiler doesn.t force client programmers either to catch the
exception or declare it in a throws clause. ,n fact, client programmers may not
even &now that the exception could be thrown. eg,
!tring,ndex%ut%f8ounds1xception thrown by !tring.s char(t"# methodG
Chec&ed exceptions must be caught at compile time. Auntime exceptions do
not need to be. 1rrors often cannot be.
%@
!
What is 0verridin#?
"!<hen a class defines a method using the same name, return type, and
arguments as a method in its superclass, the method in the class overrides the
method in the superclass.
<hen the method is invo&ed for an object of the class, it is the new definition
of the method that is called, and not the method definition from superclass.
Methods may be overridden to be more public, not more private.
%@
1
!
What are different types of inner classes?
"!Nested top-level classes, Member classes, Local classes, Anonymous classes
Nested top-level classes* ,f you declare a class within a class and specify the static
modifier, the compiler treats the class just li&e any other top*level class.
(ny class outside the declaring class accesses the nested class with the declaring class name
acting similarly to a pac&age. eg, outer.inner. op*level inner classes implicitly have access only
to static variables.here can also be inner interfaces. (ll of these are of the nested top*level
variety.
Member classes * Member inner classes are just li&e other member methods and member
variables and access to the member class is restricted, just li&e methods and variables. his
means a public member class acts similarly to a nested top*level class. he primary difference
between member classes and nested top*level classes is that member classes have access to
the specific instance of the enclosing class.
Local classes * 6ocal classes are li&e local variables, specific to a bloc& of code. heir
visibility is only within the bloc& of their declaration. ,n order for the class to be useful beyond
the declaration bloc&, it would need to implement a
more publicly available interface.8ecause local classes are not members, the modifiers public,
protected, private, and static are not usable.
Anonymous classes * (nonymous inner classes extend local inner classes one level further.
(s anonymous classes have no name, you cannot provide a constructor.


Java Interview uestions
:uestion;(re the imports chec&ed for validity at compile time= e.g. will the code
containing an import such as java.lang.(8C7 compile=
:uestion;7oes importing a pac&age imports the subpac&ages as well= e.g. 7oes
importing com.Myest.H also import com.Myest.9nitests.H=
:uestion;<hat is the difference between declaring a variable and defining a variable=
:uestion;<hat is the default value of an object reference declared as an instance
variable=
:uestion;Can a top level class be private or protected=
:uestion;<hat type of parameter passing does Java support=
:uestion;@rimitive data types are passed by reference or pass by value=
:uestion;%bjects are passed by value or by reference=
:uestion;<hat is seriali)ation=
:uestion;>ow do , seriali)e an object to a file=
:uestion;<hich methods of !eriali)able interface should , implement=
:uestion;>ow can , customi)e the serali)ation process= i.e. how can one have a
control over the seriali)ation process=
:uestion;<hat is the common usage of seriali)ation=
:uestion;<hat is 1xternali)able interface=
:uestion;<hat happens to the object references included in the object seriali)ed=
:uestion;<hat one should ta&e care of while seriali)ing the object=
:uestion;<hat happens to the static fields of a class during seriali)ation=
1

!
"re the imports checked for validity at compile time? e&#& will the code containin# an
import such as -ava&lan#&"1C% compile?
"! 5es the imports are chec&ed for the semantic validity at compile time. he code
containing above line of import will not compile. ,t will throw an error saying,can not
resolve symbol
symbol ; class (8C7
location; pac&age io
import java.io.(8C7-
C Aeceived from !andesh !adhaleD %@
!
%oes importin# a packa#e imports the subpacka#es as well? e&#& %oes importin#
com&(y)est&2 also import com&(y)est&/nit)ests&2?
"! $o you will have to import the subpac&ages explicitly. ,mporting com.Myest.H will
import classes in the pac&age Myest only. ,t will not import any class in any of it.s
subpac&age.
C Aeceived from !andesh !adhaleD %@
!
What is the difference between declarin# a variable and definin# a variable?
"! ,n declaration we just mention the type of the variable and it.s name. <e do not
initiali)e it. 8ut defining means declaration E initiali)ation.
e.g !tring s- is just a declaration while !tring s I new !tring "+abcd+#- %r !tring s I
+abcd+- are both definitions.
C Aeceived from !andesh !adhaleD %@
!
What is the default value of an ob-ect reference declared as an instance variable?
"! null unless we define it explicitly.
C Aeceived from !andesh !adhaleD %@
!
Can a top level class be private or protected?
"! $o. ( top level class can not be private or protected. ,t can have either +public+ or
no modifier. ,f it does not have a modifier it is supposed to have a default access.,f a
top level class is declared as private the compiler will complain that the +modifier
private is not allowed here+. his means that a top level class can not be private.
!ame is the case with protected.
C Aeceived from !andesh !adhaleD %@
!
What type of parameter passin# does Java support?
"! ,n Java the arguments are always passed by value .
C 9pdate from 1&i and Jyothish VenuD %@
!
3rimitive data types are passed by reference or pass by value?
"! @rimitive data types are passed by value.
C Aeceived from !andesh !adhaleD %@
!
0b-ects are passed by value or by reference?
"! Java only supports pass by value. <ith objects, the object reference itself is passed
1
by value and so both the original reference and parameter copy both refer to the
same object .
C 9pdate from 1&i and Jyothish VenuD %@
!
What is serialization?
"! !eriali)ation is a mechanism by which you can save the state of an object by
converting it to a byte stream.
C Aeceived from !andesh !adhaleD %@
!
'ow do I serialize an ob-ect to a file?
"! he class whose instances are to be seriali)ed should implement an interface
!eriali)able. hen you pass the instance to the %bject%utput!tream which is
connected to a fileoutputstream. his will save the object to a file.
C Aeceived from !andesh !adhaleD %@
!
Which methods of Serializable interface should I implement?
"! he seriali)able interface is an empty interface, it does not contain any methods. !o
we do not implement any methods.
C Aeceived from !andesh !adhaleD %@
!
'ow can I customize the seralization process? i&e& how can one have a control over the
serialization process?
"! 5es it is possible to have control over seriali)ation process. he class should
implement 1xternali)able interface. his interface contains two methods namely
read1xternal and write1xternal. 5ou should implement these methods and write the
logic for customi)ing the seriali)ation process.
C Aeceived from !andesh !adhaleD %@
!
What is the common usa#e of serialization?
"! <henever an object is to be sent over the networ&, objects need to be seriali)ed.
Moreover if the state of an object is to be saved, objects need to be serila)ed.
C Aeceived from !andesh !adhaleD %@
!
What is Externalizable interface?
"! 1xternali)able is an interface which contains two methods read1xternal and
write1xternal. hese methods give you a control over the seriali)ation mechanism.
hus if your class implements this interface, you can customi)e the seriali)ation
process by implementing these methods.
C Aeceived from !andesh !adhaleD %@
!
What happens to the ob-ect references included in the ob-ect?
"! he seriali)ation mechanism generates an object graph for seriali)ation. hus it
determines whether the included object references are seriali)able or not. his is a
recursive process. hus when an object is seriali)ed, all the included objects are also
seriali)ed alongwith the original obect.
C Aeceived from !andesh !adhaleD %@
!
What one should take care of while serializin# the ob-ect?
1
"! %ne should ma&e sure that all the included objects are also seriali)able. ,f any of the
objects is not seriali)able then it throws a $ot!eriali)able1xception.
C Aeceived from !andesh !adhaleD %@
!
What happens to the static fields of a class durin# serialization?
"!
here are three exceptions in which seriali)ation doesnot necessarily read and write to the stream.
hese are
0. !eriali)ation ignores static fields, because they are not part of ay particular state state.
2. 8ase class fields are only hendled if the base class itself is seriali)able.
3. ransient fields.
C Aeceived from !andesh !adhale Modified after @.John 7avid comments.D %@

:uestion;7oes Java provide any construct to find out the si)e of an object=
:uestion;Give a simplest way to find out the time a method ta&es for execution
without using any profiling tool=
:uestion;<hat are wrapper classes=
:uestion;<hy do we need wrapper classes=
:uestion;<hat are chec&ed exceptions=
:uestion;<hat are runtime exceptions=
:uestion;<hat is the difference between error and an exception==
:uestion;>ow to create custom exceptions=
:uestion;,f , want an object of my class to be thrown as an exception object, what
should , do=
:uestion;,f my class already extends from some other class what should , do if , want
an instance of my class to be thrown as an exception object=
:uestion;<hat happens to an unhandled exception=
:uestion;>ow does an exception permeate through the code=
:uestion;<hat are the different ways to handle exceptions=
:uestion;<hat is the basic difference between the 2 approaches to exception
handling...0/ try catch bloc& and 2/ specifying the candidate exceptions in
the throws clause=
<hen should you use which approach=
:uestion;,s it necessary that each try bloc& must be followed by a catch bloc&=
:uestion;,f , write return at the end of the try bloc&, will the finally bloc& still execute=
:uestion;,f , write !ystem.exit "F#- at the end of the try bloc&, will the finally bloc& still
execute=

!
%oes Java provide any construct to find out the size of an ob-ect?
"! $o there is not si)eof operator in Java. !o there is not direct way to determine the
si)e of an object directly in Java.
C Aeceived from !andesh !adhaleD %@
!
%oes importin# a packa#e imports the subpacka#es as well? e&#& %oes importin#
com&(y)est&2 also import com&(y)est&/nit)ests&2?
"! Aead the system time just before the method is invo&ed and immediately after
method returns. a&e the time difference, which will give you the time ta&en by a
1
method for execution.
o put it in code...
long start I !ystem.currentimeMillis "#-
method "#-
long end I !ystem.currentimeMillis "#-
!ystem.out.println "+ime ta&en for execution is + E "end * start##-
Aemember that if the time ta&en for execution is too small, it might show that it is ta&ing )ero
milliseconds for execution. ry it on a method which is big enough, in the sense the one which is
doing considerable amout of processing.
C Aeceived from !andesh !adhaleD %@
!
What are wrapper classes?
"! Java provides speciali)ed classes corresponding to each of the primitive data types.
hese are called wrapper classes. hey are e.g. ,nteger, Character, 7ouble etc.
C Aeceived from !andesh !adhaleD %@
!
Why do we need wrapper classes?
"! ,t is sometimes easier to deal with primitives as objects. Moreover most of the
collection classes store objects and not primitive data types. (nd also the wrapper
classes provide many utility methods also. 8ecause of these resons we need
wrapper classes. (nd since we create instances of these classes we can store them
in any of the collection classes and pass them around as a collection. (lso we can
pass them around as method parameters where a method expects an object.
C Aeceived from !andesh !adhaleD %@
!
What are checked exceptions?
"! Chec&ed exception are those which the Java compiler forces you to catch. e.g.
,%1xception are chec&ed 1xceptions.
C Aeceived from !andesh !adhaleD %@
!
What are runtime exceptions?
"! Auntime exceptions are those exceptions that are thrown at runtime because of
either wrong input data or because of wrong business logic etc. hese are not
chec&ed by the compiler at compile time.
C Aeceived from !andesh !adhaleD %@
!
What is the difference between error and an exception?
"! (n error is an irrecoverable condition occurring at runtime. !uch as %ut%fMemory
error. hese JVM errors and you can not repair them at runtime. <hile exceptions
are conditions that occur because of bad input etc. e.g. 'ile$ot'ound1xception will
be thrown if the specified file does not exist. %r a $ull@ointer1xception will ta&e
place if you try using a null reference. ,n most of the cases it is possible to recover
from an exception "probably by giving user a feedbac& for entering proper values
etc.#.
C Aeceived from !andesh !adhaleD %@
1
!
'ow to create custom exceptions?
"! 5our class should extend class 1xception, or some more specific type thereof.
C Aeceived from !andesh !adhaleD %@
!
If I want an ob-ect of my class to be thrown as an exception ob-ect$ what should I do?
"! he class should extend from 1xception class. %r you can extend your class from
some more precise exception type also.
C Aeceived from !andesh !adhaleD %@
!
If my class already extends from some other class what should I do if I want an instance
of my class to be thrown as an exception ob-ect?
"! %ne can not do anytihng in this scenarion. 8ecause Java does not allow multiple
inheritance and does not provide any exception interface as well.
C Aeceived from !andesh !adhaleD %@
!
What happens to an unhandled exception?
"! %ne can not do anytihng in this scenarion. 8ecause Java does not allow multiple
inheritance and does not provide any exception interface as well.
C Aeceived from !andesh !adhaleD %@
!
'ow does an exception permeate throu#h the code?
"! (n unhandled exception moves up the method stac& in search of a matching <hen
an exception is thrown from a code which is wrapped in a try bloc& followed by one
or more catch bloc&s, a search is made for matching catch bloc&. ,f a matching type
is found then that bloc& will be invo&ed. ,f a matching type is not found then the
exception moves up the method stac& and reaches the caller method. !ame
procedure is repeated if the caller method is included in a try catch bloc&. his
process continues until a catch bloc& handling the appropriate type of exception is
found. ,f it does not find such a bloc& then finally the program terminates.
C Aeceived from !andesh !adhaleD %@
!
What are the different ways to handle exceptions?
"! here are two ways to handle exceptions,
0. 8y wrapping the desired code in a try bloc& followed by a catch bloc& to catch the
exceptions. and
2. 6ist the desired exceptions in the throws clause of the method and let the caller of
the method hadle those exceptions.
C Aeceived from !andesh !adhaleD %@
!
! What is the basic difference between the 4 approaches to exception handlin#&&&56 try
catch block and 46 specifyin# the candidate exceptions in the throws clause?
When should you use which approach?
"! ,n the first approach as a programmer of the method, you urself are dealing with the
exception. his is fine if you are in a best position to decide should be done in case
of an exception. <hereas if it is not the responsibility of the method to deal with it.s
own exceptions, then do not use this approach. ,n this case use the second
approach. ,n the second approach we are forcing the caller of the method to catch
1
the exceptions, that the method is li&ely to throw. his is often the approach library
creators use. hey list the exception in the throws clause and we must catch them.
5ou will find the same approach throughout the java libraries we use.
C Aeceived from !andesh !adhaleD %@
!
Is it necessary that each try block must be followed by a catch block?
"! ,t is not necessary that each try bloc& must be followed by a catch bloc&. ,t should
be followed by either a catch bloc& %A a finally bloc&. (nd whatever exceptions are
li&ely to be thrown should be declared in the throws clause of the method.
C Aeceived from !andesh !adhaleD %@
!
If I write return at the end of the try block$ will the finally block still execute?
"! 5es even if you write return as the last statement in the try bloc& and no exception
occurs, the finally bloc& will execute. he finally bloc& will execute and then the
control return.
C Aeceived from !andesh !adhaleD %@
!
If I write System&exit 789: at the end of the try block$ will the finally block still execute?
"! $o in this case the finally bloc& will not execute because when you say !ystem.exit
"F#- the control immediately goes out of the program, and thus finally never
executes.
C Aeceived from !andesh !adhaleD %@

Java Interview uestions
:uestion;>ow are %bserver and %bservable used=
:uestion;<hat is synchroni)ation and why is it important=
:uestion;>ow does Java handle integer overflows and underflows=
:uestion;7oes garbage collection guarantee that a program will not run out of
memory=
:uestion;<hat is the difference between preemptive scheduling and time slicing=
:uestion;<hen a thread is created and started, what is its initial state=
:uestion;<hat is the purpose of finali)ation=
:uestion;<hat is the 6ocale class=
:uestion;<hat is the difference between a while statement and a do statement=
:uestion;<hat is the difference between static and non*static variables=
:uestion;>ow are this"# and super"# used with constructors=
:uestion;<hat are synchroni)ed methods and synchroni)ed statements=
:uestion;<hat is daemon thread and which method is used to create the daemon
thread=
:uestion;Can applets communicate with each other=
:uestion;<hat are the steps in the J78C connection=
:uestion;>ow does a try statement determine which catch clause should be used
to handle an exception=


1
!
'ow are 0bserver and 0bservable used?
"!%bjects that subclass the %bservable class maintain a list of observers. <hen
an %bservable object is updated it invo&es the update"# method of each of its
observers to notify the observers that it has changed state. he %bserver
interface is implemented by objects that observe %bservable objects.
CAeceived from Ven&ateswara ManamD %@
!
What is synchronization and why is it important?
"!<ith respect to multithreading, synchroni)ation is the capability to control
the access of multiple threads to shared resources. <ithout synchroni)ation, it
is possible for one thread to modify a shared object while another thread is in
the process of using or updating that object.s value. his often leads to
significant errors.
C Aeceived from Ven&ateswara ManamD %@
!
'ow does Java handle inte#er overflows and underflows?
"!,t uses those low order bytes of the result that can fit into the si)e of the type
allowed by the operation.
C Aeceived from Ven&ateswara ManamD %@
!
%oes #arba#e collection #uarantee that a pro#ram will not run out of memory?
"!Garbage collection does not guarantee that a program will 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 objects
that are not subject to garbage collection
.
C Aeceived from Ven&ateswara ManamD %@
!
What is the difference between preemptive schedulin# and time slicin#?
"!9nder preemptive scheduling, the highest priority tas& executes until it enters
the waiting or dead states or a higher priority tas& comes into existence. 9nder
time slicing, a tas& executes for a predefined slice of time and then reenters
the pool of ready tas&s. he scheduler then determines which tas& should
execute next, based on priority and other factors.
C Aeceived from Ven&ateswara ManamD %@
!
When a thread is created and started$ what is its initial state?
"!( thread is in the ready state after it has been created and started.
C Aeceived from Ven&ateswara ManamD %@
!
What is the purpose of finalization?
"!he purpose of finali)ation is to give an unreachable object the opportunity to
perform any cleanup processing before the object is garbage collected.
C Aeceived from Ven&ateswara ManamD %@
!
What is the +ocale class?
"!he 6ocale class is used to tailor program output to the conventions of a
particular geographic, political, or cultural region.
C Aeceived from Ven&ateswara ManamD %@
1
!
What is the difference between a while statement and a do statement?
"!( while statement chec&s at the beginning of a loop to see whether the next
loop iteration should occur. ( do statement chec&s at the end of a loop to see
whether the next iteration of a loop should occur. he do statement will always
execute the body of a loop at least once.
C Aeceived from Ven&ateswara ManamD %@
!
What is the difference between static and non;static variables?
"!( static variable is associated with the class as a whole rather than with
specific instances of a class. $on*static variables ta&e on uni?ue values with
each object instance.
C Aeceived from Ven&ateswara ManamD %@
!
'ow are this79 and super79 used with constructors?
"!%this"# is used to invo&e a constructor of the same class. super"# is used to
invo&e a superclass constructor.
C Aeceived from Ven&ateswara ManamD %@
!
What are synchronized methods and synchronized statements?
"!!ynchroni)ed methods are methods that are used to control access to an
object. ( thread only executes a synchroni)ed method after it has ac?uired the
loc& for the method.s object or class. !ynchroni)ed statements are similar to
synchroni)ed methods. ( synchroni)ed statement can only be executed after a
thread has ac?uired the loc& for the object or class referenced in the
synchroni)ed statement.
C Aeceived from Ven&ateswara ManamD %@
!
What is daemon thread and which method is used to create the daemon thread?
"!7aemon thread is a low priority thread which runs intermittently in the bac&
ground doing the garbage collection operation for the java runtime system.
set7aemon method is used to create a daemon thread.
C Aeceived from !hipra JamraD %@
!
Can applets communicate with each other?
"!(t this point in time applets may communicate with other applets running in
the same virtual machine. ,f the applets are of the same class, they can
communicate via shared static variables. ,f the applets are of different classes,
then each will need a reference to the same class with static variables. ,n any
case the basic idea is to pass the information bac& and forth through a static
variable.
(n applet can also get references to all other applets on the same page using
the get(pplets"# method of java.applet.(ppletContext. %nce youK.ve got a
reference to an applet, you can communicate with it by using its public
members.
,t is conceivable to have applets in different virtual machines that tal& to a
server somewhere on the ,nternet and store any data that needs to be
seriali)ed there. hen, when another applet needs this data, it could connect to
this same server. ,mplementing this is non*trivial.
C Aeceived from Jrishna Jumar D %@
1
!
What are the steps in the J%1C connection?
"! <hile ma&ing a J78C connection we go through the following steps ;
!tep 0 ; Aegister the database driver by using ;
Class.for$ame"K+ driver classs for that specific databaseK+ #-
!tep 2 ; $ow create a database connection using ;
Connection con I 7riverManager.getConnection"url,username,password#-
!tep 3; $ow Create a ?uery using ;
!tatement stmt I Connection.!tatement"K+select H from (861 $(M1K+#-
!tep 4 ; 1xceute the ?uery ;
stmt.exceute9pdate"#-
C Aeceived from !hri @ra&ash JunwarD %@
!
'ow does a try statement determine which catch clause should be used to handle an
exception?
"!
<hen an exception is thrown within the body of a try statement, the catch clauses of the try
statement are examined in the order in which they appear. he first catch clause that is
capable of handling the exceptionis executed. he remaining catch clauses are ignored.

Java Interview uestions
:uestion;Can an unreachable object become reachable again=
:uestion;<hat method must be implemented by all threads=
:uestion;<hat are synchroni)ed methods and synchroni)ed statements=
:uestion;<hat is 1xternali)able=
:uestion;<hat modifiers are allowed for methods in an ,nterface=
:uestion;<hat are some alternatives to inheritance=
:uestion;<hat does it mean that a method or field is +static+= =
:uestion;<hat is the difference between preemptive scheduling and time slicing=
:uestion;<hat is the catch or declare rule for method declarations=


!
Can an unreachable ob-ect become reachable a#ain?
"! (n unreachable object may become reachable again. his can happen when the
object.s finali)e"# method is invo&ed and the object performs an operation which
causes it to become accessible to reachable objects.
CAeceived from @ AajeshD %@
!
What method must be implemented by all threads?
"! (ll tas&s must implement the run"# method, whether they are a subclass of hread
1
or implement the Aunnable interface.
C Aeceived from @ AajeshD %@
!
What are synchronized methods and synchronized statements?
"! !ynchroni)ed methods are methods that are used to control access to an object. (
thread only executes a synchroni)ed method after it has ac?uired the loc& for the
method.s object or class. !ynchroni)ed statements are similar to synchroni)ed
methods. ( synchroni)ed statement can only be executed after a thread has
ac?uired the loc& for the object or class referenced in the synchroni)ed statement.
C Aeceived from @ AajeshD %@
!
What is Externalizable?
"! 1xternali)able is an ,nterface that extends !eriali)able ,nterface. (nd sends data
into !treams in Compressed 'ormat. ,t has two methods, write1xternal"%bject%uput
out# and read1xternal"%bject,nput in#
C Aeceived from Ven&ateswara ManamD %@
!
What modifiers are allowed for methods in an Interface?
"! %nly public and abstract modifiers are allowed for methods in interfaces.
C Aeceived from @ AajeshD %@
!
What are some alternatives to inheritance?
"! 7elegation is an alternative to inheritance. 7elegation means that you include an
instance of another class as an instance variable, and forward messages to the
instance. ,t is often safer than inheritance because it forces you to thin& about each
message 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 methods of the super class;
you can provide only the methods that really ma&e sense. %n the other hand, it
ma&es you write more code, and it is harder to re*use "because it is not a subclass#.
C Aeceived from @ AajeshD %@
!
What does it mean that a method or field is <static<?
"! !tatic variables and methods are instantiated only once per class. ,n other words
they are class variables, not instance variables. ,f you change the value of a static
variable in a particular object, the value of that variable changes for all instances of
that class.
!tatic methods can be referenced with the name of the class rather than the name of a particular
object of the class "though that wor&s too#. hat.s how library methods li&e !ystem.out.println"# wor&
out is a static field in the java.lang.!ystem class.
C Aeceived from @ AajeshD %@
!
What is the difference between preemptive schedulin# and time slicin#?
"! 9nder preemptive scheduling, the highest priority tas& executes until it enters the
waiting or dead states or a higher priority tas& comes into existence. 9nder time
slicing, a tas& executes for a predefined slice of time and then reenters the pool of
ready tas&s. he scheduler then determines which tas& should execute next, based
1
on priority and other factors.
C Aeceived from @ AajeshD %@
!
What is the catch or declare rule for method declarations?
"! ,f a chec&ed exception may be thrown within the body of a method, the method
must either catch the exception or declare it in its throws clause.
C Aeceived from @ AajeshD %@
%ll .ac9a-es
java!lan- .ac9a-e
nterfaces Classes Exceptions
Clonea"le ;ou"le3 :loat3 8ong3
nteger3 5hort3 1%te3
1oolean3 Character3
5rithmeticE*ce+tion,
5rra:Inde*O/tO4Bo/ndO4.E,
ClassCast.E, Class1ot(o/nd.E
Runna"le Class3 Class8oader lleAcess'E3 llegalArgument'E
Compara"le Brocess3 Run4ime3 6oid llegal5ate'E3 9ullBointer'E
5tring3 5tring1uffer 9o5uch:ield'E3 9o5uch2ethod'E
4hread3 4hreadGroup 9um"er:ormat'E
java!(O .ac9a-e
nterfaces Classes Exceptions
;atanputstream 1uffernputstream3
1uffer)utput5tream
;ata)utputstream 1ufferReader3 1uffer#riter
)"jectnput5tream 1%teArra%nput5tream3
1%teArra%)utputstream
)"ject)utputstream Characterarra%Reader3
CharacterAra%#riter
5eriali(a"le ;atanput5tream3 ;ata)utput5tream
Externiali(a"le :ilereader3 :ile#riter
)"jectnput5tream3
)"ject)utput5tream
Object class
5ll other classes are s/7 classes o4 o7ject class, O7ject class is a s/+er class o4 all other class.
Methods2 A
void noti4:98 void noti4:5ll98
O7ject clone98 ting totring98
7oolean e@/als9O7ject o7ject8 void ;ait98
void 4inali<e98 void ;ait9long milliseconds, int
nanoseconds8
int hashcode98
1
$hread class
Methods2 A
get1ame98 r/n98
getPriorit:98 lee+98
is5live98 tart98
join98
throwable class
Methods2 A
5tring
get2essage()
6oid print5tac&4race()
5tring to5tring() 4hro$a"le filln5tac&4race()
java!s=l .ac9a-e
nterfaces Classes Exceptions
Connection ;river2anager
Calla"le5tatement ;ate Class9ot:oundExcept
ion
;river 4ime5tamp nstantiation
Exception
Brepared5tatement 4ime
Result5et 4%pes
Result5et2eta;ata 5.8 Exception3 5.8
#arnings
5tatement
;ata"ase2eta;ata
Arra%
Barameter2eta;ata
Clo"3 1lo"
5.8nput3 5.8)utput3
5.8Bermission
5avepoint
java:!s=l .ac9a-e
Inter4aces
Classes Exceptions
ConnectionEvent8istener
ConnectionEvent
ConnectionBool;ata5ource Ro$setEvent
;ata5ource
BooledConnection
Ro$5et
Ro$5et8istener
Ro$5et2eta;ate
Ro$5etReaderC#riter
DAConnection
DA;ata5ource
Java:!servlet .ac9a-e
nterfaces Classes Exceptions
5ervlet Generic5ervlet 5ervletException
5ervletConfig 5ervletnput5tream Unavalia"leExcep
tion
5ervletContext 5ervlet)utput5tream
1
5ervletRe=uest 5ervletContextAttri"ute
Event
5ervletResponse
5ingle4hread2odel
5ervletContext8istener
5ervletContextAttri"ute8istener
5ervletContextnitiali(ation
parameters
5ervletRe=uestAttri"ute8istener
5ervletRe=uest8istner
:ilter
:ilterChain
:ilterConfig
Re=uest;ispatcher
3enericervlet 9C8 +/7lic void destro:98O
+/7lic tring getInitParameter9tring name8O
+/7lic En/meration getInitParameter1ames98O
+/7lic ervletCon4ig getervletCon4ig98O
+/7lic ervletConte*t getervletConte*t98O
+/7lic tring getervletIn4o98O
+/7lic void init9ervletCon4ig con4ig8 thro;s ervletE*ce+tionO
+/7lic void log9tring msg8O
+/7lic a7stract void service9ervletVe@/est re@, ervletVes+onse res8
ervletIn+/ttream 9C8 +/7lic int readHine97:te 7RS, int o44, int len8
ervletO/t+/ttream 9C8 +/7lic void +rint9tring s8 thro;s IOE*ce+tionO
+/7lic void +rintln98 thro;s IOE*ce+tionO
5ervletContextAttri"uteEvent (C) pu"lic void
attri"uteAdded(5ervletContextAttri"uteEvent sca")
pu"lic void
attri"uteRemoved(5ervletContextAttri"uteEvent sca")
pu"lic void
attri"uteReplaced(5ervletContextAttri"uteEvent sca")
ervlet 9I8 +/7lic a7stract void destro:98O
+/7lic a7stract ervletCon4ig getervletCon4ig98O
+/7lic a7stract tring getervletIn4o98O
+/7lic a7stract void init9ervletCon4ig con4ig8 thro;s ervletE*ce+tionO
+/7lic a7stract void service9ervletVe@/est re@, ervletVes+onse res8
ervletCon4ig 9I8 +/7lic a7stract tring getInitParameter9tring name8O
+/7lic a7stract En/meration getInitParameter1ames98O
+/7lic a7stract ervletConte*t getervletConte*t98O
ervletConte*t 9I8 +/7lic a7stract O7ject get5ttri7/te9tring name8O
+/7lic a7stract tring getVealPath9tring +ath8O
+/7lic a7stract tring geterverIn4o98O
+/7lic a7stract ervlet getervlet9tring name8 thro;s ervletE*ce+tionO
+/7lic a7stract En/meration getervlet1ames98O
+/7lic a7stract En/meration getervlets98O
1
+/7lic a7stract void log9E*ce+tion e*ce+tion, tring msg8O
ervletVe@/est 9I8 +/7lic a7stract O7ject get5ttri7/te9tring name8O
+/7lic a7stract tring getParameter9tring name8O
+/7lic a7stract En/meration getParameter1ames98O
+/7lic a7stract tringRS getParameterDal/es9tring name8O
+/7lic a7stract tring getVealPath9tring +ath8O
+/7lic a7stract tring getVemote5ddr98O
+/7lic a7stract tring getVemote,ost98O
+/7lic a7stract tring geterver1ame98O
+/7lic a7stract int geterverPort98O
Ve@/est6is+atcher getVe@/est6is+atcher9tring +ath8O
+/7lic int getHocalPort98O ?? servlet 2.$
+/7lic int getVemotePort98O ?? servlet 2.$
+/7lic tring getHocal1ame98O ?? servlet 2.$
+/7lic tring getHocal5ddr98O ?? servlet 2.$
ervletVes+onse 9I8 +/7lic a7stract tring getCharacterEncoding98O
+/7lic a7stract PrintWriter getWriter98 thro;s IOE*ce+tionO
+/7lic a7stract void setContentHength9int len8O
+/7lic a7stract void setContent!:+e9tring t:+e8O
Java:!servlet!2ttp .ac9a-e
nterfaces Classes Exceptions
7ttp5ervletRe=uest Coo&ies 5ervletException
7ttp5ervletResponse 7ttp5ervlet (A"starct
Class)
Unavalia"leException
7ttp5ession 7ttpUtils
7ttp5ession8istener 7ttp5ession1indingEvent
7ttp5essionActivation8istener
7ttp5essionAttri"ute8istener
7ttp5ession1inding8istener
7ttp5essionContext
(deprecated)
:ilter
ervletConte*tHistener 9I8 +/7lic void conte*tInitiali<ed9ervletConte*tEvent event8
+/7lic void conte*t6estro:ed9ervletConte*tEvent event8
ervletConte*t5ttri7/teHistener 9I8 +/7lic void attri7/te5dded9ervletConte*t5ttri7/teEvent sca78
+/7lic void attri7/teVemoved9ervletConte*t5ttri7/teEvent sca78
+/7lic void attri7/teVe+laced9ervletConte*t5ttri7/teEvent sca78
ervletConte*tInitila<ation +arameters
Coo9ies #C) p"blic Object clone#)I
+/7lic int getMa*5ge98O
+/7lic tring get1ame98O
+/7lic tring getPath98O
+/7lic tring getDal/e98O
+/7lic int getDersion98O
+/7lic void setMa*5ge9int e*+ir:8O
1
+/7lic void setPath9tring /ri8O
+/7lic void setDal/e9tring ne;Dal/e8O
+/7lic void setDersion9int v8O
,tt+ervlet 9C8 +/7lic void service9ervletVe@/est re@, ervletVes+onse res8
+rotected void do6elete 9,tt+ervletVe@/est re@, ,tt+ervletVes+onse res8
+rotected void do3et 9,tt+ervletVe@/est re@, ,tt+ervletVes+onse res8
+rotected void doO+tions9,tt+ervletVe@/est re@, ,tt+ervletVes+onse res8
+rotected void doPost9,tt+ervletVe@/est re@, ,tt+ervletVes+onse res8
+rotected void doP/t9,tt+ervletVe@/est re@, ,tt+ervletVes+onse res8
+rotected void do!race9,tt+ervletVe@/est re@, ,tt+ervletVes+onse res8
+rotected long getHastModi4ied9,tt+ervletVe@/est re@8O
+rotected void service9,tt+ervletVe@/est re@, ,tt+ervletVes+onse res8
,tt+ession7indingEvent 9C8 +/7lic tring get1ame98O
+/7lic ,tt+ession getession98O
,tt+ervletVe@/est 9I8 +/7lic a7stract Coo)ieRS getCoo)ies98O
+/7lic a7stract tring get,eader9tring name8O
+/7lic a7stract En/meration get,eader1ames98O
+/7lic a7stract tring get./er:tring98O
+/7lic a7stract tring getVemoteUser98O
+/7lic a7stract tring getVe@/estedessionId98O
+/7lic a7stract tring getVe@/estUVI98O
+/7lic a7stract tring getervletPath98O
+/7lic a7stract ,tt+ession getession97oolean create8O
+/7lic a7stract 7oolean isVe@/estedessionId(romCoo)ie98O
+/7lic a7stract 7oolean isVe@/estedessionId(romUrl98O
+/7lic a7stract 7oolean isVe@/estedessionIdDalid98O
,tt+ervletVes+onse 9I8 +/7lic a7stract void addCoo)ie9Coo)ie coo)ie8O
+/7lic a7stract tring encodeVedirectUrl9tring /rl8O
+/7lic a7stract tring encodeUrl9tring /rl8O
+/7lic a7stract void sendError9int sc, tring msg8 thro;s IOE*ce+tionO
+/7lic a7stract void sendVedirect9tring location8 thro;s IOE*ce+tionO
+/7lic a7stract void addInt,eader9tring header, int val/e8O
+/7lic a7stract void add6ate,eader9tring header, long val/e8O
+/7lic a7stract void set,eader9tring name, tring val/e8O
+/7lic a7stract void setInt,eader9tring header, int val/e8O
+/7lic a7stract void set6ate,eader9tring header, long val/e8O
+/7lic void settat/s98O
,tt+ession 9I8 +/7lic a7stract long getCreation!ime98O
+/7lic a7stract tring getId98O
+/7lic set5ttri7/te9tring name, O7ject val/e8O
+/7lic get5ttri7/te9tring name, O7ject val/e8O
+/7lic remove 5ttri7/te9tring name, O7ject val/e8O
+/7lic a7stract long getHast5ccessed!ime98O
+/7lic a7stract ,tt+essionConte*t getessionConte*t98O
+/7lic a7stract O7ject getDal/e9tring name8O
1
+/7lic a7stract tringRS getDal/e1ames98O
+/7lic a7stract void invalidate98O
+/7lic a7stract 7oolean is1e;98O
+/7lic a7stract void +/tDal/e9tring name, O7ject val/e8O
+/7lic a7stract void removeDal/e9tring name8O
+/7lic setMa*InactiveIntervel98O
7ttp5ession8istener () pu"lic void sessionCreated(7ttp5essionEvent event)
+/7lic void session6estro:ed9,tt+essionEvent event8
,tt+ession5ttri7/teHistener 9I8 +/7lic void attri7/te5dded9ervletConte*t5ttri7/teEvent sca78
+/7lic void attri7/teVemoved9ervletConte*t5ttri7/teEvent sca78
+/7lic void attri7/teVe+laced9ervletConte*t5ttri7/teEvent sca78
7ttp5ession1inding8istener ()
+/7lic void ,tt+essionBindingHistener.val/eBo/nd9,tt+essionBindingEvent event8
+/7lic void ,tt+essionBindingHistener.val/eUn7o/nd9,tt+essionBindingEvent event8
7ttp5essionActivation8istener ()
+/7lic void session6id5ctivate9,tt+essionEvent event8
+/7lic void sessionWill+assivate9,tt+essionEvent event8
3ilter #i)
+/7lic void do(ilter 9ervletVe@/est re@/est, ervletVes+onse res+onse, (ilterChain chain8
+/7lic (ilterCon4ig get(ilterCon4ig98
+/7lic void set(ilterCon4ig 9(ilterCon4ig 4ilterCon4ig8
1
J&BC Q"estions
.8 What Class.4or1ame ;ill do ;hile loading driversM
58 Will create an instance o4 the driver and register ;ith the 6riverManager.
.8 &6BC 3.# ne; 4eat/resM
58 1. !ransaction ave+oint s/++ort2 A 5dded the ave+oint inter4ace, ;hich contains ne; methods to set,
release, or roll 7ac) a transaction to designated save+oints.
:. Reuse of prepared statements by connection pools+ , to control how prepared statements are pooled and reused by
connections.
3. Connection +ool con4ig/ration 2A 6e4ined a n/m7er o4 +ro+erties 4or the ConnectionPool6atao/rce
inter4ace.
!hese +ro+erties can 7e /sed to descri7e ho; PooledConnection o7jects created 7: 6atao/rce o7jects sho/ld
7e +ooled.
$. Vetrieval o4 +arameter metadata2 A 5dded the inter4ace ParameterMeta6ata, ;hich descri7es the n/m7er,
t:+e
and +ro+erties o4 +arameters to +re+ared statements.
5. Vetrieval o4 a/toAgenerated )e:s2 A 5dded a means o4 retrieving val/es 4rom col/mns containing
a/tomaticall:
generated val/es.
'. M/lti+le o+en Ves/ltet o7jects2 A 5dded the ne; method getMoreVes/lts9int8.
%. Passing +arameters to Calla7letatement o7jects 7: name2 A 5dded methods to allo; a string to identi4: the
+arameter to 7e set 4or a Calla7letatement o7ject.
-. ,olda7le c/rsor s/++ort2 A 5dded the a7ilit: to s+eci4: the o4 holda7ilit: o4 a Ves/ltet o7ject.
0. BOOHE51 data t:+e2 A 5dded the data t:+e java.s@l.!:+es.BOOHE51. BOOHE51 is logicall: e@/ivalent
to BI!.
1#. Ma)ing internal /+dates to the data in Blo7 and Clo7 o7jects2 A 5dded methods to allo; the data contained
in Blo7 and Clo7 o7jects to 7e altered.
11. Vetrieving and /+dating the o7ject re4erenced 7: a Ve4 o7ject2 A 5dded methods to retrieve the o7ject
re4erenced 7: a Ve4 o7ject. 5lso added the a7ilit: to /+date a re4erenced o7ject thro/gh the Ve4 o7ject.
12. U+dating o4 col/mns containing BHOB, CHOB, 5VV5F and VE( t:+es2 A 5dded o4 the /+dateBlo7,
/+dateClo7, /+date5rra:, and /+dateVe4 methods to the Ves/ltet inter4ace.
.8 &6BC 6rivers
o &6BCAO6BC Bridge 6river
o 1ative 5PI A Partl: &ava 6river
o 1et;or) +rotocol A 5ll &ava 6river
o 1ative Protocol A P/re &ava 6river
!ier 6river mechanism 6escri+tion
!;o &6BCAO6BC
&6BC access via most O6BC drivers, some O6BC 7inar:
code and client code m/st 7e loaded on each client machine.
!his driver is commonl: /sed 4or +rotot:+ing. !he &6BCA
O6BC Bridge is &6BC driver ;hich im+lements &6BC
o+erations 7: translating them to O6BC o+erations.
!;o 1ative 5PI A Partl: &ava driver
!his driver converts &6BC calls to data7ase s+eci4ic native
calls. Client re@/ires data7ase s+eci4ic li7raries.
!hree 1et;or) +rotocol A 5ll &ava !his driver converts &6BC calls into 6BM inde+endent
1
6river
net;or) +rotocol that is sent to the middle;are server. !his
;ill translate this 6BM inde+endent net;or) +rotocol into
6BM s+eci4ic +rotocol, ;hich is sent to a +artic/lar data7ase.
!he res/lts are again rooted 7ac) to middle;are server and
sent 7ac) to client.
!;o
1ative +rotocol A 5ll A &ava
driver
!he: are +/re java driver, the: comm/nicate directl: ;ith the
vendor data7ase.
.8 &6BC connection
im+ort java.s@l.ZO
+/7lic class &6BCam+le Q
+/7lic static void main9java.lang.tringRS args8 Q
tr: Q
Class.4or1ame9Es/n.jd7c.od7c.&d7cOd7c6riverE8O
P catch 9Class1ot(o/ndE*ce+tion e8 Q
:stem.o/t.+rintln9EUna7le to load 6river ClassE8O
ret/rnO
P
tr: Q
Connection con T 6riverManager.getConnection9Ejd7c2od7c2com+an:d7E,EE, EE8O
tatement stmt T con.createtatement98O
Ves/ltet rs T stmt.e*ec/te./er:9EEHEC! (IV!]15ME (VOM EMPHOFEEE8O
;hile9rs.ne*t988 Q
:stem.o/t.+rintln9rs.gettring9E(IV!]15MEE88O
P
rs.close98O
stmt.close98O
con.close98O
P
catch 9.HE*ce+tion se8 Q
:stem.o/t.+rintln9E.H E*ce+tion2 E X se.getMessage988O
P
P
P
.8 $th t:+e driver
class.4or1ame9Boracle.jd7cdriver.oracledriverC8O
connection con T driverManager.getConnection9B&6BC2oracle2thin2fhostname2+ortno2oracleserviceC,C/idC,
B+;dC8O
.8 te+s to connect to &6BCM
58 1. (irst thing is /sing jd7c :o/ have to esta7lish a connection to the data 7ase this is 2 ste+s +rocess 9i8 :o/
m/st load the jd7c driver 9ii8 then ma)e a connection, to do this ;e can call the getConnection98 method o4
driver manager class.
2. !o e*ec/te an: s@l commands /sing jd7c connection :o/ m/st 4irst create a statement o7ject to create this
call statement st T con.createteatement98.
!his is done 7: calling the createtatement98 method in connection inter4ace. Once the statement is created
:o/ can e*ec/ted it 7: calling e*ec/te98 method o4 the statement inter4ace.
.8 Ves/ltset !:+es
1
rs.before*irst() "oto 9st record
rs.a4terHast98 goto last record
is(irst98 ? isHast98
res.a7sol/te9$8 ;ill got $th record in res/lt set.
rs.deleteVo;98
rs./+dateVo;93,--8 val/e in col/mn 3 o4 res/ltset is set to --.
rs./+date(loat98
rs.relative928
.8 !ransactional ave+oints
tatement stmt T conn.createtatement 98O
Int ro;co/nt T stmt.e*ec/teU+date 9Einsert into eta7le 9event8 val/es 9L!MML8E8O
Int ro;co/nt T stmt.e*ec/teU+date 9Einsert into costs 9cost8 val/es 9$5.#8E8O
ave+oint sv1 T conn.setavePoint 9Esv+oint1E8O ?? create save +oint 4or inserts
Int ro;co/nt T stmt.e*ec/teU+date 9Edelete 4rom em+lo:eesE8O
Conn.roll7ac) 9sv18O ?? discard the delete statement 7/t )ee+ the inserts
Conn.commitO ?? inserts are no; +ermanent
Q) @pdatin- B;OB & C;OB &ata $ypes
rs'next()-
Blo7 data T rs.getClo7 918O
Vs.close98O
?? no; letLs insert this histor: into another ta7le
stmt.setClo7 91, data8O ?? data is the Clo7 o7ject ;e retrieved 4rom the histor: ta7le
int InsertCo/nt T stmt.e*ec/teU+date9Einsert into EscalatedIncidents 9IncidentI6, Case,istor:, O;ner8E
X E Dal/es 9%11'$, M, L3oodsonL8 E8O
Q *etreivin- J Storin- J @pdatin- %rray of Objects
5rra: a T rs.get5rra:918O
Pstmt.set5rra:92, mem7er]arra:8O
Vs./+date5rra:9Blast]n/mC,n/m8O
Q) 2ow to e:ec"te no of ="eries at one -o?
58 B: /sing a 7atchU+dateLs 9i.e. thro; addBatch98 and e*ec/teBatch988 in java.s@l.tatement inter4ace or 7:
/sing +roced/res.
.8 Batch U+dates
Calla7letatement stmt T con.+re+areCall9BQcall em+lo:eeIn4o 9M8PC8O
stmt.addBatch9EI1EV! I1!O em+lo:ees D5HUE 91###, L&oe &onesL8E8O
stmt.addBatch9EI1EV! I1!O de+artments D5HUE 92'#, LhoeL8E8O
?? s/7mit a 7atch o4 /+date commands 4or e*ec/tion
intRS /+dateCo/nts T stmt.e*ec/teBatch98O
.8 M/lti+le Ves/ltset
58 !he methods getMoreVes/lts, getU+dateCo/nt, and getVes/ltet can 7e /sed to retrieve all the res/lts.
Calla7letatement cstmt T connection.+re+areCall9+rocCall8O
7oolean retval T cstmt.e*ec/te98O
i4 9retval TT 4alse8 Q
P else Q
Ves/ltet rs1 T cstmt.getVes/ltet98O
1
retval T cstmt.getMoreVes/lts9tatement._EEP]CUVVE1!]VEUH!8O
i4 9retval TT tr/e8 Q
Ves/ltet rs2 T cstmt.getVes/ltet98O
rs2.ne*t98O
rs1.ne*t98O
P
P
CHOE]5HH]VEUH! 5ll +revio/sl: o+ened Ves/ltet o7jects sho/ld 7e closed ;hen
calling getMoreVes/lts98.
CHOE]CUVVE1!]VEUH! !he c/rrent Ves/ltet o7ject sho/ld 7e closed ;hen calling
getMoreVes/lts98.
_EEP]CUVVE1!]VEUH! !he c/rrent Ves/ltet o7ject sho/ld not 7e closed ;hen calling
getMoreVes/lts98.
.8 6i44 e*ec/te98 ,e*ec/teU+date98 and e*ec/te./er:98 M
5) execute() returns a boolean !alue, which may return multiple results.
executePpdate() is used for nonfetchin" 8ueries, which returns int !alue and tell how many rows will be affected.
e*ec/te./er:98 is /sed 4or 4etching @/eries, ;hich ret/rns single Ves/let o7ject and never ret/rn 1/ll
val/e.

.8 ,o; to move the c/rsor in scrolla7le res/ltsetM
!:+e o4 a Ves/ltet o7ject2A
!FPE](OVW5V6]O1HF, !FPE]CVOHH]I1E1I!IDE, !FPE]CVOHH]E1I!IDE,
CO1CUV]VE56]O1HF and CO1CUV]UP65!5BHE.
tatement stmt T con.createtatement9Ves/ltet.!FPE]CVOHH]E1I!IDE,
Ves/ltet.CO1CUV]VE56]O1HF8O
Ves/ltet rs T stmt.e*ec/te./er:9EEHEC! COHUM1]1, COHUM1]2 (VOM !5BHE]15MEE8O
rs.a4terHast98O
;hile 9srs.+revio/s988 Q
tring name T rs.gettring9ECOHUM1]1E8O
4loat salar: T rs.get(loat9ECOHUM1]2E8O
rs.a7sol/te9$8O ?? c/rsor is on the 4o/rth ro;
int ro;1/m T rs.getVo;98O ?? ro;1/m sho/ld 7e $
rs.relative9A38O
int ro;1/m T rs.getVo;98O ?? ro;1/m sho/ld 7e 1
rs.relative928O
int ro;1/m T rs.getVo;98O ?? ro;1/m sho/ld 7e 3
??...
P
.8 ,o; to BU+dateC W B6eleteC a res/ltset +rogrammaticall:M
9pdate; *
!tatement stmt I con.create!tatement"Aesult!et.5@1L!CA%66L!1$!,,V1,
Aesult!et.C%$C9AL9@7((861#-
Aesult!et uprs I stmt.execute:uery"+!161C C%69M$L0, C%69M$L2 'A%M (861L$(M1+#-
uprs.last"#-
uprs.update'loat"+C%69M$L2+, 2M.MM#-BBupdate last row.s data
uprs.updateAow"#-BBdon.t miss this method, otherwise, the data will be lost.

1
7elete; *
uprs.absolute"M#-
uprs.deleteAow"#- BB will delete row M.
.8 &6BC connection +ool
-hen you are "oin" to caret a pool of connection to the database. This will "i!e access to a collection of
already opened data base connections, which will reduce the time it ta2es to ser!ice the re8uest and you can ser!ice .n/
number of re8uest at once.
Q) Why yo" need J&BC if O&BC is available?
58 O6BC is +/rel: ;ritten in BcC so ;e cannot directl: connect ;ith java. &6BC is a lo; level +/re java 5PI
/sed to e*ec/te .H statements. 9i8 O6BC is not a++ro+riate 4or direct /se 4rom java 7eca/se it /ses BcC
inter4aces. Calls 4rom java to native BcC code has n/m7er o4 dra;7ac)s in the sec/rit:, im+lementation and
ro7/stness.
Q) Can we establish the connection with O&BC itself?
58 Fes, /sing java native classes ;e have to ;rite a +rogram.
Q) What is necessity of J&BC in J&BC?O&BC brid-e?
58 !he +/r+ose o4 &6BC is to lin) java 5PI to the O6BC, O6BC ret/rn high level BcC 5PI so the &6BC
converts BcC level 5PI to java 5PI.
.8 6oes the &6BCAO6BC Bridge s/++ort m/lti+le conc/rrent o+en statements +er connectionM
58 1o. Fo/ can o+en onl: one tatement o7ject +er connection ;hen :o/ are /sing the &6BCAO6BC Bridge.
Q) (s the J&BC?O&BC Brid-e "lti?threaded?
58 1o. !he &6BCAO6BC Bridge does not s/++ort conc/rrent access 4rom di44erent threads. !he &6BCA
O6BC Bridge /ses s:nchroni<ed methods to seriali<e all o4 the calls that it ma)es to O6BC
.8 6:namicall: creating !a7les
tatement st T con.cretaetatement98O
Int n T st.e*ec/teU+date9Bcreate ta7le B X /nameX B9sno int, sent7: varchar91#8, s/7ject varchar9158C8O
.8 tatements in &6BC
tatement 6oes not ta)e an: arg/ments, In this statement it ;ill chec) s:nta* error and e*ec/te it
ever: time 9it ;ill +arse ever: time8.
Pre+are statement P. are +recom+iled statements once ;e com+ile the statements and send it to the server
4or later /se. P. are +artiall: com+iled statements +laced at server side ;ith +laceholders. Be4ore e*ec/tion o4
these statements /ser has to s/++l: val/es 4or +lace holders, it ;ill increase +er4ormance o4 a++lication.
Pre+aredtatement +st T con.+re+aretatement9EEHEC! Z (VOM EMP W,EVE de+tnoTME8O
6ataIn+/ttream dis T ne; 6ataIn+/ttream9B:stem.inC8O
Int dno T Integer.ParseInt9dis.readHine988O
+st.setInt91, dno8O
Ves/ltet rs T +st.e*ec/te./er:98O
Calla7le statement C. /sed to retrieve data 7: invo)ing stored +roced/res, stored +roced/re are +rogram
/nits +laced at data 7ase server side 4or re/sa7ilit:. !hese are /sed 7: nAn/m7er o4 clients. tored +roced/re is
+recom+iled in V6BM, so the: can r/n 4aster than the d:namic s@l.
1
Calla7le statement ;ill call a single stored +roced/re, the: +er4orm m/lti+le @/eries and /+dates ;itho/t
net;or) tra44ic.
calla7letatement cst T con.+re+areCall9BQC5HH +roced/reAname9MM8P C8O
6ataIn+/ttream dis T ne; 6ataIn+/ttream9B:stem.inC8O
Int en/m T Integer.ParseInt9dis.readHine988O
cst.setInt91, en/m8O
cst.registerO/tParameter92, t:+es.D5VC,5V8
res/ltset rs T cst.e*ec/te98O
In /sed to send in4ormation to the +roced/re.
O/t /sed to retrieve in4ormation 4rom data 7ase.
InO/t 7oth.
Q) (n which interface the ethods coit#) & rollbac9#) savepoint#) defined ?
58 java.s@l.Connection inter4ace
Q) *etrievin- very lar-e val"es fro database?
58 get5CIIteram98 read val/es ;hich are character in nat/re.
3etBinar:tream98 /sed to read images.
.8 Ves/ltetMeta6ata
It is /sed to 4ind o/t the in4ormation o4 a ta7le in a data 7ase.
Ves/ltet rs T stmt.e*ec/te./er:9EEHEC! Z (VOM EX ta7le8O
Ves/ltetMeta6ata rsmd T rs.getMeta6ata98O
Methods getCol/mnCo/nt98, getCol/mn1ame98, getCol/mnHa7el98, getCol/mn!:+e98, get!a7le1ame98,
.8 6ata7ase Meta6ata
Fo/ need some in4ormation a7o/t the Bdata 7aseC W Bdictionar:C ;e /se this .!o 4ind o/t ta7les, stored
+roced/re names, col/mns in a ta7le, +rimar: )e: o4 a ta7le ;e /se this, this is the largest inter4ace in java.s@l
+ac)age
Connection con T 6riverManager.getConnection9jd7cUVH, EE, EE8O
6ata7aseMeta6ata d7md T con.getMeta6ata98O
Ves/ltet rsT d7md.get***98O
Methods getCol/mns98, get!a7le!:+es98, get!a7les98, get6river1ame98, getMajorDersion98, get
MinorDersion98, getProced/res98, getProced/reCol/mns98, get!a7les98.
.8 .H Warnings
Warnings ma: 7e retrieved 4rom Connection, tatement, and Ves/ltet o7jects. !r:ing to retrieve a ;arning
on a connection a4ter it has 7een closed ;ill ca/se an e*ce+tion to 7e thro;n. imilarl:, tr:ing to retrieve a
;arning on a statement a4ter it has 7een closed or on a res/lt set a4ter it has 7een closed ;ill ca/se an
e*ce+tion to 7e thro;n. 1ote that closing a statement also closes a res/lt set that it might have +rod/ced.
Connection.getWarnings98
tatement.getWarnings98,
Ves/ltet.getWarnings98, eriali<ed (orm
1
.HWarning ;arning T stmt.getWarnings98O
i4 9;arning YT n/ll8
Q
;hile 9;arning YT n/ll8
Q
:stem.o/t.+rintln9EMessage2 E X ;arning.getMessage988O
:stem.o/t.+rintln9E.Htate2 E X ;arning.get.Htate988O
:stem.o/t.+rint9EDendor error code2 E8O
:stem.o/t.+rintln9;arning.getErrorCode988O
;arning T ;arning.get1e*tWarning98O
P
P
Q) .roced"re
Proced/re is a s/7+rogram ;ill +er4orm some s+eci4ic action, s/7 +rograms are name PH?.H 7loc)s
that can ta)e +arameters to 7e invo)ed.
create 9or8 re+lace +roced/re +roced/reAname 9id I1 I1!E3EV , 7al I1 OU! (HO5!8 I
BE3I1
select 7alance into 7al 4rom acco/nts ;here acco/nt]id T idO
Bal2 T 7al X 7al Z #.#3O
U+date acco/nts set 7alance T 7al ;here acco/nt]id T idO
E16O
.8 !rigger
!rigger is a stored PH?.H 7loc) associated ;ith a s+eci4ic data7ase ta7le. Oracle e*ec/tes triggers
a/tomaticall: ;hen ever a given .H o+eration e44ects the ta7le, ;e can associate 12 data 7ase triggers ;ith
in a given ta7le.
Create?Ve+lace trigger 7e4ore Insert 9or8 6elete 9or8 U+date on em+ 4or each ro;
Begin
Insert into table,name !alues(+empno@ +name)
end
.8 tored Images into a ta7le

P/7lic class img
Q
P/7lic static void main9tring argsRS8Q
Class.4or1ame98O
Connection con T 6riverManager.getConnection98O
Pre+arestatement +st T con.+re+aretatement9Binsert into image val/e9M88O
(ileIn+/ttream 4is T ne; (ileIn+/ttream9Ba.gi4C8O
Pst.setBinar:tream91, 4is, 4is.availa7le8O
Int I T +st.e*ec/teU+adate98O
P
Vetrieve Image
tatement st T con.Createtatement98O
1
Ves/ltet rs T st.e*ec/te./er:9Bselect Z 4rom imgC8O
Vs.ne*t98O
In+/ttream is T rs.getBinar:tream918O
(ileO/tP/ttream 4os T ne; (ileO/tP/ttream9Bg2.gi4C8O
Int chO
While99chTis.read9188YTYA18
Q
4os.;rite9ch8O
P
1
&atabase Q"estions
.8 6MH insert, /+date, delete
66H create, alter, dro+, tr/ncate, rename.
6.H select
6CH grant, revo)e.
!CH commit, roll7ac), save+oint.

Q) Aorali5ation
1ormali<ation is the +rocess o4 sim+li4:ing the relationshi+ 7et;een data elements in a record.
9i8 1st normal 4orm2 A 1st 1.( is achieved ;hen all re+eating gro/+s are removed, and P._ sho/ld 7e de4ined.
7ig ta7le is 7ro)en into man: small ta7les, s/ch that each ta7le has a +rimar: )e:.
9ii8 2nd normal 4orm2 A Eliminate an: nonA4/ll de+endence o4 data item on record )e:s. I.e. !he col/mns in a
ta7le ;hich is not com+letel: de+endant on the +rimar: )e: are ta)en to a se+arate ta7le.
9iii8 3rd normal 4orm2 A Eliminate an: transitive de+endence o4 data items on P._Ks. i.e. Vemoves !ransitive
de+endenc:. Ie I4 [ is the +rimar: )e: in a ta7le. F W ` are col/mns in the same ta7le. /++ose ` de+ends
onl: on F and F de+ends on [. !hen ` does not de+end directl: on +rimar: )e:. o remove ` 4rom the ta7le
to a loo) /+ ta7le.
.8 6i44 Primar: )e: and a Uni@/e )e:M What is 4oreign )e:M
58 Both +rimar: )e: and /ni@/e en4orce /ni@/eness o4 the col/mn on ;hich the: are de4ined. B/t 7: de4a/lt
+rimar: )e: creates a cl/stered inde* on the col/mn, ;here are /ni@/e creates a noncl/stered inde* 7:
de4a/lt. 5nother major di44erence is that, +rimar: )e: doesnLt allo; 1UHHs, 7/t /ni@/e )e: allo;s one 1UHH
onl:.
(oreign )e: constraint +revents an: actions that ;o/ld destro: lin) 7et;een ta7les ;ith the corres+onding
data val/es. 5 4oreign )e: in one ta7le +oints to a +rimar: )e: in another ta7le. (oreign )e:s +revent actions
that ;o/ld leave ro;s ;ith 4oreign )e: val/es ;hen there are no +rimar: )e:s ;ith that val/e. !he 4oreign
)e: constraints are /sed to en4orce re4erential integrit:.
C,EC_ constraint is /sed to limit the val/es that can 7e +laced in a col/mn. !he chec) constraints are /sed to
en4orce domain integrit:.
1O! 1UHH constraint en4orces that the col/mn ;ill not acce+t n/ll val/es. !he not n/ll constraints are /sed
to en4orce domain integrit:, as the chec) constraints.
Q) &iff &elete & $r"ncate?
58 Voll7ac) is +ossi7le a4ter 6EHE!E 7/t !VU1C5!E remove the ta7le +ermanentl: and canKt roll7ac).
!r/ncate ;ill remove the data +ermanentl: ;e cannot roll7ac) the deleted data.
6ro++ing 2 9!a7le str/ct/re X 6ata are deleted8, Invalidates the de+endent o7jects, 6ro+s the inde*es
!r/ncating 2 96ata alone deleted8, Per4orms an a/tomatic commit, (aster than delete
6elete 2 96ata alone deleted8, 6oesnKt +er4orm a/tomatic commit
Q) &iff 'archar and 'archar7?
58 !he di44erence 7et;een Darchar and Darchar2 is 7oth are varia7le length 7/t onl: 2### 7:tes o4 character
o4 data can 7e store in varchar ;here as $### 7:tes o4 character o4 data can 7e store in varchar2.
Q) &iff ;OA1 & ;OA1 *%W?
58 Fo/ /se the HO13 datat:+e to store varia7leAlength character strings. !he HO13 datat:+e is li)e the
D5VC,5V2 datat:+e, e*ce+t that the ma*im/m length o4 a HO13 val/e is 32%'# 7:tes.
1
Fo/ /se the HO13 V5W datat:+e to store 7inar: data 9or8 7:te strings. HO13 V5W data is li)e HO13
data, e*ce+t that HO13 V5W data is not inter+reted 7: PH?.H. !he ma*im/m length o4 a HO13 V5W
val/e is 32%'# 7:tes.
.8 6i44 (/nction W Proced/re
(/nction is a sel4Acontained +rogram segment, 4/nction ;ill ret/rn a val/e 7/t +roced/re not.
Proced/re is s/7 +rogram ;ill +er4orm some s+eci4ic actions.
.8 ,o; to 4ind o/t d/+licate ro;s W delete d/+licate ro;s in a ta7leM
58 MPI6 EMP15ME EMP1
AAAAA AAAAAAAAAA AAAAAAAAAAA
1 &ac) 555A55A5555
2 Mi)e 555A5-A5555
3 &ac) 555A55A5555
$ Mi)e 555A5-A5555
.H> select co/nt 9em+ssn8, em+ssn 4rom em+lo:ee gro/+ 7: em+ssn
having co/nt 9em+ssn8 > 1O
COU1! 9EMP18 EMP1
AAAAAAAAAAAAA AAAAAAAAAAA
2 555A55A5555
2 555A5-A5555
.H> delete 4rom em+lo:ee ;here 9em+id, em+ssn8
not in 9select min 9em+id8, em+ssn 4rom em+lo:ee gro/+ 7: em+ssn8O
.8 elect the nth highest ran) 4rom the ta7leM
58 elect Z 4rom ta7 t1 ;here 2T9select co/nt 9distinct 9t2.sal88 4rom ta7 t2 ;here t1.sal=Tt2.sal8
.8 a8 Em+ ta7le ;here 4ields em+1ame, em+Id, address
78 alar: ta7le ;here 4ields Em+Id, month, 5mo/nt
these 2 ta7les he ;ants Em+Id, em+1ame and salar: 4or month 1ovem7erM
58 elect em+.em+Id, em+1ame, 5mo/nt 4rom em+, salar: ;here em+.em+IdTsalar:.em+Id and
monthT1ovem7erO
.8 Oracle?PH.H2 :non:msM
58 5 s:non:m is an alternative name 4or o7jects s/ch as ta7les, vie;s, se@/ences, stored +roced/res, and
other data7ase o7jects
:nta*2 A
Create Ror re+laceS R+/7licS s:non:m Rschema.S s:non:m]name 4or Rschema.S o7ject]nameO
or re+lace AA allo;s :o/ to recreate the s:non:m 9i4 it alread: e*ists8 ;itho/t having to iss/e a 6VOP
s:non:m command.
P/7lic AA means that the s:non:m is a +/7lic s:non:m and is accessi7le to all /sers.
chema AA is the a++ro+riate schema. I4 this +hrase is omitted, Oracle ass/mes that :o/ are re4erring to :o/r
o;n schema.
o7ject]name AA is the name o4 the o7ject 4or ;hich :o/ are creating the s:non:m. It can 7e one o4 the
4ollo;ing2
!a7le Pac)age
1
Die; materiali<ed vie;
se@/ence java class schema o7ject
stored +roced/re /serAde4ined o7ject
(/nction :non:m

e*am+le2
Create +/7lic s:non:m s/++liers 4or a++. s/++liersO
E*am+le demonstrates ho; to create a s:non:m called s/++liers. 1o;, /sers o4 other schemas can re4erence
the ta7le called s/++liers ;itho/t having to +re4i* the ta7le name ;ith the schema named a++. (or e*am+le2
elect Z 4rom s/++liersO
I4 this s:non:m alread: e*isted and :o/ ;anted to rede4ine it, :o/ co/ld al;a:s /se the or re+lace +hrase as
4ollo;s2
Create or re+lace +/7lic s:non:m s/++liers 4or a++. s/++liersO
6ro++ing a s:non:m
It is also +ossi7le to dro+ a s:non:m.
dro+ R+/7licS s:non:m Rschema .S :non:m]name R4orceSO
+/7lic AA +hrase allo;s :o/ to dro+ a +/7lic s:non:m. I4 :o/ have s+eci4ied +/7lic, then :o/ donLt s+eci4: a
schema.
(orce AA +hrase ;ill 4orce Oracle to dro+ the s:non:m even i4 it has de+endencies. It is +ro7a7l: not a good
idea to /se the 4orce +hrase as it can ca/se invalidation o4 Oracle o7jects.

E*am+le2
6ro+ +/7lic s:non:m s/++liersO
!his dro+ statement ;o/ld dro+ the s:non:m called s/++liers that ;e de4ined earlier.
.8 What is an alias and ho; does it di44er 4rom a s:non:mM
58 5n alias is an alternative to a s:non:m, designed 4or a distri7/ted environment to avoid having to /se the
location @/ali4ier o4 a ta7le or vie;. !he alias is not dro++ed ;hen the ta7le is dro++ed.
.8 What are joinsM Inner join W o/ter joinM
58 B: /sing joins, :o/ can retrieve data 4rom t;o or more ta7les 7ased on logical relationshi+s 7et;een the
ta7les
Inner &oin2 A ret/rns all ro;s 4rom 7oth ta7les ;here there is a match.
O/ter &oin2 A o/ter join incl/des ro;s 4rom ta7les ;hen there are no matching val/es in the ta7les.
\ HE(! &OI1 or HE(! OU!EV &OI1
!he res/lt set o4 a le4t o/ter join incl/des all the ro;s 4rom the le4t ta7le s+eci4ied in the HE(! OU!EV
cla/se, not j/st the ones in ;hich the joined col/mns match. When a ro; in the le4t ta7le has no matching
ro;s in the right ta7le, the associated res/lt set ro; contains n/ll val/es 4or all select list col/mns coming
4rom the right ta7le.
\ VI3,! &OI1 or VI3,! OU!EV &OI1.
5 right o/ter join is the reverse o4 a le4t o/ter join. 5ll ro;s 4rom the right ta7le are ret/rned. 1/ll val/es are
ret/rned 4or the le4t ta7le an: time a right ta7le ro; has no matching ro; in the le4t ta7le.
\ (UHH &OI1 or (UHH OU!EV &OI1.
5 4/ll o/ter join ret/rns all ro;s in 7oth the le4t and right ta7les. 5n: time a ro; has no match in the other
ta7le, the select list col/mns 4rom the other ta7le contain n/ll val/es. When there is a match 7et;een the
ta7les, the entire res/lt set ro; contains data val/es 4rom the 7ase ta7les.
1
Q! &iff join and a @nion?
58 5 join selects col/mns 4rom 2 or more ta7les. 5 /nion selects ro;s.
;hen /sing the U1IO1 command all selected col/mns need to 7e o4 the same data t:+e. !he U1IO1
command eliminate d/+licate val/es.
Q! @nion & @nion %ll?
58 !he U1IO1 5HH command is e@/al to the U1IO1 command, e*ce+t that U1IO1 5HH selects all val/es.
It cannot eliminate d/+licate val/es.
> EHEC! E]1ame (VOM Em+lo:ees]1or;a:
U1IO1 5HH
EHEC! E]1ame (VOM Em+lo:ees]U5
.8 Is the 4oreign )e: is /ni@/e in the +rimar: ta7leM
58 1ot necessar:
.8 !a7le mentioned 7elo; named em+lo:ee
I6 15ME MI6
1 CEO 1/ll
2 DP CEO
3 6irector DP
5s)ed to ;rite a @/er: to o7tain the 4ollo;ing o/t+/t
CEO 1/ll
DP CEO
6irector DP
58 .H> elect a.name, 7.name 4rom em+lo:ee a, em+lo:ee 7 ;here a.midT7.id9X8.
.8 E*+lain a scenario ;hen :o/ donKt go 4or normali<ationM
58 I4 ;e r s/re that there ;ont 7e m/ch data red/ndanc: then donKt go 4or normali<ation.
.8 What is Ve4erential integrit:M
58 V.I re4ers to the consistenc: that m/st 7e maintained 7et;een +rimar: and 4oreign )e:s, i.e. ever: 4oreign
)e: val/e m/st have a corres+onding +rimar: )e: val/e.
.8 What techni@/es are /sed to retrieve data 4rom more than one ta7le in a single .H statementM
58 &oins, /nions and nested selects are /sed to retrieve data.
.8 What is a vie;M Wh: /se itM
58 5 vie; is a virt/al ta7le made /+ o4 data 4rom 7ase ta7les and other vie;s, 7/t not stored se+aratel:.
.8 EHEC! statement s:nta*M
58 EHEC! R 6I!I1C! b 5HH S col/mn]e*+ression1, col/mn]e*+ression2, ....
R (VOM 4rom]cla/se S
R W,EVE ;here]e*+ression S
R 3VOUP BF e*+ression1, e*+ression2, .... S
R ,5DI13 having]e*+ression S
R OV6EV BF order]col/mn]e*+r1, order]col/mn]e*+r2, .... S
col/mn]e*+ression 22T e*+ression R 5 S R col/mn]alias S
1
4rom]cla/se 22T select]ta7le1, select]ta7le2, ...
4rom]cla/se 22T select]ta7le1 HE(! ROU!EVS &OI1 select]ta7le2 O1 e*+r ...
4rom]cla/se 22T select]ta7le1 VI3,! ROU!EVS &OI1 select]ta7le2 O1 e*+r ...
4rom]cla/se 22T select]ta7le1 RI11EVS &OI1 select]ta7le2 ...
select]ta7le 22T ta7le]name R 5 S R ta7le]alias S
select]ta7le 22T 9 s/7]select]statement 8 R 5 S R ta7le]alias S
order]col/mn]e*+r 22T e*+ression R 5C b 6EC S
.8 6I!I1C! cla/seM
5) The #I)TI(6T clause allows you to remo!e duplicates from the result set.
> EHEC! 6I!I1C! cit: (VOM s/++lierO
.8 COU1! 4/nctionM
58 !he COU1! 4/nction ret/rns the n/m7er o4 ro;s in a @/er:
> EHEC! COU1! 9Z8 as E1o o4 em+sE (VOM em+lo:ees W,EVE salar: > 25###O
Q) &iff 2%'(A1 C;%@S+ & W2+*+ C;%@S+?
58 ,aving Cla/se is 7asicall: /sed onl: ;ith the 3VOUP BF 4/nction in a @/er:. W,EVE Cla/se is a++lied
to each ro; 7e4ore the: are +art o4 the 3VOUP BF 4/nction in a @/er:.
.8 6i44 3VOUP BF W OV6EV BFM
58 3ro/+ 7: controls the +resentation o4 the ro;s, order 7: controls the +resentation o4 the col/mns 4or the
res/lts o4 the EHEC! statement.
> EHEC! Ecol]nam1E, UM9Ecol]nam2E8 (VOM Eta7]nameE 3VOUP BF Ecol]nam1E
> EHEC! Ecol]namE (VOM Eta7]namE RW,EVE EconditionES OV6EV BF Ecol]namE R5C, 6ECS
.8 What )e:;ord does an .H EHEC! statement /se 4or a string searchM
58 !he HI_E )e:;ord allo;s 4or string searches. !he d sign is /sed as a ;ildcard.
.8 What is a 1UHH val/eM What are the +ros and cons o4 /sing 1UHHM
58 1UHH val/e ta)es /+ one 7:te o4 storage and indicates that a val/e is not +resent as o++osed to a s+ace or
<ero val/e. 5 1UHH in a col/mn means no entr: has 7een made in that col/mn. 5 data val/e 4or the col/mn is
E/n)no;nE or Enot availa7le.E
.8 Inde*M !:+es o4 inde*esM
58 Hocate ro;s more @/ic)l: and e44icientl:. It is +ossi7le to create an inde* on one 9or8 more col/mns o4 a
ta7le, and each inde* is given a name. !he /sers cannot see the inde*es, the: are j/st /sed to s+eed /+
@/eries.
Uni@/e Inde* 2 A
5 /ni@/e inde* means that t;o ro;s cannot have the same inde* val/e.
>CVE5!E U1I.UE I16E[ inde*]name O1 ta7le]name 9col/mn]name8
When the U1I.UE )e:;ord is omitted, d/+licate val/es are allo;ed. I4 :o/ ;ant to inde* the val/es in a
col/mn in descending order, :o/ can add the reserved ;ord 6EC a4ter the col/mn name2
>CVE5!E I16E[ PersonInde* O1 Person 9Hast1ame 6EC8

If you want to index more than one column you can list the column names within the parentheses.
>CVE5!E I16E[ PersonInde* O1 Person 9Hast1ame, (irst1ame8
1
.8 6i44 s/7@/eries W Correlated s/7@/eriesM
58s/7@/eries are sel4Acontained. 1one o4 them have /sed a re4erence 4rom o/tside the s/7@/er:.
correlated s/7@/er: cannot 7e eval/ated as an inde+endent @/er:, 7/t can re4erence col/mns in a ta7le listed
in the 4rom list o4 the o/ter @/er:.
.8 Predicates I1, 51F, 5HH, E[I!M
58 /7 @/er: can ret/rn a s/7set o4 <ero to n val/es. 5ccording to the conditions ;hich one ;ants to e*+ress,
one can /se the +redicates I1, 51F, 5HH or E[I!.
I1 !he com+arison o+erator is the e@/alit: and the logical o+eration 7et;een val/es is OV.
51F 5llo;s to chec) i4 at least a val/e o4 the list satis4ies condition.
5HH 5llo;s to chec) i4 condition is reali<ed 4or all the val/es o4 the list.
E[I! I4 the s/7@/er: ret/rns a res/lt, the val/e ret/rned is !r/e other;ise the val/e ret/rned is (alse.
Q) What are soe s=l %--re-ates and other B"ilt?in f"nctions?
58 5D3, UM, MI1, M5[, COU1! and 6I!I1C!.
$L"
!What is S+?
"! !:6 stands for .!tructured :uery 6anguage..
%@
!What is SE+EC) statement?
"! he !161C statement lets you select a set of values from a table in a database. he
values selected from the database table would depend on the various conditions that
are specified in the !:6 ?uery.
%@
!'ow can you compare a part of the name rather than the entire name?
"! !161C H 'A%M people <>1A1 empname 6,J1 .NabN.
<ould return a recordset with records consisting empname the se?uence .ab. in
empname .
%@
!What is the I=SE>) statement?
"! he ,$!1A statement lets you insert information into a database.
%@
!'ow do you delete a record from a database?
"! 9se the 71611 statement to remove records or any particular column values from a
database.
1
%@
!'ow could I #et distinct entries from a table?
"! he !161C statement in conjunction with 7,!,$C lets you select a set of distinct
values from a table in a database. he values selected from the database table
would of course depend on the various conditions that are specified in the !:6
?uery. 1xample
SELECT DSTNCT empname !"#M emptable
%@
!'ow to #et the results of a uery sorted in any order?
"! 5ou can sort the results and return the sorted results to your program by using
%A71A 85 &eyword thus saving you the pain of carrying out the sorting yourself.
he %A71A 85 &eyword is used for sorting.
SELECT empname, a$e, city !"#M emptable #"DE" %& empname
%@
!'ow can I find the total number of records in a table?
"! 5ou could use the C%9$ &eyword , example
SELECT C#'NT()* !"#M emp +,E"E a$e-./
%@
!What is ?>0/3 1@?
"! he GA%9@ 85 &eywords have been added to !:6 because aggregate functions "li&e
!9M# return the aggregate of all column values every time they are called. <ithout
the GA%9@ 85 functionality, finding the sum for each individual group of column
values was not possible.
%@
!What is the difference amon# <droppin# a table<$ <truncatin# a table< and
<deletin# all records< from a table.
"! %roppin# ! "able structure E 7ata are deleted#, ,nvalidates the dependent
objects ,7rops the indexes
)runcatin#! "7ata alone deleted#, @erforms an automatic commit, 'aster than
delete
%elete ! "7ata alone deleted#, 7oesnOt perform automatic commit
%@
!What are the +ar#e ob-ect types suported by 0racle?
"! 8lob and Clob.
%@
!%ifference between a <where< clause and a <havin#< clause&
1
"! >aving clause is used only with group functions whereas <here is not used with.
%@
!WhatAs the difference between a primary key and a uni,ue key?
"! 8oth primary &ey and uni?ue enforce uni?ueness of the column on which they are
defined. 8ut by default primary &ey creates a clustered index on the column, where
are uni?ue creates a nonclustered index by default. (nother major difference is that,
primary &ey doesn.t allow $966s, but uni?ue &ey allows one $966 only.
%@
!What are cursors? Explain different types of cursors& What are the
disadvanta#es of cursors? 'ow can you avoid cursors?
"! Cursors allow row*by*row prcessing of the resultsets.
ypes of cursors; !tatic, 7ynamic, 'orward*only, Jeyset*driven. !ee boo&s online for
more information.
7isadvantages of cursors; 1ach time you fetch a row from the cursor, it results in a
networ& roundtrip, where as a normal !161C ?uery ma&es only one rowundtrip,
however large the resultset is. Cursors are also costly because they re?uire more
resources and temporary storage "results in more ,% operations#. 'urthere, there
are restrictions on the !161C statements that can be used with some types of
cursors.
Most of the times, set based operations can be used instead of cursors.
%@
!What are tri##ers? 'ow to invoke a tri##er on demand?
"!riggers are special &ind of stored procedures that get
executed automatically when an ,$!1A, 9@7(1 or 71611
operation ta&es place on a table.
riggers can.t be invo&ed on demand. hey get triggered only
when an associated action ",$!1A, 9@7(1, 71611#
happens on the table on which they are defined.
riggers are generally used to implement business rules,
auditing. riggers can also be used to extend the referential
integrity chec&s, but wherever possible, use constraints for
this purpose, instead of triggers, as constraints are much
faster.
!What is a -oin and explain different types of -oins&
1
"!Joins are used in ?ueries to explain how different tables are
related. Joins also let you select data from a table depending
upon data from another table.
ypes of joins; ,$$1A J%,$s, %91A J%,$s, CA%!! J%,$s.
%91A J%,$s are further classified as 61' %91A J%,$!, A,G>
%91A J%,$! and '966 %91A J%,$!.
%@
!What is a self -oin?
"! !elf join is just li&e any other join, except that two instances of the same table will
be joined in the ?uery.
1

Potrebbero piacerti anche