1
Table of Contents Core java ................................................. ........................................................................................................ ....................................................... ......................................... ................................. ............. .....2 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 ame !hreadro/+In4o.java........................................................................................................1#$ Main thread is e*iting............................................................................................................................1#Main thread is e*iting............................................................................................................................1#0 ll Pac)ages..................................................................................................................................................120 &6BC /estions............................................................................................................................................135 6ata7ase /estions.......................................................................................................................................1$3
2
Core java Basics Q) What is difference between Java and C++?
8 9i8 &ava does not s/++ort +ointers. Pointers are inherentl: insec/re an d 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 ll 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
> are not overloaded 4or I?O o+erations Q) Oops concepts Polymorphism
7ilit: 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 +ol:mor+hism8 Inheritance
Is the +rocess 7: ;hich one o7ject ac@/ires the +ro+erties o4 another o7ject. !he advantages a dvantages o4 inheritance are re/sa7ilit: o4 code and accessi7ilit: o4 varia7les and methods o4 the s/+er class 7: s/7classes. Encapsulation
Wra++ing Wra++ing o4 data and 4/nction into a single /nit called enca+s/lation. E*A all java +rograms. 9Or8 othing 7/t data hiding, li)e the varia7les declared /nder +rivate o4 a +artic/lar class are accessed onl: in that clas classs and and canno cannott acce access ss in an: an: other other the the clas class. s. Or idi iding ng the the in4o in4orm rmat atio ion n 4rom 4rom othe others rs is call called ed 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
othing 7/t re+resenting the essential 4/t/res ;itho/t incl/ding 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 o 4 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+ enerall: 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
Core java Basics Q) What is difference between Java and C++?
8 9i8 &ava does not s/++ort +ointers. Pointers are inherentl: insec/re an d 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 ll 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> are not overloaded 4or I?O o+erations Q) Oops concepts Polymorphism
7ilit: 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 +ol:mor+hism8 Inheritance
Is the +rocess 7: ;hich one o7ject ac@/ires the +ro+erties o4 another o7ject. !he advantages a dvantages o4 inheritance are re/sa7ilit: o4 code and accessi7ilit: o4 varia7les and methods o4 the s/+er class 7: s/7classes. Encapsulation
Wra++ing Wra++ing o4 data and 4/nction into a single /nit called enca+s/lation. E*A all java +rograms. 9Or8 othing 7/t data hiding, li)e the varia7les declared /nder +rivate o4 a +artic/lar class are accessed onl: in that clas classs and and canno cannott acce access ss in an: an: other other the the clas class. s. Or idi iding ng the the in4o in4orm rmat atio ion n 4rom 4rom othe others rs is call called ed 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
othing 7/t re+resenting the essential 4/t/res ;itho/t incl/ding 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 o 4 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+ enerall: 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).
3 Q) Syste!o"t!println#) +rintln98 is
a methd o4 java.io.+rintWriter. java.io.+rintWriter. o/t 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 val/e ;ill 7e changed /ne*+ectedl: 7: the other +art o4 the +rogram, it tells tells the com+iler a varia7le ma: change as:nchrono/sl: d/e to threads
Q) %ccess Specifiers & %ccess odifiers?
ccess +eci4iers . gives access +rivileges to o/tside o4 a++lication 9or8 others, the: are P/7lic, Protected, Private, 6e4a/lts. ccess Modi4iers .M ;hich gives additional meaning to data, methods and classes, 4inal cannot 7e modi4ied at an: +oint o4 time.
ame class ame +ac)age /7class ame +ac)age nonAs/7class 6i44erent +ac)age s/7class 6i44erent +ac)age nonAs/7class
Private P/7lic Fes Fes o Fes o Fes o Fes o Fes
Protected Fes Fes Fes Fes o
o modi4ier Fes Fes Fes o o
Q) efa"lt 'al"es
A2G'3 to 2G'3 "1 #H Int A2G31 to 2G31 "1 # hor hortt A2G1 A2G15 5 to to 2G15 2G15 "1 # B:te A2G% to 2G% "1 #
long
do/7le
# .# d
(loat Boolean Char
#.#4 4alse # to 2G% "1 n/ll character 9or8 J/ ####K
Q) Byte code & J($ copiler & J' & J* & J, B:te
code is a highl: o+timi
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 Tools pro!ided by J#$ is
9i8 9i8 java javacc " com+ com+il iler er 9ii8 9ii8 java java " int inter er+r +ret etor or 9iii 9iii88 jd7 jd7 " de7/ de7/gg gger er 9iv8 9iv8 java java+ + A 6isa 6isass ssem em7l 7les es 9v8 9v8 a++ a++le letv tvie ie;e ;err " ++le ++lets ts 9vi8 9vi8 java javado docc A doc/ doc/m menta entati tion on gene genera rato torr 9vii 9vii88 jav javah ah A LCL LCL head header er 4ile 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: re4erence
$ &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. rg/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 Private !he +rogram com+iles +ro+erl: 7/t at r/ntime it ;ill give Main method not +/7lic. Message What i4 the static modi4ier is removed 4rom the signat/re o4 the main method %ro"ram compiles. &ut at runtime throws an error 'ouchMethodrror'. We can
;rite static +/7lic void instead o4 +/7lic static void 7/t not +/7lic void static. 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 method %ro"ram compiles but throws a runtime error 'ouchMethodrror'. I4
no arg/ments on the command line, tring arra: o4 Main method ;ill 7e em+t: or n/ll 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?
8 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?
8 o 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
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
:stem.o/t.+rintln9hello8
5 Class B e*tends Q B98Q :stem.o/t.+rintln94riend8 Class +rint Q P/7lic static void main 9tring args RS8Q B 7 T ne; B98 o?+A hello 4riend Q) iff between Constr"ctor & ethod
Constr/ctor
Method
Use to instance of a class
Grouping java statement
o ret/rn t:+e ame name as class name
Doid 9or8 valid ret/rn t:+e s a name e*ce+t the class method name, 7egin ;ith lo;er case.
!his re4er to another constr/ctor in the same class /+er to invo)e the s/+er class constr/ctor
Refers to instance of class
“nheritance! cannot "e inherited
Can 7e inherited Can 7e inherited
#e can “overload! "ut $e cannot “overridden! #ill automaticall% invo&e $hen an o"ject is created
Execute an overridden method in the super class
Method has called e*+licitl:
Q) 1arba-e collection
.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
Q) 2ow an object becoes eli-ible for 1arba-e Collection?
8 n o7ject is eligi7le 4or gar7age collection ;hen no o7ject re4ers to it, n 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%8 i T n/ll 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.
'
(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: 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. n: 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
8 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?
8 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
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?
8 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 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 +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 # void amethod98Q :stem.o/t.+rintln9in Parent8 class Child e*tends ParentQ int i T 1# void amethod98Q :stem.o/t.+rintln9in Child8 class !estQ +/7lic static void main9tringRS args8Q Parent + T ne; Child98 Child c T ne; Child98 :stem.o/t.+rint9iTX+.iX 8 +.amethod 98 :stem.o/t.+rint9iTXc.iX 8 c.amethod98 o?+ 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.newnstance"# or Constructor.newnstance"# 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 classs 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 (nonstatic) 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 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: 4inal, 7eca/se overriding is onl: done 7ased on the t:+e o4 the o7jects !he: cannot re4er this are s/+er 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 static )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 static )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 created 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 Conversion A int I T integer.val/eO492$8.intDal/e98 int * T integer.+arseInt9$338 4loat 4 T 4loat.val/eO4923.08.4loatDal/e98
0 Int to tring Conversion A tring arg T tring.val/eO491#8 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?
8 ested 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. n: 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 7 e inner inter4aces. ll o4 these are o4 the nested to+Alevel variet:. Mem7er classes A Mem7er inner classes are j/st li)e other mem7er methods an d 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 o 4 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. non:mo/s classes A non:mo/s inner classes e*tend local inner classes one level 4/rther. s 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> 7stract class +rovide some de4a/lt 7ehavio/r, .C are e*cellent candidates inside o4 a++lication 4rame;or). .C allo; single inheritance model, ;hich sho/ld 7e ver: 4aster. Q) %bstract Class
n: 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. .C can contain concrete methods. n: s/7 class o4 an 7stract class m/st either im+lement all the a7stract methods in the s/+er class or 7e declared itsel4 as 7stract. Com+ile time error occ/r i4 an attem+t to create an instance o4 an 7stract class. Fo/ cannot declare a7stract constr/ctor and a7stract static method. n a7stract method also declared +rivate, native, 4inal, s:nchroni, ;hich is accessi7ilit: as +ac)age. n a7stract method declared in a nonAa7stract class. O n a7stract class can have instance methods that im+lement a de4a/lt 7ehavior.
1 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. class ;ith an a7stract method. gain note that the class itsel4 is declared a7stract, other;ise a com+ile time error ;o/ld have occ/rred. 7stract class Q P/7lic a7stract callme98 Doid callmetoo98Q class B e*tends 9 void callme(){
class 7stract6emoQ +/7lic static void main9string argsRS8Q B 7 T ne; B98 7.callme98 7.callmetoo98 Q) When we "se %bstract class?
8 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 7starctclass nimalQ P/7lic void eat94ood 4ood8 Q +/7lic void slee+9int ho/rs8 Q +/7lic a7stract void ma)eoise98 +/7lic 6og e*tends nimal Q +/7lic void ma)eoise98 Q :stem.o/t.+rintln9Bar)Y Bar)8 +/7lic Co; e*tends nimal Q +/7lic void ma)eoise98 Q :stem.o/t.+rintln9mooY moo8
1 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. ll methods in inter4ace are im+licitl: a7stract, even i4 the a7stract modi4ier is omitted. Inter4ace methods have no im+lementation Inter4aces are /se4/l 4or 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 im+lemented. n inter4ace 7od: ma: contain constant declarations, a7stract method declarations, inner classes a nd inner inter4aces. ll methods o4 an inter4ace are im+licitl: 7stract, P/7lic, even i4 the +/7lic modi4ier is omitted. n inter4ace methods cannot 7e declared +rotected, +rivate, strict4+, native or s:nchroni
class can onl: e*tend one other class. class ma: im+lements more than one inter4ace. Inter4ace can e*tend more than one inter4ace. Inter4ace Q 4inal static 4loat +i T 3.1$4 class B im+lements Q +/7lic 4loat com+/te94loat *, 4loat :8 Q ret/rn9*Z:8 class testQ +/7lic static void main9tring argsRS8 Q a T ne; B98 a.com+/te98
1 Q) iff (nterface & %bstract Class? .C
ma: have some e*ec/ta7le methods and methods le4t /nim+lemented. Inter4ace contains no im+lementation code. n .C can have nona7stract methods. ll methods o4 an Inter4ace are a7stract. n .C can have instance varia7les. n Inter4ace cannot. n .C m/st have s/7classes ;hereas inter4ace canLt have s/7classes n .C can de4ine constr/ctor. n Inter4ace cannot. 5n
5.6 can ha!e any !isibility+ public, pri!ate, protected. 5n Interface !isibility must be public (or) none.
n
.C can have instance methods that im+lement a de4a/lt 7ehavior. n 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? 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. ll 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. 7stract 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. n 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 classes .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;s • •
•
•
Inter4aces +rovide a 4orm o4 m/lti+le inheritance. class can e*tend onl: one other class. Inter4aces are limited to +/7lic methods and constants ;ith no im+lementation. 7stract classes can have a +artial im+lementation, +rotected +arts, static methods, etc. 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. 7stract classes are 4ast.
$imilarities: •
either 7stract 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 &ava • • •
Method overloading Method overriding thro/gh inheritance Method overriding thro/gh the &ava inter4ace
Q) What are soe alternatives to inheritance?
8 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 7e ca/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 class :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'Externalial"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
1 eriali
:nchroni
8 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
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#)?
8 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/44er9mit8 tringB/44er s72T ne; tringB/44er9mit8 tring s1 T mit tring s2 T mit
1 tring s3 T ne; tring9a7cd8 tring s$ T ne; tring9a7cd8 tring ss1 T mit 9s71TTs728 ( 9s71.e@/als9s7288 ( 9s71.e@/als9ss188 (
9s1.e@/als9s288 ! 99s1TTs288 ! 9s3.e@/als9s$88 ! 99s3TTs$88 (
tring s1 T a7c tring s2 T ne; tring9a7c8 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 res+onsi7le 4or handling *ml s:nta*, chec)ing the contents o4 the doc/ment against constraints esta7lished in a 6!6 or chema. '. 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
[ \ Parses node 7: node \ 6oesnKt store the [MH in memor: \ We cant insert or delete a node \ [ is an event 7ased +arser \ [ is a im+le PI 4or [MH \ doesnKt +reserve comments \ [ 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 96OM 96OM88 PI
1 \ Preserves comments \ [ generall: r/ns a little 4aster than 6OM
Q) ar9er (nterfaces #or) $a--ed (nterfaces >
n Inter4ace ;ith no methods. Is called mar)er Inter4aces, eg. eriali
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 con verting 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; UVH9;;;.:ahoo.com8 UVHConnection con T h+.o+enConnection98 Q) *"ntie class
V/ntime class enca+s/late the r/nAtime environment. Fo/ Fo/ cannot instantiate a V/ntime o7ject. Fo/ 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 mem1 Mem1 T r.4reeMemor:98 r.4reeMemor:98 Mem1 T r.totalMemor:98 r.totalMemor:98 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/ntime98 Process + T n/ll !r:Q + T r.e*ce9note+ad8 +.;ai(or98 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
ative 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*A 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 Class$ot'ound1xception getClass6oader"# get'ield"# getMethods"# getnterface"#
getClass"# getConstructor"# get7eclared'ields"# get7eclearedMethods"# 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 modi4ier o4 class. Fo/ 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'instancef 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 Hi7 in jd) 8in contains all tools such as javac, appletviewer and awt tool.
Hi7 contains PI and all +ac)ages. ! What is a platfor?
+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 Windo;s 2### and [P, Hin/*, Hin/*, olaris, and MacO. ! 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+onents 1. !he &ava Dirt/al Machine 9&ava DM8 2. !he &ava ++lication Programming Inter4ace 9&ava PI8 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 PI 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 9UI8 ;idgets. F! What is the pac9a-e?
!he +ac)age is a &ava names+ace or +art o4 &ava li7raries. !he &ava PI is gro/+ed into li7raries o4 related classes and inter4aces 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?
ot reall:. s 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 co m+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
B: im+lementing either the java.io.eriali
Inheritance 58 Which class does 7egin &ava class hierarch:
1 ns O7ject class '8 O7ject class is a s/+erclass o4 all other classes !r/e?(alse ns !r/e %8 &ava s/++orts m/lti+le inheritance !r/e?(alse ns (alse 1#8 Which method is /sed to call the constr/ctors o4 the s/+erclass 4rom the s/7class ns s/+er9arg/ment8 118 Which is /sed to e*ec/te an: method o4 the s/+erclass 4rom the s/7class ns s/+er.methodAname9arg/ments8 128 Which methods are /sed to destro: the o7jects created 7: the constr/ctor methods ns 4inali
2
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 ob4ectoriented, 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 ob4ectoriented 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 ) Rubber stamp %hoto"raphic ne"ati!e
Couse tamped ima"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 ob4ectoriented 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 ! 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 ) @
! 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 methods or abstract methods or a mixture.
Interface should contain only abstract methods.
:.
The methods may ha!e any access specifier except pri!ate.
The access specifier must be public.
H.
The !ariables can ha!e any access specifier except pri!ate.
The !ariables must be public, static and final.
.
Multiple inheritance is not possible.
Multiple inheritance is possible.
.
Inheritance "oes with extends 2eyword.
Inheritance "oes with implements 2eyword.
2
K.
abstract 2eyword must be included in method declaration.
public and abstract, e!en if omitted, they 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 overridinF! 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 %rinttream extends *ilter0utputtream < 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-
0ccurs in the same class o method hides another. o method replaces the other. #ifferent method si"natures May ha!e different return types May ha!e different declared exceptions
Overrdin-
0ccurs between two classes 2nown as superclass and subclass. ubclass method hides(bloc2s) superclass mehod ubclass method replaces the suerclasss method. ame method si"nataure. hould ha!e the same return type. 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 ) @ ystem.out.println( s"per!: ) @ ystem.out.println( x B super.x) @ A public static !oid main(trin" ar"s= > ) < & b new &( ) @ b.display( ) @ A A
EE prints :F EE prints 9F EE prints HF
@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 EE Cello9 is printed s"per!display# ) I 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
A
&( ) < 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 &( ) @ A EE output is 9F and
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 6lan"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. A final class 5 < 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!
6! 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.
3
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 nonstatic method can be called from a static method. &ut a static ethod cannot call a nonstatic 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. . tatic methods cannot be called with s"per 2eyword in inheritance.
6! 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 #6 implements Jet%lane < int numn"ines( ) <
3
return H @ A A class #69F implements Jet%lane < int numn"ines( ) < return @ A A class InterfaceJet%lane < public static !oid main(trin" ar"s= > ) < ystem.out.println( 'o. of en"ines #6 contains ' B new #6( ).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 #6 contains H o. of en"ines #69F contains
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, #6 2eeps H en"ines and #69F 2eeps 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 o utput 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 subpac2a"es to pac2a"es. *or example, in java!awt!event e!ent is the subpac2a"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 d ictates 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 d ictates 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 %rotected 2eyword o 2eyword( default ) %ri!ate 2eyword
5ccessible to all the classes. 5ccessible to classes in the same pac2a"e or subclasses of other pac2a"e. 5ccessible only to classes of the same pac2a"e 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 CC++ ? -hen jd96!G ( Ja!a;s first !ersion ) was released to the world in 9OO o!ember, it was described by Mr !James Goslin", who heads the Ja!a de!elopment team at un Microsystems as+ Java is siple4 objectoriented4 distrib"ted4 interpreted4 rob"st4 sec"re4 architect"rene"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 cleanup 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. Objectoriented > 0b4ectoriented 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 d is2. *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. .latforindependent > 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. @ #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( ) @ double y ? d9.doubleValue( ) @
EE to "et bac2 int !alue from i6 ob4ect 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 ob4ectoriented support. 5lthou"h, the Ja!a lan"ua"e is stron"ly ob4ectoriented, 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( bytes ). 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 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 ? @ double y ? x @ ystem.out.println( y ) @
EE prints .F
In the abo!e code, : ( int occupies bytes ) can be assi"ned to d ( double occupies 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 ? .K @ int i ? d @ ystem.out.println( i ) @
EE raises a compilation error
In the abo!e pro"ram, d ( of bytes ) can be assi"ned to i ( of bytes ). It needs explicit castin". The abo!e code rewritten as follows + double d ? .K @ int i ? ( int ) d @ ystem.out.println( i ) @
EE prints
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 *lower f ? new *lower( ) @ Rose r ? new Rose( ) @ f
< A
EE obser!e e:tends 9eyword here
EE it is le"al, as per rule 9. 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 ob 4ects( 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
7! 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
7! 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.totrin"( ) @
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 achineindependent 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 /.
.3ava )ile
( s o ur c e
6ompiler
.class )ile
( c o n t i a n s byt e c ode
Interpreter
Windows A$
0utput
Interpreter
S"n Solaris
0utput
acintosh
0utput
Interpreter
@nicode> 56II(extended) character ran"e is F to :. -e cannot add one more character, if we do want. 0nly n"lish alphabets has "ot correspondin" 56II !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" 56II( 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 K,H. This ran"e is called @nicode. -e can say %SC(( is a s"bset of @nicode. Ppto :, Pnicode represents
3 56II ran"e and afterwards it adds its own !alues for the alphabets of many world lan"ua"es. Pnicode is already includes up to H,9: 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 platformindependent 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 p ercenta"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
! native ?
6! instanceof > The instanceof 2eyword is a twoar"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) compiletime and b) runtime. 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
$ 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 ? , b ? F, c, x= > ? < 9F, :F A @ try < c?aEb@ 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
NE
else if ( e instanceof Interruptedxception ) ystem.out.println( 'lement does not exist'B e)@ 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 runtime.
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. ! 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 platformindependent. The nati!e code of the pro"ram, is con!erted into a #DD that can be lin2ed dynamically at runtime. 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 ? 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: ? 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 ) E 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 mar2sweep "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 threadlocal 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
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 > ? @ EE assi-nin- a !alue to an element ystem.out.println( sub4ect= 9 > ) @ EE now, prints 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= > ? < :, , S, 9F A @ ystem.out.println( sub4ect = 9 > ) @
EE initiali7in" an array EE prints
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= > ? < :, , S, 9F A @ EE si7e should not written, e!en if it is correct.
88! 2ow Java arrays of Java are different fro C 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
2
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 ).
.
In Ja!a, array si7e sho"ld not be entioned while initiali7in". int sub4ect= > ? < :, , S, 9F A @ The abo!e statement raises a compilation error as the si7e of the array is specified ( e!en if it is correct also ). &ut in 6, it is optional.
.
In Ja!a, trin" is an ob4ect and does not terminate with G.. &ut in 6, it is an array of characters terminatin" with 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.
Strin-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 CC+ + ? 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" G. &ut in Ja!a, strin" is an ob4ect of Strinclass. 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 for strin"s that can chan"e.
Strin-, for constant strin"s and Strin-B"ffer ,
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
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 totrin"( ) method of 0b4ect class. &ut totrin"( ) 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 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( ) ) @ ystem.out.println( str:.toPpper6ase( ) ) @
EE prints snrao EE prints S*!3%C@;$P
8! :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" G. &ut in Ja!a, strin" is an ob4ect of Strinclass. 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
public )inal class $trin# e,ten&s O7ject implements eriali
$ 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 ) @ . 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 ) @ ystem.out.println( str ) @
EE copies H characters startin" from index number 9 EE prints ell
. 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.totrin"( ) @ ystem.out.println( str ) @ 1. What &oes a well7written pro#ram loo8 li8e*4&onate& in July2 '99
;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 7GG)
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 virt/al is not +art o4 the naming convention in &ava 9 as it is in CXX, CAshar+ and DB.E!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 7GG)
$ 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:9+athAtoAli7rar:A4ile8 .... When :o/ call ne; !est 98, the static 7loc) ;ill 7e called 4irst 7e4ore an: initiali
WBS($ N G7
htt+??;;;.roseindia.net?intervie;@/estions?inde*.shtml
1. What is ollection API* Answer: !he Collection PI 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.
;.
$ +.
+/7lic inter4ace sam+leInter4ace Q +/7lic void 4/nctionOne98 +/7lic long CO!!]OE T 1### . 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. n /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+le 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 6. E,plain the new !eatures o) JDB '.9 ore API* Answer: !he &6BC 2.# PI incl/des the com+lete &6BC PI, ;hich incl/des 7oth core and O+tional Pac)age PI, and +rovides ind/ctrialAstrength data7ase com+/ting ca+a7ilities. e; (eat/res in &6BC 2.# Core PI •
• • • • •
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 PI +rovides the Batch U+dates 4/nctionalit: to the java a++lications. &ava a++lications can no; /se the Ves/ltet./+date[[[ methods. e; 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
. E,plain #arba#e collection* Answer: ar7age collection is one o4 the most im+ortant 4eat/re o4 &ava. ar7age 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=e4 method 4rom 3ava.lan#.b3ect, the 4inali
5 varia7le ;hen no more in /se. I &ava on calling $ystem.#c4 and >untime.#c42 &DM tries to rec:cle the /n/sed o7jects, 7/t there is no g/arantee ;hen all the o7jects ;ill gar7age collected. ?.
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 &ava • • •
Method overloading Method overriding thro/gh inheritance Method overriding thro/gh the &ava inter4ace
1. What are Access $peci)iers available in Java* Answer ccess s+eci4iers are )e:;ords that determines the t:+e o4 access to the mem7er o4 a class. !hese are • •
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. n 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 classes .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
1. >ea& the )ollowin# pro#ram:
+/7lic class test Q +/7lic static void main9tring RS args8 Q int * T 3 int : T 1 i4 9* T :8 :stem.o/t.+rintln9ot e@/al8 else :stem.o/t.+rintln9E@/al8 What is the res/lt . !he o/t+/t is E@/al B. !he o/t+/t in ot E@/al C. n error at i4 9* T :8 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. +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 1. 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
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. '.
'?.
5 ;. Whats new with the stop42 suspen&4 an& resume4 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 class 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: +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. ++.
5 '. Hame omponent subclasses that support paintin#. Answer: !he Canvas, (rame, Panel, and ++let classes s/++ort +ainting ;. What is a native metho&* Answer: native method is a method that is im+lemented in a lang/age other than &ava +.
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. D! 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. E! What is an abstract ethod?
Answer: n 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: 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: +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 nonstatic inner class?
Answer: nonAstatic inner class ma: have o7ject instances that are associated ;ith instances o4 the classLs o/ter class. static inner class does not have an: o7ject instances. D7! What is an objects loc9 and which objects have loc9s?
Answer: n o7jectLs loc) is a mechanism that is /sed 7: m/lti+le threads to o7tain s:nchroni
5 D8! When can an object reference be cast to an interface reference?
Answer: n o7ject re4erence 7e cast to an inter4ace re4erence ;hen the o7ject im+lements the re4erenced inter4ace.
+. 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. .What &o heavy wei#ht components mean* Answer: eav: ;eight com+onents li)e 7stract Windo; !ool)it 9W!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 ative 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. 6. Which pac8a#e has li#ht wei#ht components* Answer: java*.;ing +ac)age. ll com+onents in ;ing, e*ce+t &++let, &6ialog, &(rame and &Windo; are light;eight com+onents. . What are peerless components* Answer: !he +eerless com+onents are called light ;eight com+onents. ?. 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. -. What happens when a threa& cannot ac5uire a loc8 on an ob3ect* Answer: I4 a thread attem+ts to e*ec/te a s:nchroniea&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: 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: 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: 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. ?. 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. ??.
5 -9. What a&vanta#e &o Javas 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
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. -. 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.
' Answer: Windo;, (rame, 6ialog, (ile6ialog, Panel, ++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'.
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 Vandomccess(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: n o7ject m/st im+lement the erialiesourceBun&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: croll7ar is a Com+onent, 7/t not a Container. crollPane is a Container. 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: &ava +ac)age is a naming conte*t 4or classes and inter4aces. +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
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). 11.
' Answer: o. !he: are com+letel: di44erent. ome s:nta* ma: 7e similar. 11-.What is a ontainer in a GI*
Answer: 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
Answer:
We can disc/ss s/ch iss/e 4rom the 4ollo;ing as+ects o
O7jects allo; +roced/res to 7e enca+s/lated ;ith their data to red/ce +otential inter4erence.
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. o
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: /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 a7stract a7stract class ma: contain concrete methods.
inter4ace contains varia7les that m/st 7e static and 4inal a7stract class ma: contain nonA4inal and 4inal varia7les. o
o
mem7ers in an inter4ace are +/7lic 7: de4a/lt, a7stract class ma: contain nonA+/7lic mem7ers.
o
inter4ace is /sed to im+lements ;hereas a7stract class is /sed to e*tends.
o
inter4ace can 7e /sed to achieve m/lti+le inheritance a7stract class can 7e /sed as a single inheritance.
inter4ace can e*tends another inter4ace, a7stract class can e*tends another class and im+lements m/lti+le inter4aces. o
o
inter4ace is a7sol/tel: a7stract a7stract class can 7e invo)ed i4 a main98 e*ists.
inter4ace is more 4le*i7le than a7stract class 7eca/se one class can onl: e*tends one s/+er class, 7/t im+lements m/lti+le inter4aces. o
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 ns a. 28 On s/ccess4/l com+ilation a 4ile ;ith the class e*tension is created. a8 !r/e 78 (alse ns a. 38 !he &ava so/rce code can 7e created in a ote+ad editor. a8 !r/e 78 (alse ns a. $8 !he &ava Program is enclosed in a class de4inition. a8 !r/e 78 (alse ns a. 58 What declarations are re@/ired 4or ever: &ava a++lication ns class and the main9 8 method declarations. '8 What are the t;o +arts in e*ec/ting a &ava +rogram and their +/r+oses ns !;o +arts in e*ec/ting a &ava +rogram are &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 them ns Enca+s/lation, Inheritance and Pol:mor+hism are the three OOPs Princi+les. Enca+s/lation 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. Inheritance Is the +rocess 7: ;hich one o7ject ac@/ires the +ro+erties o4 another o7ject. Pol:mor+hism Is a 4eat/re that allo;s one inter4ace to 7e /sed 4or a general class o4 actions.
-8 What is a com+ilation /nit ns &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 statement :stem.o/t.+rintln9?? Hoo)s li)e a comment.8 ?? Hoo)s li)e a comment !he statement res/lts in a com+ilation error Hoo)s li)e a comment o o/t+/t is dis+la:ed ns 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/e 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 ns 7 118 What are identi4iers and ;hat is naming convention ns Identi4iers are /sed 4or class names, method names and varia7le names. n identi4ier ma: 7e an: descri+tive se@/ence o4 /++er case 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 method ns void 138 What is the arg/ment t:+e o4 +rogramKs main9 8 method ns string arra:. 1$8 Which characters are as 4irst characters o4 an identi4ier ns " `, a " <, ] , 158 What are di44erent comments ns 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 method ns 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_ ns 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: varia7le ns 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 &ava What are their /ses ns &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 declared ns Daria7les can 7e declared an:;here in the method de4inition and can 7e initiali
' 78(alse ns a. 1$8 Which o+erator is to create and concatenate string ns ddition o+erator9X8. 158 Which o4 the 4ollo;ing declare an arra: o4 string o7jects tringR S s tring R Ss tringR sS tring sR S ns a, 7 and d 1'8 What is the val/e o4 aR3S as the res/lt o4 the 4ollo;ing arra: declaration 1 2 3 $ ns d 1%8 Which o4 the 4ollo;ing are +rimitive t:+es 7:te tring integer (loat ns a. 1-8 What is the range o4 the char t:+e # to 21' # to 215 # to 21'A1 # to 215A1 ns. d 108 What are +rimitive data t:+es ns 7:te, short, int, long 4loat, do/7le 7oolean char 2#8 What are de4a/lt val/es o4 di44erent +rimitive t:+es ns 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 ns 7. 228 o; do ;e change the val/es o4 the elements o4 the arra: ns !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 varai7le ns I4 a varia7le is declared as 4inal varia7le, then :o/ can not change its val/e. It 7ecomes constant.
' 2$8 What is static varia7le ns 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 &ava ns O+erators are s+ecial s:m7ols /sed in e*+ressions. !he 4ollo;ing are the t:+es o4 o+erators rithmetic o+erators, ssignment o+erators, Increment 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 ns a. 38 Com+arison?Hogical o+erators are /sed 4or testing and magnit/de. a8!r/e 78(alse ns a. $8 Character literals are stored as /nicode characters. a8!r/e 78(alse ns a. 58 What are the Hogical o+erators ns OV9b8, 698, [OV9G8 6 O!98. '8 What is the o+erator ns 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 13 3 5 % 0 ns c. -8 Is T a valid o+erator ns o. 08 Can a do/7le val/e 7e cast to a 7:te ns Fes 1#8 Can a 7:te o7ject 7e cast to a do/7le val/e ns o. n o7ject cannot 7e cast to a +rimitive val/e. 118 What are order o4 +recedence and associativit: ns Order o4 +recedence the order in ;hich o+erators are eval/ated in e*+ressions. ssociativit: determines ;hether an e*+ression is eval/ated le4tAright or rightAle4t. 128 Which &ava o+erator is right associativit:
' ns T o+erator. 138 What is the di44erence 7et;een +re4i* and +ost4i* o4 AA and XX o+erators ns !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 3,2 !he do/7le val/e -.' !he string -.' !he long val/e -. !he tring 5.$53.2 ns d 158 What are the val/es o4 * and : * T 5 : T XX* ns * T ' : T ' 1'8 What are the val/es o4 * and < * T 5 < T *XX ns * T ' < T 5
ontrol $tatements 18 What are the +rogramming constr/cts ns 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# int j T 55 int < T # < T i = j i j ?? ternar: o+erator :stem.o/t.+rintln9!he val/e assigned is X <8 What is o/t+/t o4 the a7ove +rogram ns !he val/e assigned is 2# 38 !he s;itch statement does not re@/ire a 7rea). a8!r/e 78(alse ns 7. $8 !he conditional o+erator is other;ise )no;n as the ternar: o+erator. a8!r/e 78(alse ns a. 58 !he ;hile loo+ re+eats a set o4 code ;hile the condition is 4alse. a8!r/e
' 78(alse ns 7. '8 !he doA;hile loo+ re+eats a set o4 code atleast once 7e4ore the condition is tested. a8!r/e 78(alse ns a. %8 What are di44erence 7et;een 7rea) and contin/e ns !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 ns a. 08 Can a 4or statement loo+ inde4intel: ns Fes. 1#8 What is the di44erence 7et;een ;hile statement and a do statement? ns ;hile statement chec)s at the 7eginning o4 a loo+ to see ;hether the ne*t loo+ iteration sho/ld occ/r. 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 varia7les ns 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 ns a. 38 class is a tem+late 4or m/lti+le o7jects ;ith similar 4eat/res. a8!r/e 78(alse ns a. $8 What is mean 7: gar7age collection ns 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: de4ined ns 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. methodLs signat/re is a com7ination o4 the 4irst three +arts mentioned a7ove. '8 What is calling method ns Calling methods are similar to calling or re4erring to an instance v aria7le. !hese methods are accessed /sing dot notation. E* o7j.methodname9+aram1,+aram28 %8 Which method is /sed to determine the class o4 an o7ject
% ns 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 ll the classes in java.lang +ac)age are a/tomaticall: im+orted ;hen a +rogram is com+iled. a8!r/e 78(alse ns a. 08 o; can class 7e im+orted to a +rogram ns !o im+ort a class, the im+ort )e:;ord sho/ld 7e /sed as sho;n. im+ort classname 1#8 o; can class 7e im+orted 4rom a +ac)age to a +rogram ns im+ort java . +ac)agename . classname 9or8 im+ort java.+ac)age name.Z 118 What is a constr/ctor ns constr/ctor is a s+ecial )ind o4 method that determines ho; an o7ject is initiali
1'8 Casting 7et;een +rimitive t:+es allo;s conversion o4 one +rimitive t:+e to another. a8!r/e 78(alse ns a. 1%8 Casting occ/rs commonl: 7et;een n/meric t:+es. a8!r/e 78(alse ns a. 1-8 Boolean val/es can 7e cast into an: other +rimitive t:+e. a8!r/e 78(alse ns 7. 108 Casting does not a44ect the original o7ject or val/e. a8!r/e 78(alse ns a. 2#8 Which cast m/st 7e /sed to convert a larger val/e into a smaller one ns E*+licit cast. 218 Which cast m/st 7e /sed to cast an o7ject to another class ns +eci4ic cast. 228 Which o4 the 4ollo;ing 4eat/res are common to 7oth &ava CXX .!he class declaration
% 7.!he access modi4iers c.!he enca+s/lation o4 data methods ;ith in o7jects d.!he /se o4 +ointers ns a,7,c. 238 Which o4 the 4ollo;ing statements acc/ratel: descri7e the /se o4 access modi4iers ;ithin a class de4inition a.!he: can 7e a++lied to 7oth data 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 ns 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 class a.:es 7.no ns 7. 258 Which o4 the 4ollo;ing statements can 7e /sed to descri7e a +/7lic method 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 ns a,c. 2'8 Which o4 the 4ollo;ing t:+es o4 class mem7ers can 7e +art o4 the internal +art o4 a class a.P/7lic instance varia7les 7.Private instance varia7les c.P/7lic methods d.Private methods ns 7,d. 2%8 Fo/ ;o/ld /se the ]]]] o+erator to create a single instance o4 a named class. a.ne; 7.dot ns a. 2-8 Which o4 the 4ollo;ing statements correctl: descri7es the relation 7et;een an o7ject and the instance varia7le it stores 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 o 7jects ns 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 ns a. 3#8 What are the 4/nctions o4 the dot9.8 o+erator 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
% ns a,7,c. 318 Which o4 the 4ollo;ing can 7e re4erenced 7: this varia7le a.!he instance varia7les o4 a class onl: 7.!he methods o4 a class onl: c.!he instance varia7les and methods o4 a class ns c. 328 !he this re4erence is /sed in conj/nction ;ith ]]]methods. a.static 7.nonAstatic ns 7. 338 Which o4 the 4ollo;ing o+erators are /sed in conj/nction ;ith the this and s/+er re4erences a.!he ne; o+erator 7.!he instanceo4 o+erator c.!he dot o+erator ns c. 3$8 constr/ctor is a/tomaticall: called ;hen an o7ject is instantiated a. tr/e 7. 4alse ns a. 358 When ma: a constr/ctor 7e called ;itho/t s+eci4:ing arg/ments 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 ns c. 3'8 Each class in java can have a 4inali
% 7.4alse ns a. $28 are o7jects re4erenced 7: a varia7le candidates 4or gar7age collection ;hen the varia7le goes o/t o4 sco+e a :es 7. no ns a. $38 &avaLs gar7age collector r/ns as a ]]] +riorit: thread ;aiting 4or ]]+riorit: threads to relin@/ish the +rocessor. a.high 7.lo; ns a,7. $$8 !he gar7age collector ;ill r/n immediatel: ;hen the s:stem is o/t o4 memor: a.tr/e 7.4alse ns 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 ]]] ns n/ll $'8 When might :o/r +rogram ;ish to r/n the gar7age collecter 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
% 5$8 What is meant 7: Passing 7: val/e and Passing 7: re4erence ns o7jects " +ass 7: re4errence Methods A +ass 7: val/e 558 Is a class a s/7class o4 itsel4 ns class is a s/7class itsel4. 5'8 What modi4iers ma: 7e /sed ;ith to+Alevel class ns +/7lic, a7stract, 4inal. 5%8 What is an e*am+le o4 +ol:mor+hism Inner class non:mo/s classes Method overloading Method overriding ns c
Pac8a#es an& inter)ace 18 What are +ac)ages ;hat is /se o4 +ac)ages ns !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 +)g 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 java.a++let.++let and java.a++let.Z ns java.a++let.++let ;ill im+ort onl: the class ++let 4rom the +ac)age java.a++let Where as java.a++let.Z ;ill im+ort all the classes 4rom java.a++let +ac)age. 38 What do :o/ /nderstand 7: +ac)age access s+eci4ier ns +/7lic n:thing declared as +/7lic can 7e accessed 4rom an:;here +rivate n:thing declared in the +rivate canKt 7e seen o/tside o4 its class. de4a/lt It is visi7le to s/7classes as ;ell as to other classes in the same +ac)age. $8 What is inter4ace What is /se o4 inter4ace ns 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 inter4ace ns Fes. ll the methods have to 7e im+lemented. '8 Which is the de4a/lt access modi4ier 4or an inter4ace method ns +/7lic. %8 Can ;e de4ine a varia7le in an inter4ace and ;hat t:+e it sho/ld 7e ns 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 class ns ll 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 ns !r/e 1#8 &ava com+iler stores the .class 4iles in the +ath s+eci4ied in CHP! environmental varia7le. !r/e?(alse
% ns (alse 118 UserAde4ined +ac)age can also 7e im+orted j/st li)e the standard +ac)ages. !r/e?(alse ns !r/e 128 When a +rogram does not ;ant to handle e*ce+tion, the ]]]]]]class is /sed. ns !hro;s 138 !he main s/7class o4 the E*ce+tion class is ]]]]]]] class. ns V/ntimeE*ce+tion 1$8 Onl: s/7classes o4 ]]]]]]class ma: 7e ca/ght or thro;n. ns !hro;a7le 158 n: /serAde4ined e*ce+tion class is a s/7class o4 the ]]]]] class. ns E*ce+tion 1'8 !he catch cla/se o4 the /serAde4ined e*ce+tion class sho/ld ]]]]]] its Base class catch cla/se. ns E*ce+tion 1%8 ]]]]]]] is /sed to se+arate the hierarch: o4 the class ;hile declaring an Im+ort statement. ns Pac)age 1-8 ll standard classes o4 &ava are incl/ded ;ithin a +ac)age called ]]]]]. ns java.lang 108 ll the classes in a +ac)age can 7e sim/ltaneo/sl: im+orted /sing ]] ]]. ns Z 2#8 Can :o/ de4ine a varia7le inside an Inter4ace. I4 no, ;h: I4 :es, ho; ns. FE. 4inal and static 218 o; man: concrete classes can :o/ have inside an inter4ace ns. one 228 Can :o/ e*tend an inter4ace ns. Fes 238 Is it necessar: to im+lement all the methods o4 an inter4ace ;hile im+lementing the inter4ace ns. o 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 ns. a7stract 258 o; do :o/ achieve m/lti+le inheritance in &ava ns Using inter4aces. 2'8 o; to declare an inter4ace e*am+le ns access class classname im+lements inter4ace. 2%8 Can :o/ achieve m/lti+le inter4ace thro/gh inter4ace a8!r/e 78 4alse ns a. 2-8 Can varia7les 7e declared in an inter4ace I4 so, ;hat are the modi4iers ns Fes. 4inal and static are the modi4iers can 7e declared in an inter4ace. 208 What are the +ossi7le access modi4iers ;hen im+lementing inter4ace methods ns +/7lic. 3#8 Can anon:mo/s classes 7e im+lemented an inter4ace ns Fes. 318 Inter4aces canKt 7e e*tended.
% a8!r/e 78(alse ns 7. 328 ame inter4aces ;itho/t a method ns eriali
% Collections 3rae Wor9 Collection classes 7stract collection 7stract Hist 7stract et rra: Hist Hin)ed Hist ash set !ree et ash Ma+ !ree Ma+ 7stract e@/ential Hist
Collection Inter4aces Collection Hist et orted et Ma+ Iterator
Hegac: classes 6ictionar: ash !a7le tac) Dector Pro+erties
Hegac: inter4ace En/merator
Wh: hashset is not allo;ing d/+licate element 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 7stract collection Im+lements most o4 the collection inter4aces. 7stract Hist E*tends 7stract collection Im+lements Hist Inter4ace. 7stract Hist allo; random access. Methods>> void add 9int inde*, O7ject element8, 7oolean add9O7ject o8, 7oolean addll9Collection c8, 7oolean addll9int inde*, Collection c8, O7ject remove9int inde*8, void clear98, Iterator iterator98. 7stract et E*tends 7stract collection Im+lements et inter4ace. Array "ist rra: Hist e*tends 7stractHist and im+lements the Hist inter4ace. rra:Hist is a varia7le length o4 arra: o4 o7ject re4erences, rra:Hist s/++ort d:namic arra: that gro; as needed. .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. rra: Hist9 .H8 internal node traversal 4rom the start to the end o4 the collection is signi4icantl: 4aster than Hin)ed Hist traversal. .H is a re+lacement 4or Dector.
Methods>>void add 9int inde*, O7ject element8, 7oolean add9O7ject o8, 7oolean addll9Collection c8, 7oolean addll9int inde*, Collection c8, O7ject remove9int inde*8, void clear98, o7ject get9int inde*8, int inde*O49O7ject element8, int latInde*O49O7ject element8, int si
% "in8e& "ist E*tends 7stacte@/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 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 addll9Collection c8, 7oolean addll9int 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>7oolean add9O7ject o8, Iterator iterator98, 7oolean remove9O7ject o8, int si> 7oolean add9O7ject o8, 7oolean addll9Collection c8, O7ject 4irst98, O7ject last98, Iterator iterator98, 7oolean remove9O7ject o8.
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. 7stract e@/ential Hist E*tends 7stract collection /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 addll9c8, int i> 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
% Methods >> void add9int inde*, O7ject o7j8, 7oolean addll9int inde*, Collection c8, O7ject get9int inde*8, int inde*O49O7ject o7j8, int lastInde*O49O7ject o7j8, HistIterator iterator98, O7ject remove9int inde*8, O7ject removell9Collection 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 >> /llPointerE*ce+tion, ClassCastE*ce+tion, o/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 )e: and val/e. In ma+ 7oth the )e: val/e are o7jects. Methods >> O7ject get9O7ject )8, O7ject +/t9O7ject ), O7ject v8, int si> 7oolean hase*t98, o7ject ne*t98,void remove98 E*A ra:Hist arr T ne; rra:Hist98 rr.add9c8 Iterator itr T arr.iterator98 While9itr.hashe*t988 Q O7ject element T itr.ne*t98 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 Ma+ 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
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> 4inal void addElement9O7ject element8, 4inal int si
8 Hin)edHist is the 7est one, 7ene4its incl/de 1. Vetains the original retrieval order. 2. as @/ic) insertion at the head?tail 3. 6oesnLt h ave an internal si
8 rra: 5rray of fixed len"th of same data type@ we can store primiti!e data types as well as class ob4ects. rra:s
are initiali
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 =o+tion val/eT>ltelect tandard Wor)(lo;gt=?o+tion> = hma+ T9ashMa+8re@/est.getttri7/te9std;48 i49 hma+.si
Q Integer )e: T 9Integer8it.ne*t98 > =o+tion val/eT=T)e:>>=T9tring8hma+.get9)e:8>=?o+tion> = > =?select>
8 Vetrieving data 4rom a collection +/7lic class Iterator6emo Q +/7lic static void main9tring argsRS8 Q Collection c T ne; rra:Hist98 ?? dd ever: +arameter to o/r arra: list 4or 9int ind* T # ind* = args.length ind*XX8 Q c.add9argsRind*S8
?? E*amine onl: those +arameters that start ;ith A Iterator i T c.iterator98 ?? PVE Collection has all +arameters ;hile 9i.hase*t988 Q tring +aram T 9tring8 i.ne*t98 ?? Use the remove method o4 iterator i4 9Y +aram.startsWith9A8 8 i.remove98
?? PO! Collection onl: has +arameters that start ;ith A ?? 6emonstrate 7: d/m+ing collection contents Iterator i2 T c.iterator98 ;hile 9i2.hase*t988 Q :stem.o/t.+rintln 9Param X i2.ne*t988 8 o; do I sort an arra:
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+
rra:s.sort9therra:8 If,
howe!er, it is an array of ob4ects that d onQt implement the 6omparable interface then you need to pro!ide a custom 6omparator to help you sort the elements in the array.
rra:s.sort9therra:, theCom+arator8 TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
-
:ception 2andlin-
Object
Throwable rror 5-T rror
xception
Virtual Machine rror 6ompile time x. (chec2ed)
0ut0fMemory. tac20!er*low.
0*.
Runtime xception (Pnchec2ed)
*ilenot*ound. 5rithmetic.
5rrayIndexout0f&ound.
ull%ointer. Indexoutof &ound.
tirn"Indexout0f&ound
:ceptions
8! 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 ? , b ? F, c @ try < c?aEb@ 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 *ileInputtream( trin" filename ) throws *ileot*oundxception public !oid sleep( int milliseconds ) throws Interruptedxception In the abo!e statements, *ileot*oundxception and Interruptedxception are chec2ed exceptions. That is, when *ileInputtream( trin" filename ) constructor is used by the pro"rammer, he should write a try 1 catch mechanism for *ileot*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 . E F ) prints (nfinity and not an exception ). *ollowin" example illustrates+ public class xceptionCandled < public static !oid main( trin" ar"s= > ) < int a ? , b ? F, c @ try < c?aEb@ 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 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= > ) @ EE th 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, 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 *ileInputtream( trin" filename ) throws *ileot*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 < *ileInputtream fis ? new *ileInuttream( a.txt ) @ ystem.out.println( Cello ) @ A catch( *ileot*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 *ileot*oundxception < *ileInputtream fis ? new *ileInuttream( 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 ? FF, 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 ob4ectoriented 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 5rrayIndex0ut0f&oundsxception c) umber*ormatxception etc.
b)
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 ? , b ? F, c @ c?aEb@ 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 ? , b ? F, c @ try < c?aEb@ 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 runtime 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= > ) @ The abo!e statement raises an exception called 5rrayIndex0ut0f&oundsxception as element does not exist in the array. c) A"ber3orat:ception >
th
0
The abo!e exception is raised when a strin" !alue is not parsed successfully at runtime. The followin" code illustrates + trin" str ? '.:' @ int x ? Inte"er.parseInt( str ) @ If .: is replaced with , it wor2s. 8 6i44 7?; E*ce+tion 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:. n 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;n 8 Fes, an e*ce+tion can 7e rethro;n. 8 tr:, catch, thro;, thro;s !his is /sed to 4i* /+ the error, to +revent the +rogram 4rom a/tomaticall: terminating, tr:Acatch is tr: /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/ght 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: statement !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 UnChec)ed E*ce+tion A 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 method 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 chart98 method 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 9o5uch2ethodException
ArithmeticException Arra%ndexutf1oundException
o/ch(ieldE*ce+tion Interr/+tedE*ce+tion
ClasscastE*ce+tion Illegalrg/mentE*ce+tion
0 llegalAccessException Clone9ot5upportedException
IllegalMonitorateE*ce+tion Illegal!hreadtateE*ce+tion Inde*O/tO4Bo/ndE*ce+tion /llPointerE*ce+tion /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. rra:Inde*O/tO47o/nd AA> (or accessing an arra: element 7: +roviding an inde* val/es =# or > or e@/al to the arra: si (or accessing character o4 a string or string 7/44er ;ith inde* val/es =# or > or e@/al to the arra: si s/ch as divide 7: ssignment to an arra: element o4 an incom+ati7le t:+es. ClasscastE*ce+tion AA> Invalid casting. Illegalrg/ment E*ce+tion AA> Illegal arg/ment is /sed to invo)e a method. /ll+ointer E*ce+tion AA> I4 attem+t to made to /se a n/ll o7ject. /m7er(ormat E*ce+tion AA> Invalid conversition o4 string to n/meric 4ormat. Classot4o/nd E*ce+tion AA> class not 4o/nd. Instantion E*ce+tion AA> ttem+t to create an o7ject o4 an 7stract class or Inter4ace. os/ch(ield E*ce+tion AA> re@/est 4ield does not e*ist. os/chMethod E*ce+tion AA> re@/est method does not e*ist. 8 Methods in E*ce+tions 8 getMessage98, totring98, +rinttac)!race98, getHocali
!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 sendError 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 xx
4%pe nformation al 5uccess
?xx
Redirection
@xx
Client Error 5erver Error
xx
;escription Re=uested received3 continuing to process 4he action $as successfull% received3 understood3 and accepted :urther action must "e ta&en in order to complete the re=uest 4he re=uest contains "ad s%ntax or cannot "e fulfilled 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 lowle!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. *ileInpusttream is "enerally used to read byte by byte from a file and *ile0utputtream is used to write byte by byte to a file. 7! Character Streas> jd9 6!6 !ersion, introduces character based streams. 6haracterbased input and output streams( subclasses of Reader and -riter classes) pro!ide se!eral ad!anta"es. -hile byte streams( subclasses of Inputtream and 0utputtream classes) reads bit 56II byte at a time, characterbased streams reads 9Kbit 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 *ilterInputtream and *ilter0utputtream 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+ DineumberInputtream, #ataInputtream, and %ushbac2Inputtream etc. The extra functionality "i!en by the DineumberInputtream is, it adds line numbers in the destination file that does not exist in the source file. %ushbac2Inputtream 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"hle!el stream is a lowle!el stream. 5nd also a hi"h le!el stream can be lin2ed to another hi"hle!el stream. The followin" code snippet illustrates+ Connectin- a lowlevel strea to a hi-hlevel strea>
*ileInputtream fis ? new *ileInputtream( a.4a!a ) @ EE a lowle!el stream #ataInputtream dis ? new #ataInputtream( fis ) @ EE a hi"hle!el stream In the abo!e code, fis, a lowle!el input stream is passed as parameter to a hi"hle!el stream, #ataInputtream. Connectin- a hi-hlevel strea to another hi-hlevel strea>
*ileInputtream fis ? new *ileInputtream( a.4a!a ) @ EE a lowle!el stream &ufferedInputtream bis ? new &ufferedInputtream( fis ) @ EE a hi"hle!el stream #ataInputtream dis ? new #ataInputtream( bis ) @ EE a hi"hle!el stream In the abo!e code, bis, a hi"hle!el stream ob4ect is passed as a parameter to another hi"h le!el stream, #ataInputtream. H7! Write notes on read# ) and read;ine# ) ethods ?
6! read# ) ethod> read# ) method is defined as an abstract method in Inputtream class and is implemented by all its subclasses. read( ) method reads a byte from a file and returns an inte"er !alue 1 the 56II !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 Inputtream class public int read( ) throws I0xception EE o!erridden in *ileInputtream class
7! read;ine# ) ethod> read;ine# ) method is defined in #ataInput interface. #ataInput interface is implemented by #ataInputtream. The abstract readDine( ) method of #ataInput interface is implemented("i!en a body) by #ataInputtream.
readDine( ) method reads a line( character by character until n is encountered ) from the source file and returns a strin". This method throws I0xception, a chec2ed exception. readDine( ) method is also a!ailable in &ufferedInputtream on character streams side. readDine( ) method of #ataInputtream is deprecated, but the readDine( ) method of &ufferedInputtream 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 ! 3ile*eader ! *ando%ccess3ile D! 3ile E! B"ffered(np"tStrea F! .rintStrea ?
6! (np"tStrea >
5n Inputtream 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 Inputtream class is an abstract class that ser!es as the base class for many input stream classes li2e *ileInputtream, e8uenceInputtream, 0b4ectInpusttream 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 Inputtream class, *ileInputtream class is "enerally used for performin" simple file input operations. To wor2 with *ileInputtream class, there are three steps to perform + 9. 0pen a file+ 5 file can be opened in readin" mode by usin" *ileInputtream constructor as follows+ *ileInputtream fis ? new *ileInputtream( a.4a!a ) @ EE throws *ileot*oundxception :. Read from the file+ &yte by byte can be read from the file by usin" read( ) method of the *ileInputtream 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 0utputtream class, *ile0utputtream class is "enerally used for performin" simple file output operations. To wor2 with *ile0utputtream class, there are three steps to perform+ 9. 0pen a file+ 5 file can be opened in writin" mode by usin" *ile0utputtream constructor as follows+ *ile0utputtream fos ? new *ile0utputtream( b.4a!a ) @
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 *ile0utputtream class as follows+ fos.write( 2 ) @ EE where 9 is an 56II 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 >
#ataInputtream is a hi"hle!el stream and is a subclass of *ilterInputtream. #ataInputtream also implements #ataInput interface. #ataInputtream 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 #ataInputtream is deprecated, but the readDine( ) method of &ufferedInputtream is not. #ataInputtream, bein" a hi"h le!el stream, can not read and write directly and to be lin2ed to a low le!el stream. #ataInputtream can also be lin2ed to another hi"h le!el stream for extra functionality. *ollowin" illustrates+ *ileInputtream fis ? new *ileInputtream( a.4a!a ) @ EE a lowle!el stream &ufferedInputtream bis ? new &ufferedInputtream( fis ) @ EE a hi"hle!el stream #ataInputtream dis ? new #ataInputtream( bis ) @ EE a hi"hle!el stream 5n example usin" #ataInputtream+ ( readin" 2eyboard input )
import 4a!a.io.N @ public class Ja!acanf < public static !oid main(trin" ar"s=>) throws I0xception < #ataInputtream dis ? new #ataInputtream( ystem.in ) @ ystem.out.println( ' nter somethin"+' ) @ trin" str ? dis.readDine( ) @ ystem.out.println( ' Lou enetered+ ' B str ) @ A A ! 3ile*eader > jd9 6!6 !ersion, introduces character based streams. 6haracterbased input and output streams( subclasses of Reader and -riter classes) pro!ide se!eral ad!anta"es. -hile byte streams( subclasses of Inputtream and 0utputtream classes) reads bit 56II byte at a time,
0
characterbased streams( subclasses of Reader and -riter classes) reads 9Kbit Pnicode characters. Cierarchy+ 0b4ect
Reader InputtreamReader *ileReader
*ileReader, an indirect subclass of Reader class, is a prominent class to read characters from a file. *ileReader fr ? new *ileReader( #emo.txt ) @ ! *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 *ileInputtream, 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 ) @ 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 online 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 ) @
*ileInputtream constructor will accept this ob4ect also as follows+ *ileInputtream fis ? new *ileInputtream( 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 &ufferedInputtream and &uffered0utputtream 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 &ufferedInputtream uses bufferin" effect.
0 &ufferedInputtream is a hi"h le!el stream as it is a subclass of *ilterInputtream. &ein" a hi"h le!el stream, it cannot read a file directly. 5lways it re8uires a low le!el stream li2e *ileInputtream ob4ect as a parameter. The followin" is the code snippet+
*ileInputtream fis ? new *ileInputtream( ' a.4a!a ' ) @ &ufferedInputtream bis ? new &ufferedInputtream( fis ) @ The followin" full pro"ram illustrates the use of &ufferedInputtream+
( 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 < *ileInputtream fis ? new *ileInputtream( ' a.4a!a ' ) @ &ufferedInputtream bis ? new &ufferedInputtream( 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( ) ) ? 9 ) < sb.append( ( char ) 2 ) @ A ystem.out.println( sb ) @ A A
F! .rintStrea >
%rinttream class belon"s to byte streams. 5 %rinttram adds functionality to another output stream. pecial features of %rinttream are + 9. Pnli2e other output streams, a %rinttream ne!er throws an I0xception@ instead, in exceptional situations merely set an internal fla" that can be tested !ia the chec2rror method. :. %rinttream 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 %rinttream in character streams. %rint-riter class should be used in situations that re8uire writin" characters rather than bytes. The followin" is the hierarchy. 0b4ect
0utputtream
The followin" code illustrates+ import 4a!a.io.N@ public class %rinttream#emo < public static !oid main( trin" ar"s= > ) <
*ilter0utputtream
%rinttream
0 %rinttream ps ? new %rinttream( ystem.out ) @ ps.println('hello')@ ps.println(:)@ ps.println(.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, : ) @ while( st.nextTo2en( ) ? st.TTX0*) < if( st.ttype ? ? st.TTX-0R# ) 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
EE if to2en is not 0* EE if to2en is a word
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. ;ord to)en consists o4 a ;ord constit/ent 4ollo;ed 7:
#ataInputtream is a byte stream. It is a hi"hle!el stream and a subclass of *ilterInputtream. #ataInputtream implements #ataInput interface. The followin" is the hierarchy. 0b4ect Inputtream *ilterInputtream #ataInputtream 5s it is a hi"hle!el stream it cannot read directly a source( a file or 2eyboard input etc. ). It must be lin2ed to a lowle!el stream. *or additional functionality, it can be lin2ed to another hi"h le!el stream also.
0
#ataInputtream defines methods li2e readInt( ), read#ouble( ) and readDine( ) etc., that reads an inte"er, a double and a line as a whole. 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 #atatream#emo < public static !oid main( trin" ar"s= > ) < try < *ileInputtream fis ? new *ileInputtream( ' Cello.4a!a ' ) @ #ataInputtream dis ? new #ataInputtream( fis ) @ trin" str @ while( ( str ? dis.readDine( ) ) ? null ) ystem.out.println( str ) @ dis.close( ) @ fis.close( ) @
EE lowle!el stream EE hi"hle!el stream
EE a temporary strin" !ariable
EE close the streams in re!erse order
A catch( I0xception e ) < e.printtac2Trace( ) @ 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 Constr"ctor
*ileInpusttream( ) readDine( ) close( )
:ception
*ileot*oundxception I0xception I0xception
18 What is the di44erence 7et;een thro;K and thro;sK nd itKs a++lication ns E*ce+tions that are thro;n 7: java r/ntime s:stems can 7e handled 7: 7 : !r: and catch 7loc)s. With 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 E*ce+tionK and errorK in java ns 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 Veso/rce lea)K ns (reeing /+ other reso/rces that might have 7een allocated at the 7eginning o4 a method. $8What is the 4inall:K 7loc) ns (inall: 7loc) ;ill e*ec/te ;hether or not an e*ce+tion is thro;n. I4 an a n e*ce+tion is thro;n, the 4inall: 7loc) ;ill e*ec/te even i4 no catch statement match the e*ce+tion. n: time a method is a7o/t to ret/rn to the the caller 4rom inside tr:?catch 7loc), via an /nca/ght /n ca/ght e*ce+tion or an e*+licit e*+ licit ret/rn statement, the 4inall: cla/se is also e*ec/te.
1 58 Can ;e have catch 7loc) ;ith o/t tr: 7loc) I4 so ;hen ns o. !r:?Catch or !r:?4inall: 4orm a /nit. '8 What is the di44erence 7et;een the 4ollo;ing statements Catch 9E*ce+tion e8, Catch 9Error err8, Catch 9!hro;a7le t8 ns
%8 What ;ill ha++en to the E*ce+tion o7ject a4ter e*ce+tion handling ns It ;ill go 4or ar7age Collector. nd 4rees the memor:. -8 o; man: E*ce+tions ;e can de4ine in thro;sK cla/se ns 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 ns !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 ns !r/e 118 E*ce+tions can 7e ca/ght or rethro;n to a calling method. !r/e?(alse ns !r/e 128 !he statements 4ollo;ing the thro; )e:;ord in a +rogram are not e*ec/ted. !r/e?(alse ns !r/e 138 !he totring 9 8 method in the /serAde4ined e*ce+tion class is overridden. !r/e?(alse ns !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 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 instance thread is not considered to be alive. f the start"# method is not invo&ed 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 -h at is is the the dif diffe fere renc nce e betw betwee een n %roc %roces ess s and and Th Thre read adY Y A process is a self contained execution environment and it can be seen as a program or application whereas Thread is is a single task task of execution execution within within the process. process. Java runtime runtime environment environment runs as a single process process which which contains dierent 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 -h at ar are e th the e ben benef efit its s of of mu mult lti ith thre read aded ed pr pro" o"ra ramm mmin in"Y "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 -h at is di diff ffer eren ence ce be betw twee een n use userr Thr Threa ead d and and da daem emon on Th Thre read adY Y *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.
.
Cow Co w ca can n we cr cre eat ate e a T hre rea ad in in Ja Ja! !aY There are are two wa"s to create create Thread Thread in Java - rst rst b" implementing implementing /unnable /unnable interface interface and then then creating creating a Thread ob+ect ob+ect from from it and second second is to extend extend the Thread Thread #lass. /ead /ead this post to learn learn more more about creating threads in +ava. +ava .
.
-hat -h at are are di diff ffer eren entt stat states es in in life lifecy cycl cle e of Thr hrea eadY dY *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. thread.
K.
6an 6a n we we cal calll run run() () me meth thod od of a Th Thre read ad cl clas assY sY
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 specic time, once the thread awake from sleep, it&s state gets changed to runnable and based on thread scheduling, it gets executed.
.
-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 contextswitchin" in multithreadin"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 eorts. 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
9. -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.
9.
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
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.
9.
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
: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 occured@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 $roler, 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
: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.
:.
-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
it&s possible to make them fair
•
it&s possible to make a thread responsive to interruption while waiting on a
•
it&s possible to tr" to acquire the lock, but return immediatel" or after a timeout if the lock can&t be acquired
•
H.
it&s possible to acquire and release locks in dierent scopes, and in dierent orders
-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.
.
-hat is &loc2in"ZueueY Cow can we implement %roducer6onsumer 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 .
.
-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 dene 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 #oncurrentodication7xception. #oncurrent #ollection classes support full concurrenc" of retrievals and ad+ustable expected concurrenc" for updates. a+or classes are #oncurrent:ashap, #op"1n*riteArra"
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.
"ltithreadinH! 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. PVOPVM
!;o !hreads
$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 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# ) ! notify# ) ! 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 6G I i + + ) Syste!o"t!println# i ) I T public static !oid main( trin" ar"s = > ) < #emo d9 ? new #emo( ) @ d9.start( ) @ A A
prints G to F n"bers
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 ) @ try R $hread!sleep# 6GGG ) I
EE prints F to O numbers
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. thread and terinates it and the thread ob4ect is liable for "arba"e collection!
stop# ) ethod 9ills a
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# ) ! notofy# ) ! 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 (O bloc9inHewly reate&
start# )
Runnable
res"e# )4 notify# )4 sleep tieo"t4 (O finished
stop# )
stop# )
stop# ) e a d
$he $hread life Cycle
l o c 9 e d
B
1 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.
G! What ethods can stop a thread ? 5 runnin" thread can be stopped with the followin" methods defined in Thread class. 9. :. H. .
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. 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. 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.
6! 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.
:. -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 subdirectories) and files). p"blic class $hread1ro"p e:tends Object Constr"ctors
escription
public ThreadGroup( trin" name ) public ThreadGroup( ThreadGroup parent, trin" name ) ethods
a thread "roup is created by a name assi"nin" to a "roup with a name
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" "etame( ) 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."etame( ) ) @ EE ThreadF 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."etame( ) ) @ EE MyGroup 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:."etame( ) ) @ 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.
8!
: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"I <>EADIH 18 What are the t;o t:+es o4 m/ltitas)ing ns 1.+rocessA7ased 2.!hreadA7ased 28 What are the t;o ;a:s to create the thread ns 1.7: im+lementing V/nna7le 2.7: e*tending !hread 38 What is the signat/re o4 the constr/ctor o4 a thread class ns !hread9V/nna7le threado7,tring threadame8 $8 What are all the methods availa7le in the V/nna7le Inter4ace ns r/n98 58 What is the data t:+e 4or the method islive98 and this method is availa7le in ;hich class ns 7oolean, !hread '8 What are all the methods availa7le in the !hread class ns 1.islive98 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 an d ;hat is the class in ;hich these methods are de4ined ns 1. ;ait98,noti4:98 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 time ns :nchronisation 08 What is the +roced/re to o;n the moniter 7: man: threads ns not +ossi7le 1#8 What is the /nit 4or 1### in the 7elo; statement o7.slee+91###8 ns long milliseconds 118 What is the data t:+e 4or the +arameter o4 the slee+98 method ns long 128 What are all the val/es 4or the 4ollo;ing level ma*A+riorit:
1 minA+riorit: normalA+riorit: ns 1#,1,5 138 What is the method availa7le 4or setting the +riorit: ns setPriorit:98 1$8 What is the de4a/lt thread at the time o4 starting the +rogram ns main thread 158 !he ;ord s:nchroni
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 @ Thread t @
EE name of a thread
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 F @ i ) < ystem.out.println( name B ' > ' B i ) @ Thread.sleep( 9FFF ) @ A A catch( Interruptedxception e ) < e.printtac2Trace( ) @ 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.printtac2Trace( ) @ 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,.main >
1
ew thread+Thread= Two,,main > ew thread+Thread= Three,,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,.main > ew thread+Thread= Two,,main > ew thread+Thread= Three,,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. H! :palin rethrowin- of an e:ception with an e:aple ?
1 *ethrowin- 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 ). Rethrowin" can be done for extra functionality from the callin" method. -e can ha!e output from the catch methods o f 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 ? , 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 +rogram 8 (inali
8 6i44 +rocess and threads
1 8 !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 Program can contain more than one thread. 9v8 +rogram /nder e*ec/tion is called as +rocess. 8 lee+98, ;ait98, noti4:98, noti4:ll98, 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:ll9 8 ;a)es /+ all the threads that called ;ait98 on the same o7ject, the highest +riorit: thread ;ill r/n 4irst. !he thread move to dead state. sto+9 8 s/s+end9 8 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. ;ait 4or a thread to terminate. join9 8 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+9milliseconds8 !hread.slee+9milliseconds,
nanoseconds8
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: MI]PVIOVI!F T 1 OVM]PVIOVI!F T 5 M[]PVIOVI!F T 1# 8 Can I restart a sto++ed thread 8 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 im+lements V/nna7leQ !hread t P/7lic clic)er9int +8Q ! T ne; !hread9this8 t.setPriorit:9+8
1 +/7lic void r/n98Q +/7lic void sto+98Q +/7lic void start98Q t.start98 tr:Q thread.slee+91###8 lo.sto+98 hi.sto+98 tr:Q hi.t.join98 lo.t.join98 class iHoQ +/7lic static void main9tirng argsRS8Q !hread.c/rrent!hread98.setPriorit:9!hread.M[]PVIOVI!F8 Clic)er hi T ne; Clic)er9!hread.OVM]PVIOVI!FX28 Clic)er lo T ne; Clic)er9!hread.OVM]PVIOVI!FA28 Ho.start98 i.start98 8 What is the /se o4 start98 4/nction in starting a thread ;h: ;e do not /se the r/n98 method directl: to r/n the thread tart method tell the &DM that it needs to create a s:stem s+eci4ic thread. 4ter 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 :nchroni
Hocal varia7les Instance varia7les Class varia7les Ve@/est attri7/tes ession attri7/tes Conte*t attri7/tes
M/lti !hreaded Model F F
Java Interview uestions
ingle threaded Model F F F
1
:uestion; ashMap and Map= :uestion; 7ifference between >ashMap and >ashable= :uestion; 7ifference between Vector and (rray6ist= :uestion; 7ifference between !wing and (wt= :uestion;
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 obtainedgenerally 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 :owever, you cant override a static method with a nonstatic method. n other words, you cant change a static method into an instance method in a subclass. %@ !What is final? "!( final class cant be extended ie., final class may not be subclassed. ( final method cant be overridden when its class is inherited. 5ou cant change value of a final variable "is a constant
Java Interview uestions
1
:uestion; :uestion;
ow can one prove that the array is not null but empty= :uestion;
"!t is empty. 8ut not null. 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. 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. Aeceived from !andesh !adhaleD %@ !Can an application have multiple classes havin# main method? "!5es it is possible. ence there is not conflict amongst the multiple classes having main method. 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. 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. 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. 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.'ilenput!treams read"# method 9nchec&ed exceptions are Auntime1xception and any of its subclasses. Class 1rror and its subclasses also are unchec&ed.
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;ow do seriali)e an object to a file= :uestion;ow can customi)e the serali)ation process= i.e. how can one have a control over the seriali)ation process= :uestion;
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 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 its subpac&age. 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 its name.
%@
! 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. Aeceived from !andesh !adhaleD %@ ! What type of parameter passin# does Java support? "! n Java the arguments are always passed by value . 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. Aeceived from !andesh !adhaleD
%@
! 0b-ects are passed by value or by reference? "! Java only supports pass by value.
1 by value and so both the original reference and parameter copy both refer to the same object . 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. 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. 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. 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. Aeceived from !andesh !adhaleD %@ ! What is the common usa#e of serialization? "!
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. 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.
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;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;ow does an exception permeate through the code= :uestion;
! %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. 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.
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. 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. 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. 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. 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.
1
! 'ow to create custom exceptions? "! 5our class should extend class 1xception, or some more specific type thereof. 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. 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. 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. 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
"! 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.
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. 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. 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. 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. Aeceived from !andesh !adhaleD %@
Java Interview uestions :uestion;>ow are %bserver and %bservable used= :uestion;ow does Java handle integer overflows and underflows= :uestion;7oes garbage collection guarantee that a program will not run out of memory= :uestion;ow are this"# and super"# used with constructors= :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.
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. 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. 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. 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 methods 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. 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. Aeceived from !hipra amraD %@ 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 youKve 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. Aeceived from rishna umar D %@
1
!What are the steps in the J%1C connection? "!
Aeceived from !hri @ra&ash unwarD
%@
!'ow does a try statement determine which catch clause should be used to handle an exception? "!
Java Interview uestions :uestion;Can an unreachable object become reachable again= :uestion;
! Can an unreachable ob-ect become reachable a#ain? "! (n unreachable object may become reachable again. his can happen when the objects finali)e"# method is invo&ed and the object performs an operation which causes it to become accessible to reachable objects. Aeceived 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. 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 methods 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. 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"%bjectnput in# 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. 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 doesnt 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#. Aeceived from @ AajeshD %@ ! What does it mean that a method or field is
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. 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. Aeceived from @ AajeshD %@
%ll .ac9a-es
java!lan- .ac9a-e nterfaces Clonea"le
Classes ;ou"le3 :loat3 8ong3 nteger3 5hort3 1%te3 1oolean3 Character3
Runna"le Compara"le
Class3 Class8oader Brocess3 Run4ime3 6oid 5tring3 5tring1uffer 4hread3 4hreadGroup
Exceptions
rithmeticE*ce+tion, rra:Inde*O/tO4Bo/ndO4.E, ClassCast.E, Classot(o/nd.E lleAcess'E3 llegalArgument'E llegal5ate'E3 9ullBointer'E 9o5uch:ield'E3 9o5uch2ethod'E 9um"er:ormat'E
java!(O .ac9a-e nterfaces ;atanputstream ;atautputstream "jectnput5tream "jectutputstream 5erialia"le Externialia"le
Classes 1uffernputstream3 1ufferutput5tream 1ufferReader3 1uffer#riter 1%teArra%nput5tream3 1%teArra%utputstream Characterarra%Reader3 CharacterAra%#riter ;atanput5tream3 ;atautput5tream :ilereader3 :ile#riter "jectnput5tream3 "jectutput5tream
Exceptions
Object class
ll other classes are s/7 classes o4 o7ject class, O7ject class is a s/+er class o4 all other class. Methods A void noti4:98 void noti4:ll98 O7ject clone98 ting totring98 7oolean e@/als9O7ject o7ject8 void ;ait98 void 4inali
1 $hread class
Methods A getame98 r/n98 getPriorit:98 lee+98 islive98 tart98 join98 throwable class
Methods A 5tring get2essage() 5tring to5tring()
6oid print5tac&4race() 4hro$a"le filln5tac&4race()
java!s=l .ac9a-e nterfaces Connection Calla"le5tatement
Classes ;river2anager ;ate
;river
4ime5tamp
Brepared5tatement Result5et Result5et2eta;ata
4ime 4%pes 5.8 Exception3 5.8 #arnings
Exceptions Class9ot:oundExcept ion nstantiation Exception
5tatement ;ata"ase2eta;ata Arra% Barameter2eta;ata Clo"3 1lo" 5.8nput3 5.8utput3 5.8Bermission 5avepoint
java:!s=l .ac9a-e
Inter4aces
Classes
ConnectionEvent8istener
ConnectionEvent
ConnectionBool;ata5ource ;ata5ource BooledConnection Ro$5et Ro$5et8istener Ro$5et2eta;ate Ro$5etReader#riter DAConnection DA;ata5ource
Ro$setEvent
Exceptions
Java:!servlet .ac9a-e nterfaces 5ervlet 5ervletConfig
Classes Generic5ervlet 5ervletnput5tream
5ervletContext
5ervletutput5tream
Exceptions 5ervletException Unavalia"leExcep tion
1 5ervletRe=uest
5ervletContextAttri"ute Event
5ervletResponse 5ingle4hread2odel 5ervletContext8istener 5ervletContextAttri"ute8istener 5ervletContextnitialiation parameters 5ervletRe=uestAttri"ute8istener 5ervletRe=uest8istner :ilter :ilterChain :ilterConfig Re=uest;ispatcher
enericervlet 9C8 +/7lic void destro:98 +/7lic tring getInitParameter9tring name8 +/7lic En/meration getInitParameterames98 +/7lic ervletCon4ig getervletCon4ig98 +/7lic ervletConte*t getervletConte*t98 +/7lic tring getervletIn4o98 +/7lic void init9ervletCon4ig con4ig8 thro;s ervletE*ce+tion +/7lic void log9tring msg8 +/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+tion +/7lic void +rintln98 thro;s IOE*ce+tion 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:98 +/7lic a7stract ervletCon4ig getervletCon4ig98 +/7lic a7stract tring getervletIn4o98 +/7lic a7stract void init9ervletCon4ig con4ig8 thro;s ervletE*ce+tion +/7lic a7stract void service9ervletVe@/est re@, ervletVes+onse res8 ervletCon4ig 9I8 +/7lic a7stract tring getInitParameter9tring name8 +/7lic a7stract En/meration getInitParameterames98 +/7lic a7stract ervletConte*t getervletConte*t98 ervletConte*t 9I8 +/7lic a7stract O7ject getttri7/te9tring name8 +/7lic a7stract tring getVealPath9tring +ath8 +/7lic a7stract tring geterverIn4o98 +/7lic a7stract ervlet getervlet9tring name8 thro;s ervletE*ce+tion +/7lic a7stract En/meration getervletames98 +/7lic a7stract En/meration getervlets98
1 +/7lic a7stract void log9E*ce+tion e*ce+tion, tring msg8 ervletVe@/est 9I8 +/7lic a7stract O7ject getttri7/te9tring name8 +/7lic a7stract tring getParameter9tring name8 +/7lic a7stract En/meration getParameterames98 +/7lic a7stract tringRS getParameterDal/es9tring name8 +/7lic a7stract tring getVealPath9tring +ath8 +/7lic a7stract tring getVemoteddr98 +/7lic a7stract tring getVemoteost98 +/7lic a7stract tring geterverame98 +/7lic a7stract int geterverPort98 Ve@/est6is+atcher getVe@/est6is+atcher9tring +ath8 +/7lic int getHocalPort98 ?? servlet 2.$ +/7lic int getVemotePort98 ?? servlet 2.$ +/7lic tring getHocalame98 ?? servlet 2.$ +/7lic tring getHocalddr98 ?? servlet 2.$ ervletVes+onse 9I8 +/7lic a7stract tring getCharacterEncoding98 +/7lic a7stract PrintWriter getWriter98 thro;s IOE*ce+tion +/7lic a7stract void setContentHength9int len8 +/7lic a7stract void setContent!:+e9tring t:+e8 Java:!servlet!2ttp .ac9a-e nterfaces 7ttp5ervletRe=uest 7ttp5ervletResponse 7ttp5ession 7ttp5ession8istener 7ttp5essionActivation8istener 7ttp5essionAttri"ute8istener 7ttp5ession1inding8istener 7ttp5essionContext (deprecated) :ilter
Classes Coo&ies 7ttp5ervlet (A"starct Class) 7ttpUtils 7ttp5ession1indingEvent
Exceptions 5ervletException Unavalia"leException
ervletConte*tHistener 9I8 +/7lic void conte*tInitiali
p"blic Object clone#)I
+/7lic int getMa*ge98 +/7lic tring getame98 +/7lic tring getPath98 +/7lic tring getDal/e98 +/7lic int getDersion98 +/7lic void setMa*ge9int e*+ir:8
1 +/7lic void setPath9tring /ri8 +/7lic void setDal/e9tring ne;Dal/e8 +/7lic void setDersion9int v8 tt+ervlet 9C8 +/7lic void service9ervletVe@/est re@, ervletVes+onse res8 +rotected void do6elete 9tt+ervletVe@/est re@, tt+ervletVes+onse res8 +rotected void doet 9tt+ervletVe@/est re@, tt+ervletVes+onse res8 +rotected void doO+tions9tt+ervletVe@/est re@, tt+ervletVes+onse res8 +rotected void doPost9tt+ervletVe@/est re@, tt+ervletVes+onse res8 +rotected void doP/t9tt+ervletVe@/est re@, tt+ervletVes+onse res8 +rotected void do!race9tt+ervletVe@/est re@, tt+ervletVes+onse res8 +rotected long getHastModi4ied9tt+ervletVe@/est re@8 +rotected void service9tt+ervletVe@/est re@, tt+ervletVes+onse res8 tt+ession7indingEvent 9C8 +/7lic tring getame98 +/7lic tt+ession getession98 tt+ervletVe@/est 9I8 +/7lic a7stract Coo)ieRS getCoo)ies98 +/7lic a7stract tring geteader9tring name8 +/7lic a7stract En/meration geteaderames98 +/7lic a7stract tring get/er:tring98 +/7lic a7stract tring getVemoteUser98 +/7lic a7stract tring getVe@/estedessionId98 +/7lic a7stract tring getVe@/estUVI98 +/7lic a7stract tring getervletPath98 +/7lic a7stract tt+ession getession97oolean create8 +/7lic a7stract 7oolean isVe@/estedessionId(romCoo)ie98 +/7lic a7stract 7oolean isVe@/estedessionId(romUrl98 +/7lic a7stract 7oolean isVe@/estedessionIdDalid98 tt+ervletVes+onse 9I8 +/7lic a7stract void addCoo)ie9Coo)ie coo)ie8 +/7lic a7stract tring encodeVedirectUrl9tring /rl8 +/7lic a7stract tring encodeUrl9tring /rl8 +/7lic a7stract void sendError9int sc, tring msg8 thro;s IOE*ce+tion +/7lic a7stract void sendVedirect9tring location8 thro;s IOE*ce+tion +/7lic a7stract void addInteader9tring header, int val/e8 +/7lic a7stract void add6ateeader9tring header, long val/e8 +/7lic a7stract void seteader9tring name, tring val/e8 +/7lic a7stract void setInteader9tring header, int val/e8 +/7lic a7stract void set6ateeader9tring header, long val/e8 +/7lic void settat/s98 tt+ession 9I8 +/7lic a7stract long getCreation!ime98 +/7lic a7stract tring getId98 +/7lic setttri7/te9tring name, O7ject val/e8 +/7lic getttri7/te9tring name, O7ject val/e8 +/7lic remove ttri7/te9tring name, O7ject val/e8 +/7lic a7stract long getHastccessed!ime98 +/7lic a7stract tt+essionConte*t getessionConte*t98 +/7lic a7stract O7ject getDal/e9tring name8
1 +/7lic a7stract tringRS getDal/eames98 +/7lic a7stract void invalidate98 +/7lic a7stract 7oolean ise;98 +/7lic a7stract void +/tDal/e9tring name, O7ject val/e8 +/7lic a7stract void removeDal/e9tring name8 +/7lic setMa*InactiveIntervel98 7ttp5ession8istener () pu"lic void sessionCreated(7ttp5essionEvent event)
+/7lic void session6estro:ed9tt+essionEvent event8 tt+essionttri7/teHistener 9I8 +/7lic void attri7/tedded9ervletConte*tttri7/teEvent sca78 +/7lic void attri7/teVemoved9ervletConte*tttri7/teEvent sca78 +/7lic void attri7/teVe+laced9ervletConte*tttri7/teEvent sca78 7ttp5ession1inding8istener ()
+/7lic void tt+essionBindingHistener.val/eBo/nd9tt+essionBindingEvent event8 +/7lic void tt+essionBindingHistener.val/eUn7o/nd9tt+essionBindingEvent event8 7ttp5essionActivation8istener ()
+/7lic void session6idctivate9tt+essionEvent event8 +/7lic void sessionWill+assivate9tt+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 JBC Q"estions 8 What Class.4orame ;ill do ;hile loading drivers 8 Will create an instance o4 the driver and register ;ith the 6riverManager. 8 &6BC 3.# ne; 4eat/res 8 1. !ransaction ave+oint s/++ort A dded 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 A 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 metadata A dded 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:s A dded a means o4 retrieving val/es 4rom col/mns containing a/tomaticall: generated val/es. '. M/lti+le o+en Ves/ltet o7jects A dded the ne; method getMoreVes/lts9int8. %. Passing +arameters to Calla7letatement o7jects 7: name A dded methods to allo; a string to identi4: the +arameter to 7e set 4or a Calla7letatement o7ject. -. olda7le c/rsor s/++ort A dded the a7ilit: to s+eci4: the o4 holda7ilit: o4 a Ves/ltet o7ject. 0. BOOHE data t:+e A dded the data t:+e java.s@l.!:+es.BOOHE. BOOHE is logicall: e@/ivalent to BI!. 1#. Ma)ing internal /+dates to the data in Blo7 and Clo7 o7jects A dded methods to allo; the data contained in Blo7 and Clo7 o7jects to 7e altered. 11. Vetrieving and /+dating the o7ject re4erenced 7: a Ve4 o7ject A dded methods to retrieve the o7ject re4erenced 7: a Ve4 o7ject. lso added the a7ilit: to /+date a re4erenced o7ject thro/gh the Ve4 o7ject. 12. U+dating o4 col/mns containing BHOB, CHOB, VVF and VE( t:+es A dded o4 the /+dateBlo7, /+dateClo7, /+daterra:, and /+dateVe4 methods to the Ves/ltet inter4ace. 8 &6BC 6rivers o o o o
&6BCAO6BC Bridge 6river ative PI A Partl: &ava 6river et;or) +rotocol A ll &ava 6river ative Protocol A P/re &ava 6river
!ier 6river mechanism
6escri+tion &6BC access via most O6BC drivers, some O6BC 7inar: code and client code m/st 7e loaded on each client machine. !;o &6BCAO6BC !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. !his driver converts &6BC calls to data7ase s+eci4ic native !;o ative PI A Partl: &ava driver calls. Client re@/ires data7ase s+eci4ic li7raries. !hree et;or) +rotocol A ll &ava !his driver converts &6BC calls into 6BM inde+endent
1
6river
!;o !;o
ative +rotocol A ll ll A &ava driver
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. !he: are +/re java driver, the: comm/nicate directl: ;ith the vendor data7ase.
8 &6BC connection im+ort [email protected] +/7lic class &6BCam+le Q +/7lic static void void main9java.lang.tringRS args8 args8 Q tr: Q Class.4orame9s/n.jd7c.od7c.&d7cOd7c6river8 catch 9Classot(o/ndE*ce+tion e8 Q :stem.o/t.+rintln9Una7le to load 6river Class8 ret/rn tr: Q Connection con T 6riverManager.getConnection9jd7cod7ccom+an:d7,, 6riverManager.getConnection9jd7cod7ccom+an:d7,, 8 tatement stmt T con.createtatement98 Ves/ltet rs T stmt.e*ec/te/er:9EHEC! (IV!]ME (VOM EMPHOFEE8 ;hile9rs.ne*t988 Q :stem.o/t.+rintln9rs.gettring9(IV!]ME88 rs.close98 stmt.close98 con.close98 catch 9HE*ce+tion se8 Q :stem.o/t.+rintln9H E*ce+tion X se.getMessage988 8 $th t:+e driver class.4orame9oracle.jd7cdriver.oracledriver8 connection con T driverManager.getConnection9&6BCoraclethinfhostname+ortnooracleservice,/id, driverManager.getConnection9&6BCoraclethinfhostname+ortnooracleservice,/id, +;d8 8 te+s to connect to &6BC 8 1. (irst thing is /sing jd7c :o/ have hav e 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. co n.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 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 !ransactional ave+oints tatement stmt stmt T conn.createtatement conn.createtatement 98 Int ro;co/nt T stmt.e*ec/teU+date stmt.e*ec/teU+date 9insert into eta7le 9event8 val/es 9L!MML88 Int ro;co/nt T stmt.e*ec/teU+date 9insert into costs 9cost8 val/es 9$5.#88 ave+oint sv1 T conn.setavePoint 9sv+oint18 ?? create save +oint 4or inserts Int ro;co/nt T stmt.e*ec/teU+date 9delete 4rom em+lo:ees8 Conn.roll7ac) 9sv18 ?? discard discard the delete statement 7/t )ee+ the inserts Conn.commit ?? inserts are no; +ermanent +ermanent Q) @pdatin- B;OB & C;OB ata $ypes rs'next()-
Blo7 data T rs.getClo7 rs.getClo7 918 Vs.close98 ?? no; letLs insert insert this histor: into another ta7le stmt.setClo7 91, data8 ?? data is the Clo7 o7ject ;e retrieved 4rom the histor: ta7le int InsertCo/nt T stmt.e*ec/teU+date9insert into into EscalatedIncidents 9IncidentI6, Caseistor:, Caseistor:, O;ner8 X Dal/es al/es 9%11'$, , LoodsonL8 8 Q *etreivin- Storin- @pdatin- %rray of Objects
rra: a T rs.getrra:918 Pstmt.setrra:92, mem7er]arra:8 Vs./+daterra:9last]n/m,n/m8
Q) 2ow to e:ec"te no of ="eries at one -o?
8 B: /sing a 7atchU+dateLs 9i.e. thro; addBatch98 ad dBatch98 and e*ec/teBatch988 in java.s@l.tatement inter4ace or 7: /sing +roced/res. 8 Batch U+dates Calla7letatement stmt T con.+re+areCall9Qcall em+lo:eeIn4o 988 stmt.addBatch9IEV! stmt.addBatch9IEV ! I!O em+lo:ees DHUE 91###, 91### , L&oe &onesL88 stmt.addBatch9IEV! stmt.addBatch9IEV ! I!O de+artments DHUE 92'#, LhoeL88 ?? s/7mit a 7atch o4 /+date commands 4or e*ec/tion intRS /+dateCo/nts T stmt.e*ec/teBatch98 8 M/lti+le Ves/ltset 8 !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+rocCall8 7oolean retval T cstmt.e*ec/te98 i4 9retval TT 4alse8 Q else Q Ves/ltet rs1 T cstmt.getVes/ltet98
1 retval T cstmt.getMoreVes/lts9t cstmt.getMoreVes/lts9tatement._EEP]CUVVE!]VEUH! atement._EEP]CUVVE!]VEUH!8 8 i4 9retval TT tr/e8 Q Ves/ltet rs2 T cstmt.getVes/ltet98 rs2.ne*t98 rs1.ne*t98 CHOE]HH]VEUH! CHOE]HH]VEUH! ll +revio/sl: o+ened Ves/ltet o7jects sho/ld 7e closed ;hen calling getMoreVes/lts98. CHOE]CUVVE CHOE]CUVVE!]VE !]VEUH UH! ! !he c/rrent Ves/lte Ves/ltett o7ject sho/ld 7e closed ;hen calling calling getMoreVes/lts98. _EEP]CUVVE _EEP]CUVVE!]VEU !]VEUH! H!
!he c/rrent c/rrent Ves/lt Ves/ltet et o7ject o7ject sho/ld sho/ld not 7e closed closed ;hen calling calling getMoreVes/lts98.
8 6i44 e*ec/te98 ,e*ec/teU+date98 and e*ec/te/er:98 5) execute() returns returns a boolean !alue, which may return return multiple results. results. executePpdate() is used for nonfetchin" 8ueries, 8ueries, which returns returns int !alue and tell tell how many rows will be affected.
e*ec/te/er:98 is /sed 4or 4etching @/eries, ;hich ret/rns ret/rns single Ves/let o7ject and never ret/rn /ll /ll val/e. 8 o; to move the c/rsor in scrolla7le res/ltset !:+e !: +e o4 a Ves/ltet o7jectA !FPE](OVWV6]OHF, !FPE]CVOHH]IEI!IDE, !FPE]CVOHH]EI!IDE, COCUV]VE6]OHF and COCUV]UP6!BHE.
tatement stmt T con.createtatement9Ves/ltet.!FPE]CVOHH]EI!IDE, Ves/ltet.COCUV]VE6]OHF8 Ves/ltet rs T stmt.e*ec/te/er:9EHEC! COHUM]1, COHUM]2 (VOM !BHE]ME8 !BHE]ME8 rs.a4terHast98 ;hile 9srs.+revio/s988 Q tring name T rs.gettring9COHUM]18 4loat salar: T rs.get(loat9COHUM]28 rs.a7sol/te9$8 ?? c/rsor is on the 4o/rth ro; int ro;/m T rs.getVo;98 ?? ro;/m sho/ld 7e $ rs.relative9A38 int ro;/m T rs.getVo;98 ?? ro;/m sho/ld 7e 1 rs.relative928 int ro;/m T rs.getVo;98 ?? ro;/m sho/ld 7e 3 ??...
8 o; to U+date 6elete 6elete a res/ltset +rogrammaticall: 9pdate; * !tatement stmt I con.create!tatement"Aesult! con.create!tatement"Aesult!et.5@1L!CA%66L!1 et.5@1L!CA%66L!1$!V1, $!V1, Aesult!et.C%$C9AL9@7((861#Aesult!et uprs I stmt.execute:uery"+!161C stmt.execute:uery"+!161C C%69M$L0, C%69M$L0, C%69M$L2 'A%M (861L$(M1+ (861L$(M1+## uprs.last"#uprs.update'loat"+C%69M$L2+, uprs.update'loat"+C%69M$L2+, 2.#-BBupdate 2.#-BBupdate last last rows data uprs.updateAow"#-BBdon uprs.updateAow"#-BBdontt miss this this method, otherwise, the the data will will be lost. lost.
1 7elete; * uprs.absolute"#uprs.deleteAow"#- BB will delete row .
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 JBC if OBC is available?
8 O6BC is +/rel: ;ritten in c so ;e cannot directl: connect ;ith java. &6BC is a lo; level +/re java PI /sed to e*ec/te H statements. 9i8 O6BC is not a++ro+riate 4or direct /se 4rom java 7eca/se it /ses c inter4aces. Calls 4rom java to native c code has n/m7er o4 dra;7ac)s in the sec/rit:, im+lementation and ro7/stness. Q) Can we establish the connection with OBC itself?
8 Fes, /sing java native classes ;e have to ;rite a +rogram. Q) What is necessity of JBC in JBCOBC brid-e?
8 !he +/r+ose o4 &6BC is to lin) java PI to the O6BC, O6BC ret/rn high level c PI so the &6BC converts c level PI to java PI. 8 6oes the &6BCAO6BC Bridge s/++ort m/lti+le conc/rrent o+en statements +er conn ection 8 o. Fo/ can o+en onl: one tatement o7ject +er connection ;hen :o/ are /sing the &6BCAO6BC Bridge. Q) (s the JBCOBC Brid-e "ltithreaded?
8 o. !he &6BCAO6BC Bridge does not s/++ort conc/rrent access 4rom di44erent threads. !he &6BCA O6BC Bridge /ses s:nchroni
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+aretatement9EHEC! Z (VOM EMP WEVE de+tnoT8 6ataIn+/ttream dis T ne; 6ataIn+/ttream9:stem.in8 Int dno T Integer.ParseInt9dis.readHine988 +st.setInt91, dno8 Ves/ltet rs T +st.e*ec/te/er:98 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+areCall9QCHH +roced/reAname98 8 6ataIn+/ttream dis T ne; 6ataIn+/ttream9:stem.in8 Int en/m T Integer.ParseInt9dis.readHine988 cst.setInt91, en/m8 cst.registerO/tParameter92, t:+es.DVCV8 res/ltset rs T cst.e*ec/te98 /sed to send in4ormation to the +roced/re. In O/t /sed to retrieve in4ormation 4rom data 7ase. InO/t 7oth.
Q) (n which interface the ethods coit#) & rollbac9#) savepoint#) defined ?
8 [email protected] inter4ace Q) *etrievin- very lar-e val"es fro database?
8 getCIIteram98 read val/es ;hich are character in nat/re. etBinar: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:9EHEC! Z (VOM X ta7le8 Ves/ltetMeta6ata rsmd T rs.getMeta6ata98 Methods getCol/mnCo/nt98, getCol/mname98, getCol/mnHa7el98, getCol/mn!:+e98, get!a7leame98, 8 6ata7ase Meta6ata Fo/ need some in4ormation a7o/t the data 7ase dictionar: ;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, , 8 6ata7aseMeta6ata d7md T con.getMeta6ata98 Ves/ltet rsT d7md.get***98 Methods getCol/mns98, get!a7le!:+es98, get!a7les98, get6riverame98, 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. ote that closing a statement also closes a res/lt set that it might have +rod/ced. Connection.getWarnings98 tatement.getWarnings98, Ves/ltet.getWarnings98, eriali
1 HWarning ;arning T stmt.getWarnings98 i4 9;arning YT n/ll8 Q ;hile 9;arning YT n/ll8 Q :stem.o/t.+rintln9Message X ;arning.getMessage988 :stem.o/t.+rintln9Htate X ;arning.getHtate988 :stem.o/t.+rint9Dendor error code 8 :stem.o/t.+rintln9;arning.getErrorCode988 ;arning T ;arning.gete*tWarning98 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 I I!EEV , 7al I OU! (HO!8 I BEI select 7alance into 7al 4rom acco/nts ;here acco/nt]id T id Bal T 7al X 7al Z #.#3 U+date acco/nts set 7alance T 7al ;here acco/nt]id T id E6 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 tablename !alues(+empno@ +name)
end 8 tored Images into a ta7le P/7lic class img Q P/7lic static void main9tring argsRS8Q Class.4orame98 Connection con T 6riverManager.getConnection98 Pre+arestatement +st T con.+re+aretatement9insert into image val/e988 (ileIn+/ttream 4is T ne; (ileIn+/ttream9a.gi48 Pst.setBinar:tream91, 4is, 4is.availa7le8 Int I T +st.e*ec/teU+adate98 Vetrieve Image tatement st T con.Createtatement98
1 Ves/ltet rs T st.e*ec/te/er:9select Z 4rom img8 Vs.ne*t98 In+/ttream is T rs.getBinar:tream918 (ileO/tP/ttream 4os T ne; (ileO/tP/ttream9g2.gi48 Int ch While99chTis.read9188YTYA18 Q 4os.;rite9ch8
1 atabase Q"estions 8 6MH insert, /+date, delete 66H create, alter, dro+, tr/ncate, rename. 6H select 6CH grant, revo)e. !CH commit, roll7ac), save+oint. Q) Aorali5ation
ormali
8 Voll7ac) is +ossi7le a4ter 6EHE!E 7/t !VUC!E remove the ta7le +ermanentl: and canKt roll7ac). !r/ncate ;ill remove the data +ermanentl: ;e cannot roll7ac) the deleted data. 6ro++ing 9!a7le str/ct/re X 6ata are deleted8, Invalidates the de+endent o7jects, 6ro+s the inde*es !r/ncating 96ata alone deleted8, Per4orms an a/tomatic commit, (aster than delete 6elete 96ata alone deleted8, 6oesnKt +er4orm a/tomatic commit Q) iff 'archar and 'archar7?
8 !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?
8 Fo/ /se the HO datat:+e to store varia7leAlength character strings. !he HO datat:+e is li)e the DVCV2 datat:+e, e*ce+t that the ma*im/m length o4 a HO val/e is 32%'# 7:tes.
1 Fo/ /se the HO HO VW VW datat:+e to store 7inar: data 9or8 7:te strings. HO VW VW data is li)e HO data, e*ce+t that HO VW data is not inter+reted 7: PH?H. !he ma*im/m length o4 a HO VW val/e is 32%'# 7:tes. 8 6i44 (/nction 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 delete d/+licate ro;s in a ta7le 8 MPI6 EMPME EMP 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 > 1 COU! 9EMP8 EMP AAAAAAAAAAAAA AAAAAAAAAAA 2 555A55A5555 2 555A5-A5555 H> delete 4rom em+lo:ee ;here 9em+id, em+ssn8 not in 9select min 9em+id8, 9em+id8, em+ssn em+ssn 4rom 4rom em+lo:ee em+lo:ee gro/+ 7: em+ssn8 em+ssn8 8 elect the nth highest ran) 4rom the ta7le 8 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+ame, em+Id, address 78 alar: ta7le ;here 4ields Em+Id, Em+Id, month, mo/nt these 2 ta7les he ;ants Em+Id, em+ame and salar: 4or month ovem7er 8 elect em+.em+Id, em+ame, e m+ame, mo/nt 4rom em+, salar: ;here em+.em+IdTsalar:.em+Id em+.em+IdTsalar:.em+Id and monthTovem7er 8 Oracle?PHH :non:ms 8 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* A Create Ror re+laceS re+laceS R+/7licS s:non:m Rschema.S Rschema.S s:non:m]name 4or Rschema.S o7ject]name 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, 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;ing !a7le Pac)age
1 Die;
materiali
se@/ence
java class schema o7ject
stored stored +roced +roced/re /re /serA /serAde4 de4ine ined d o7ject o7ject (/nction
:non:m
e*am+le Create +/7lic s:non:m s/++liers 4or a++. s/++liers E*am+le demonstrates ho; to create a s:non:m called s/++liers. o;, /sers /sers o4 other schemas can re4erence the ta7le called s/++liers ;itho/t ;itho/t having to +re4i* the ta7le name ;ith the schema named named a++. (or e*am+le elect Z 4rom s/++liers 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;s Create or re+lace +/7lic s:non:m s/++liers 4or a++. s/++liers 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 R4orceS +/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 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+le 6ro+ +/7lic s:non:m s/++liers !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:m 8 n 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 joins Inner join o/ter join 8 B: /sing joins, :o/ can retrieve data 4rom t;o or more ta7les 7ased on logical relationshi+s 7et;een the ta7les Inner &oin A ret/rns all ro;s 4rom 7oth ta7les ;here there is a match. O/ter &oin A o/ter join incl/des ro;s 4rom ta7les ;hen there a re no matching val/es in the ta7les. \ HE(! &OI or HE(! OU!EV &OI !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. \ VI! &OI or VI! OU!EV &OI. right o/ter join is the reverse o4 a le4t o/ter join. ll ro;s 4rom the right ta7le are ret/rned. /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 &OI or (UHH OU!EV &OI. 4/ll o/ter join ret/rns all ro;s in 7oth the le4t and right ta7les. n: 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?
8 join selects col/mns 4rom 2 or more ta7les. /nion selects ro;s. ;hen /sing the UIO command all selected col/mns need to 7e o4 the same data t:+e. !he UIO command eliminate d/+licate val/es. Q! @nion & @nion %ll?
8 !he UIO HH command is e@/al to the UIO command, e*ce+t that UIO HH selects selects all val/es. It cannot eliminate d/+licate val/es. > EHEC! E]ame (VOM Em+lo:ees]or;a: UIO HH EHEC! E]ame (VOM Em+lo:ees]U 8 Is the 4oreign )e: is /ni@/e in the +rimar: ta7le 8 ot necessar: 8 !a7le !a7le mentioned 7elo; named em+lo:ee I6 ME MI6 1 C EO /ll 2 DP CEO 3 6irector DP s)ed to ;rite a @/er: to o7tain the 4ollo;ing o/t+/t CEO /ll DP CEO 6irector DP 8 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
1 4rom]cla/se T select]ta7le1, select]ta7le2, ... 4rom]cla/se T select]ta7le1 HE(! ROU!EVS &OI select]ta7le2 O e*+r ... 4rom]cla/se T select]ta7le1 VI! ROU!EVS &OI select]ta7le2 O e*+r ... 4rom]cla/se T select]ta7le1 RIEVS &OI select]ta7le2 ... select]ta7le T ta7le]name R S R ta7le]alias S select]ta7le T 9 s/7]select]statement 8 R S R ta7le]alias S order]col/mn]e*+r T e*+ression R C b 6EC S 8 6I!IC! cla/se 5) The #ITI6T clause allows you to remo!e duplicates from the result set.
> EHEC! 6I!IC! cit: (VOM s/++lier 8 COU! 4/nction 8 !he COU! 4/nction ret/rns the n/m7er o4 ro;s in a @/er: > EHEC! COU! 9Z8 as o o4 em+s (VOM em+lo:ees WEVE salar: > 25### Q) iff 2%'(A1 C;%@S & W2* C;%@S?
8 aving Cla/se is 7asicall: /sed onl: ;ith the VOUP BF 4/nction in a @/er:. WEVE Cla/se is a++lied to each ro; 7e4ore the: are +art o4 the VOUP BF 4/nction in a @/er:. 8 6i44 VOUP BF OV6EV BF 8 ro/+ 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! col]nam1, UM9col]nam28 (VOM ta7]name VOUP BF col]nam1 > EHEC! col]nam (VOM ta7]nam RWEVE conditionS OV6EV BF col]nam RC, 6ECS 8 What )e:;ord does an H EHEC! statement /se 4or a string search 8 !he HI_E )e:;ord allo;s 4or string searches. !he sign is /sed as a ;ildcard. 8 What is a UHH val/e What are the +ros and cons o4 /sing UHH 8 UHH 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 CVE!E UIUE I6E[ inde*]name O ta7le]name 9col/mn]name8 When the UIUE )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 name >CVE!E I6E[ PersonInde* O Person 9Hastame 6EC8 If you want to index more than one column you can list the column names within the parentheses.
>CVE!E I6E[ PersonInde* O Person 9Hastame, (irstame8
1 8 6i44 s/7@/eries Correlated s/7@/eries 8s/7@/eries are sel4Acontained. one 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 I, F, HH, E[I! 8 /7 @/er: can ret/rn a s/7set o4
!he com+arison o+erator is the e@/alit: and the logical o+eration 7et;een val/es is OV. llo;s to chec) i4 at least a val/e o4 the list satis4ies condition. llo;s to chec) i4 condition is reali
Q) What are soe s=l %--re-ates and other B"iltin f"nctions?
8 D, UM, MI, M[, COU! and 6I!IC!.
$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 61 NabN ) 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.
"7ata alone deleted#, @erforms an automatic commit, 'aster than
%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
1
"! >aving clause is used only with group functions whereas