Sie sind auf Seite 1von 202

Chapter 1

Introduction to java
Java is language for the development of Enterprise applications, and it was
developed at Sun Microsystems as a platform-independent language primarily
aimed at controlling appliances such as video game consoles VCRs, bread toasters .
Sun! , later modi"ed the language to ta#e advantage of $orld $ide $eb. %ava is
an ob&ect-oriented language, and very similar to C''.
%ava (eatures
1. PlatformIndependent
)he concept of $rite-once-run-anywhere is one of the important #ey feature
of &ava language that ma#es &ava as the most powerful language.
2. Simple
*rograms are easy to write and debug because &ava does not use the pointers
e+plicitly. ,t is much harder to write the &ava programs that can crash the
system.
3. ObjectOriented
&ava is a fully -b&ect -riented language because, ob&ect is at the outer most
level of data structure in &ava. .o stand alone methods, constants, and
variables are there in &ava. Everything in &ava is ob&ect even the primitive
data types can also be converted into ob&ects.
4. Robust
%ava has the strong memory allocation and automatic garbage collection
mechanism. ,t provides the powerful e+ception handling and type chec#ing
mechanism as compare to other programming languages. Compiler chec#s
the program whether there any error and interpreter chec#s any run time
error and ma#es the system secure from crash. /ll of the above features
ma#es the &ava language robust.
5. Distributed
,nternet programmers can call functions on 0))* , ()* protocols and can get
access to the "les from any remote machine rather than writing codes on
their local system.
6. Portable
)he feature $rite-once-run-anywhere ma#es the &ava language portable
provided that the system must have interpreter for the %VM.
7. Secure
%ava does not use memory pointers e+plicitly. /ll the programs in &ava are run
under an area #nown as the sand bo+. Security manager determines the
accessibility options of a class li#e reading and writing a "le to the local dis#.
%ava uses the public #ey encryption system to allow the &ava applications to
transmit over the internet in the secure encrypted form. )he bytecode Veri"er
chec#s the classes after loading.
1
8. Performance
%ava uses native code usage, and lightweight process called threads. ,n the
beginning interpretation of bytecode resulted in slow performance but the
advanced versions of %VM uses &ust in time compilation techni2ue that
improves the performance.
9. Multithreaded
Multithreading programming is a very interesting concept in %ava.
10. Interpreted
-ne of the advantage of %ava as an interpreted language is its error
debugging 2uality. 3ue to this any error occurring in the program gets traced.
11. Architecture eutral
%ava was designed to support applications on networ#. )he %ava compiler
generates byte code
instructions, to be easily interpreted on any machine and to be easily
translated into native
machine code on the 4y.
!hat is Java "irtual Machine#
5anguages li#e C and *ascal converts the source code into machine code for one
speci"c type of machine and the machine language vary from system to system .
6ut %ava compiler produce code for a virtual machine . %VM converts the byte code
into machine code for the computer one wants to run.
)he %VM is a part of %RE that is re2uired by every operating system.
Each operating system and C*7 architecture re2uires a %RE. %RE consists of a set of
base classes i.e. %ava /*, as well as a %VM. %VM is &ava interpreter as it converts the
byte code into machine code for the computer one wants to run.
%RE consists of a number of classes based on %ava/*, and %VM, and without %RE, it is
impossible to run %ava.
$o% to %rite &irst Java pro'ram
public class (irst*rogram
8
public static void main9String arr:; <
8
System.out.println9= 0ello %ava $orld=<>
?
?
@
Save the "le with same name as the public class &ust adding the e+tension (java!
e.g. &irstPro'ram(java(
.ow compile asA
c)* javac &irstPro'ram(java
)his creates a class "le in bytecode form as (irst*rogam.class
$o% to e+ecute this code)
c)* java M,&irstPro'ram
-7)*7) AA 0ello %ava $orld
Di-erent .ditions of Java /echnolo',
a< Java S. - %ava SE or %ava Standard Edition provides tools and /*,Bs that you can
use to create des#top applications, applets, server applications. )hese programs
developed using %ava SE can be run on almost every popular operating system.
b< J.. - %ava Enterprise Edition helps in web application service, component model
and enterprise class service oriented architecture9S-/<.
c< JM. - %ava Micro Edition or %ME is an accumulation of %ava /*,s that are used for
the development of software for devices li#e mobile phones, *3/s, )V set-top
bo+es, game programming.
Demonstartion Pro'rams
E+ample 1 A 3emo of a Simple &ava program

public class (irst*rog
8
public static void main9String args:;<
8
System.out.println9 welcome to the &ava SE C!<>
?
?
E+ample @ A 3emo of if statement through a &ava program

public class 3emo,f
8
public static void main9String args:;<
8
int a D 1E, b D 1F, m>
if 9a G b< m D a> else m D b>
System.out.println9 ma+ number D 'm<>
H
?
?
E+ample H A 3emo of while.. loop through a &ava program

public class 3emo$hile
8
public static void main9String args:;<
8
int n D @FI, s DE, d>
while 9n JDE<
8
d D n K 1E> s D s 'd > n D n L 1E>
?
System.out.println9 sum of digits D 's<>
?
?
E+ample M A 3emo of for.. loop

public class 3emo(or
8
public static void main9String args:;<
8
int n D HE, i>
for 9i D 1> i NDn> i''<
if 9 n K i DD E <
System.out.println9 ' i <>
?
?
M
Structure of Arra,s
/rray is the most widely used data structure in &ava. ,t can contain multiple
values of the same type. Moreover, arrays are always of "+ed length i.e. the
length of an array cannot be increased or decreased. )he Arra, class
implicitly e+tends java(lan'(Object so an array is an instance of -b&ect.
Suppose an array contains =n= integers. )he "rst element of this array will
be inde+ed with the =E= value and the last integer will be referenced by =n-1=
inde+ed value.
*resume an array that contains 1@ elements as shown in the "gure. Each
element is holding a distinct value. 0ere the "rst element is refrenced by
a:E; i.e. the "rst inde+ value.
)he "gure below shows the structure of an /rray more precisely.
Arra, Declaration
)o represent the variable as an /rray, we use :; notation. )hese two brac#ets
are used to hold the array of a variable.
int:; arrayOname> LLdeclares an array
of integers
String:; names>
int:;:; matri+> LLthis is an array of
arrays
,t is essential to assign memory to an array when we declare it. Memory is
assigned to set the siPe of the declared array. for e+ampleA
int:; arrayOname D new int:F;>
0ere is an e+ample that creates an array that has F elements.
public class /rray
8
public static void main9String:; args<
8
int:; a D new int:F;>
?
?
F
Arra, Initiali0ation
/fter declaring an array variable, memory is allocated to it. )he =new=
operator is used for the allocation of memory to the array ob&ect. )he correct
way to use the =new= operator is
String names:;>
names D new String:1E;>
0ere, the new operator is followed by the type of variable and the number of
elements to be allocated. ,n this e+ample :; operator has been used to place
the number of elements to be allocated.
5ets see a simple e+ample of an array,
public class Sum
8
public static void main9Stri
ng:; args<
8
int:; + D ne% int :1E1;>
for 9int i D E> iN+.length> i
'' <
+:i; D i>
int sum D E>
for9int i D E> iN+.length> i'
'<
sum 'D +:i;>
System.out.println9sum<>
?
?
)o #now the length of the /rray, we use "eld length, as shown.
E+ample F A 3emo of 1 3 array - 5inear search

public class 3emo5search
8
public static void main9String args:;<
8
int a:; D8 1E,@E,HE,1F,@F?, i, n>
int + D 1F, 4ag D E>
n D a.length>
for 9 i D E > i N n > i ''<
if 9 a: i ; DD +<
8
4ag D 1> brea#>
?
if 9 4ag JD E <
System.out.println9 item found at D ' 9 i'1<<>
?

C
.+ample 1 ) 3emo of 1 3 array - Sorting of n integers

public class 3emoSort
8
public static void main9 String args:; <
8
int a: ; D8 1E,EQ,HE,1F,@I,1I,1@?, i, &, n,temp>
n D a.length>
for 9 i D E > i N n-1 > i ''<
for 9&D i'1> & N n> &''<
if 9 a: i ; Ga: & ;<
8
temp D a: i ;> a: i ; D a: & ;> a: & ;D temp>
?
for 9 iDE> i N n> i''<
System.out.println9 ' a: i ;<>
?
?
.+ample 2 ) 3emo of user de"ned iterative functions

public class 3emo(unction
8
public static void main9String args:;<
8
int n D F, i, fm>
fm D fact 9m<>
System.out.println9result D ' fm<>
?
static int fact9 int n<
8
int fn D 1, i>
for 9i D @> i NDn> i''<
fn D fn R i>
return fn>
?
?

I
.+ample 3 ) 3emo of Recursive functions

public class 3emoRecfun
8
public static void main9String args:;<
8
int n D F, i, fm>
fm D fact 9m<>
System.out.println9result D ' fm<>
?
static int fact9 int n<
8

if 9 n N E< return 1>
else
return n R fact 9 n S 1<>
?
?
Q
Chapter 4
Object Oriented &eatures of
Java
OOP stands for Object Oriented Pro'rammin'. /here are four main pillars of
an Object Oriented Pro'rammin' 5an'ua'e )
Inheritance) ,nheritance provide the facility to derive one class by another
using simple synta+. Tou can say that it is a process of creating new class and
use the behavior of the e+isting class by e+tending them for reuse the e+isting
code and adding the additional features as you need.
.ncapsulation) Encapsulation is the ability to bundle the property and method
of the ob&ect and also operate them. ,t is the mechanism of combining the
information and providing the abstraction as well.
Pol,morphism) *olymorphism is the way that provide the diUerent functionality
by the functions having the same name based on the signatures of the
methods. )here are two type of polymorphism "rst is run-time polymorphism
and second is compile-time polymorphism.
D,namic bindin') ,t is the way that provide the ma+imum functionality to a
program for a speci"c type at runtime. )here are two type of binding "rst is
dynamic binding and second is static binding.
Class) / class provide a feature to de"nes the properties and behavior 9variables
and methods< as an /3) , that can be used by all its ob&ects. ,t is a blue print for the
creation of ob&ects.
Object) Class itself does nothing but the real functionality is achieved through
their ob&ects. -b&ect is an instance of the class. ,t ta#es the properties 9members<
and uses the behavior 9methods< de"ned in the class.
)he .ncapsulation6 Inheritance and Pol,morphism are main pillars of OOPs(
)hese have been described below A
.ncapsulation)
Encapsulation is the process of binding together the methods and data variables as
a single entity. ,t #eeps both the data and functionality code safe from the outside
world. ,t hides the data within the class and ma#es it available only through the
methods. %ava provides diUerent accessibility scopes 9public, protected, private
,default< to hide the data from outside.
0ere we provide a e+ample in which we create a class 7Chec87 which has a
variable 7amount7 to store the current amount. .ow to manipulate this variable
V
we create a methods and to set the value of amount we create setAmount9:
method and to get the value of amount we create 'etAmount9: method
$ere is the code for 7Mainclass7 class )
class Chec#
8
private int amountDE>
public int get/mount9<
8
return amount>
?
public void set/mount9int amt<
8
amountDamt>
?
?
public class Mainclass8
public static void main9String:; args<
8
int amtDE>
Chec# ob& D ne% Chec#9<>
ob&.set/mount9@EE<>
amt D ob&.get/mount9<>
System.out.println9=Tour current amount is A='amt<>
?
?
0ere the data variable =amount= and methods setAmount9: and 'etAmount9:
are enclosed together with in a single entity called the =Chec#= class. )hese two
methods are used to manipulate this variable i.e. set and get the current value of
amount.
.+ample ; ) 3emo of ob&ect oriented programming
class 3emoCalc
8
int a , b>
public 3emoCalc9<
8
a D F> b D 1E>
1E
?
public int sum 9<
8
int +>
+ D a ' b>
return +>
?
?
public class )est3emoCalc
8
public static void main9String args:;<
8
3emoCalc m D new 3emoCalc9<>
int P>
P D m.sum9<>
System.out.println9result D ' P<>
?
?
Constructor
Constructor is the method whoose name is same as that of the class. 6ut there are
many diUerence between the method 9function< and the Constructor. ,t has no
return type.
,t is used for initialiPation purpose. / class can have any number of constructors. ,t
is then called constructor overloading.

.+ample 1< ) 3emo of Constructor -verloading

class 3emo-ver
8
int a , b>
LR default constructor RL
public 3emo-ver9<
8
a D F> b D 1E>
?
LR constructor with parameter RL
public 3emo-ver9 int #1, in# #@<
8
a D #1> b D #@>
?
11
public int sum 9<
8
int +>
+ D a ' b>
return +>
?
?

public class )est3emo-ver
8
public static void main9String args:;<
8
3emo-ver m1 D new 3emo-ver9<>
3emo-ver m@ D new 3emo-ver9@E,@F<>
int P1, P@>
P1 D m1.sum9<> P@ D m@.sum9<>
System.out.println9result1 D ' P1 ' result@ 'P@<>
?
?
this #ey word A ,t is used to resolve the ambiguity between a formal
parameter and a datamember.
.+ample 11 ) 3emo of #eyword this

class 3emothis
8
int a , b>
LR constructor with parameter RL
public 3emothis9 int a, in# b<
8
this.a D a> this.b D b>
?
public int sum 9<
8
int +>
+ D a ' b>
return +>
?
?
public class )est3emothis
8
public static void main9String args:;<
8
1@
3emothis m1 D new 3emothis9@E,@F<>
int P1>
P1 D m1.sum9<>
System.out.println9result D ' P1 <>
?
?
Instance variables) )hey are the datamembers in a class and get a copy
of memory for each ob&ect instance. $ith one ob&ect instance if they are
modi"ed , the other instances are not eUected.

.+ample 14 ) 3emo of instance variable

class 3emo,nvar
8
int a,b>
public 3emo,nvar9 <
8
aDF> bDI>
?

public void update 9<
8
a''>
b''>
?
public void disp9<
8
System.out.println 9 aD 'a ' bD!'b<>
?

?
public class )est3emo,nvar
8
public static void main9String args:;<
8
3emo,nvar m1 D new 3emo,nvar9<>
3emo,nvar m@ D new 3emo,nvar 9<>
m1.update9<>
m1.disp9<>
m@.disp9<>
?
?
1H
Static variablesA )hey are the data members in a class de"ned with a
#eyword static. Such members are also called class members , . and get a
single copy of memory per %VM, for all ob&ect instances. $ith one ob&ect
instance if they are modi"ed , the other instances are also eUected as they
are shared .

.+ample 1= ) 3emo of class variable

class 3emoClvar
8
static int a >
int b>

public 3emoClvar9 <
8
a D F> b D I>
?

public void update9 <
8
a ''> b''>
?
public void disp9 <
8
System.out.println 9 aD 'a ' bD!'b<>
?
?

public class )est3emoClvar
8
public static void main9String args:;<
8
3emoClvar m1 D new 3emoClvar9<>
3emoClvar m@ D new 3emoClvar 9<>
m1.update9 <>
m1.disp9 <>
m@.disp9 <>
?
?
Class methods A Such methods belong the class but not to the ob&ects.
)hey are called with class name.
.+ample 1> ) 3emo of class method

1M
class 3emoClmd
8

public static wishcodeE1 9<
8
System.out.println9 0appy .ew Tear!<>
?
public static wishcodeE@ 9<
8
System.out.println90appy returns=<>
?
?

public class )est3emoClmd
8
public static void main9String args:;<
8
3emoClmd.wishcodeE19 <>
3emoClmd.wishcodeE@9 <>
?
?
1F
.+ample 1? ) 3emo of class method

class 3emoMathop
8
static 4oat multiply94oat +, 4oat y<
8
return +Ry>
?
static 4oat divide94oat +, 4oat y<
8
return +Ly>
?
?
public class )est3emoMathop
8
public static void main9String args:;<
8
4oat a D 3emoMathop.multiply9@.E,F,E<>
4oat + D 3emoMathop.divide9a,@.E<>
System.out.println9=+D= ' +<>

?
?
.+ample 11 ) 3emo of method invocation by other methods of the same
class
9 .ested methods<

class 3emo.est
8
int a,b>
public 3emo.est9 <
8
aD1F> bDI>
?

public int large9<
8
int m>
mD 9 aGb<W a A b>
return m>
?
public void disp9<
1C
8
int + D large9<> LR method call RL
System.out.println 9 ma+D ' +<>
?
?
public class )est3emo.est
8
public static void main9String args:;<
8
3emo.est m1 D new 3emo.est9<>
m1.disp9<>
?
?
S,stem(out(println9: ))
)he =&ava.lang= pac#age is built into every program. / pac#age is a
libaries of classes.
)he &ava.lang pac#age has a System Class, which includes a static nested
class called =out= and this out class, has a method by name println9<.
!h, method main has 7 public 6 static7 access speci@ers ))
,t is called from outside.
)he main9< is a class method
,t is invo#ed by the interpretor with its class name.
Chapter =
Strin' $andlin'
1I
Strings are handled as ob&ects in &ava. %ava support two classes to
handle strings
1 String @ String6uUer
String ob&ects hold te+t which canBt be changed. / String class ob&ect is
immutable because the time ta#en by %VM to reallocate memory and add
data is more than creating a new ob&ect. / String6uUer on the
otherhand, is mutable. ,t can change and grow in siPe )he default
constructor allocates 1C char siPe to a String6uUer

Strin' Methods

5et s1, s@ are the source and destination strings. )hen some methods
are

s@ D s1.to5owerCase9<

s@ D s1.replace9B+B, ByB<
s@ D s1.trim9<
s1.e2uals9s@< , s1.isEmpty9<

s1.e2uals,gnoreCase9s@<
S1.length

s1.char/t9n<
s1.subString9n< , s1.subString9m,n<
s1.inde+-f9=+=<
s1.toString9<
s1.compare)o9s@<

s@ D s1.concat9sH<

s@ D s1.replace9B+B,ByB< 9,t create a new string ob&ect s@<
1Q
Strin'Au-er methods
s1.char/t9n<

s1.append9s@<, s1.replace9m,n,s@<
s1.setChar/t9n,B+B<
s1.insert9n,s@<
s1.set5ength9n< , s1.length9<, s1.reverse9<
)he following programs demonstrate String handling in &ava.
.+ample 12 ) 3emo of methods in String class
public class )estStread
8
public static void main9 String args:;<
8
String s1 D =hello=>
String s@ D new String9<> s@ D =from=
String sH D new string9=%ava=<>
String sM D s1 ' s@ ' sH>
String sF D sM.concat9= world =<>
String sC D ==>
System.out.println9sF<>
System.out.println9sF.to7pperCase9<<>
system.out.println9=is emptyW = ' sC.isEmpty9<<>
?
?

.+ample 13 ) 3emo of methods in String class
public class )estSsort
8
public static void main9 String args:;<
8
String s:; D 8 =arun=, =rao= , =sridhar=, =&ones=?>
int i,&,n>
String temp D null>
n D s.length>
for 9 iDE> iN n-1> i''<
for 9&Di'1> &Nn > &''<
1V
if 9 s:i;.compare)o9s:&;< G E <
8
temp D s:i;> s:i; D s:&;>
s:&; D temp>
?
for 9 i DE> iN n> i''<
System.out.println9s:i;<>
?
?

.+ample 1; ) 3emo of methods in String buUer class
public class )est6uU
8
public static void main9 String args:;<
8
String6uUer s1 D new String6uUer9=hello=<>
String6uUer s@ D new String6uUer9<>
s@.insert9E,= from=<>
s@.append9= &ava=<> s1.append9s@<>
System.out.println9s1<>
s1.replace9C,1E,=to=<>
System.out.println9s1<>

s1.delete9C,Q<>
System.out.println9s1<>
System.out.println9=alloted len= ' s1.capacity9<<>
s1.set5ength91EE<>
system.out.println9=new capacity=' s1.length9<<>
?
?
.+ample 4< ) 3emo of methods in String6uUers
public class )estSbuU
8
public static void main9 String args:;<
8
String6uUer sbD new String6uUer9=%ava is tough=<>
System.out.println9sb<>
int n D sb.length9<> int p>

for 9 iDE> iN n> i''<
8
@E
p D i ' 1>
System.out.print9=char at pos= 'p'=D= ' sb.char/t9i<<>
?

String a D new String9sb.toString9<<>
p D a.inde+-f9=tough=<>
sb.insert9p,=.ot =<>
System.out.println9sb<>

sb.append9= to learn=<>
System.out.println9sb<>
?
?
Strin'Auilder class ))
String6uUer , can be used by multiple threads. ,t is recommended when
synchroniPation is re2uired. ,ts methods are synchroniPed. / String6uilder
has no synchroniPed methods. So it wor#s faster and , $hen we are doing
number of string operations in a single thread we gain tremendous
performance than String6uUer.
E+ample @1 AA 3emo of String6uilder
public class )est/pp
8
public static void main9String args:;<
8
String s D concate9=&ava=,= =,=is=,= =,=simple=<>
System.out.println9s<>
?
static String concate9String... #<
8
String6uilder sd D new String6uilder9 <>
int n D #.length> int i>
for 9 iD E> iN n > i''<
sd.append9#:i;<>
return sd.toString9 <>
?
?
Strin'/o8eni0er(
.+ample 44)
@1
import &ava.util.String)o#eniPer>
class S)3emo 8
static String in D=titleD%avaA )he Complete Reference>= '
=authorD.aughton and Schildt>= '
=publisherD-sborneLMcXraw-0ill>= '
=copyrightD1VVV=>
public static void main9String args:;< 8
String)o#eniPer st D new String)o#eniPer9in, =D>=<>
while9st.hasMore)o#ens9<< 8
String #ey D st.ne+t)o#en9<>
String val D st.ne+t)o#en9<>
System.out.println9#ey ' =YYt= ' val<>
?
?
?
!rappers
%ava provide wrapper classes in order to use primitive data types as
ob&ects, Every primitive type has a class de"ned
primitive wrapper
int ,nteger
4oat (loat
char Character
)here are methods de"ned to return the values of an ob&ect

.+ample 4= ) 3emo of wrapper class
public class )est$rp1
8
@@
public static void main9 String args:;<
8
,nteger i D new ,nteger9@F<>
Character c D new Character9B0B<>
int % D i.intValue9<>
char # D c.charValue9<>
System.out.println9& ' = = 'i<>
System.out.println9#' = = ' c<>
?
?
5et a,b are primitive types, m,n are ob&ects , and S is string ob&ect
Conversion of primitive types to primitive ob&ects
,nteger m D new ,nteger9a<>
(loat n D new (loat9b<>
Conversion of primitive ob&ects to primitive types
int a D m.intValue9<>
4oat b D n.4oatValue9<>

Conversion of primitive types to string ob&ects
String s D ,nteger.toString9a<>
String s D (loat.toString9b<>
Conversion of string ob&ects to primitive types
int a D ,nteger.parse,nt9s<>
4oat b D (loat.parse(loat9s<>
.+ample 4> ) 3emo of wrapper class
public class /dder
8
public static void main9 String args:;<
8
int a, b, m>
aD ,nteger.parse,nt9args:E;<>
bD ,nteger.parse,nt9args:1;<>
m D a'b>
System.out.println9=result = ' m<>
?
?
Autobo+in'6 unbo+in' of primitive t,pes
.+ample 4? ) 3emo of autobo+ing, unbo+ing
public class )est6o+7nbo+
@H
8
public static void main9 String args:;<
8
,nteger ib1,ib@,ibH>
ib1 D @F> LL autobo+ing - encapsulating a value
int i1 D ib1> LL unbo+ing - e+tracting the value
System.out.println9ib1 ' = = 'i1<>

ib@ D HF>
ib@ D ib@ ' 1> LL unbo+ and rebo+
System.out.println9=value= ' ib@< >

ibH D /bo+.getval9FF<> LL /utobo+
System.out.println9= value returned= ' ibH<>
?
?
class /bo+
8
static int getval9 ,nteger ib<
8
return ib> LL unbo+ the return vaule
?
?
for B each loop ))
for 9type varaible A collection<
statement>
.+ample 41 ) 3emo of for each
public class 3emo/pp
8
public static void main9 String args:;<
8
for 9 String sA args<
System.out.println9s<>
?
?
.+ample 42 ) 3emo of for-each
public class 3emo/pp
@M
8

enum Country 8 india, china, &apan, canada?>
public static void main9 String args:;<
8
for 9 Country cA Country.values9<<
System.out.println9=it ,s= ' c<>
?
?
variable number of ar'uemnts ))
@F
.+ample 43 ) 3emo of variable numer of parameters
public class 3emo/pp
8

static void mthvar9int... i<
8
int n D i.length>
System.out.println9=number of para=' n<>
System.out.println9=contents are=<>
for 9 int # A i<
System.out.println9=it ,s= ' #<>

?
public static void main9 String args:;<
8
mthvar9<>
mthvar9@F,HF<>
mthvar91E,@E,HE,ME<>

?
?
.+ample 4; ) 3emo of for-each
public class 3emo/pp
8
public static void main9 String args:;<
8
int a:; D 8 1E,@E,HE,ME,FE?>
int ma+ D E>
for 9 int #A a<
if 9 # G ma+< ma+ D #>

System.out.println9=ma+imum= ' ma+<>
?
?
Chapter >
@C
Inheritance C Pol,morphism in
java
,nheritance allows a class 9subclass< to ac2uire the properties and behavior of
another class 9superclass<. ,n &ava, a class can inherit only one class 9superclass< at
a time but a class can have any number of subclasses. ,t helps to reuse, customiPe
and enhance the e+isting code. So it helps to write a code accurately and reduce
the development time. %ava uses e+tends #eyword to e+tend a class.
$ere is the code of the e+ample )
class /
8
public void fun19int +<
8
System.out.println9=in / is A= ' +<>
?
?
class 6 e+tends /
8
public void fun@9int +,int y<
8
fun191:D LL prints =int in /=
System.out.println9=in 6 is A= ' + = and ='y<>
?
?
public class /estinherit
8
public static void main9String:; args<
8
6 ob&D ne% 69<>
ob&.fun@9@<>
?
?
,n the above e+ample, class 6 e+tends class / and so ac2uires properties and
behavior of class /. So we can call method of / in class 6.
)hus inheritance is aechanism used to create new class by e+tending
the de"nition of another class. )his process of e+tending one class to create
new class is called subclassing.
/,pes))
@I
Single inheritance Multiple ,nheritance
Multilevel ,nheritance 0irarchial ,nheritance
0ybrid ,nheritance

LR 3emo of inheritance RL
class 3emoCalc
8
int a,b>
public 3emoCalc9<
8
a D F> b D 1E>
?
public int sum 9<
8
int +>
+ D a ' b>
return +>
?
?

public class )est3emoCalc
8
public static void main9String args:;<
8
3emoCalc m D new 3emoCalc9<>
int P>
P D m.sum9<>
System.out.println9result D ' P<>
?
?
.+ample =< ) 3emo of inheritance
class Ch3emoCalc e+tends 3emoCalc
8
public int diU9<
8
int +>
+ D a-b>
return +>
?
?
public class )estCh3emoCalc
8
public static void main9String args:;<
8
@Q
Ch3emoCalc m D new Ch3emoCalc9<>
int P1,P@>
P1 D m.sum9<>
P@ D m.diU9<>
System.out.println9 sumD' P1 ' =diUD= 'P@ <>
?
?
Constructor under inheritance
$hen a child class ob&ect is instantiated the constructor of the base
class is called "rst , then followed by the derived class constructor.
.+ample =1 ) 3emo of constructor under inheritance
class /
8
/9 <
8
System.out.println9=,n constructor of /=<>
?
?
class 6 e+tends /
8
69 <
8
System.out.println9=,n constructor of 6=<>
?
?
public class )est/pp
8
public static void main9String args:;<
8
6 b1 D new 69<>
?
?
output AA ,n construtor of /
,n construtor of 6
.+ample =4 ) constructor with param under inheritance - 1
class /
8
/9 <
8
System.out.println9=,n constructor of /=<>
@V
?
?
class 6 e+tends /
8
69String s <
8
System.out.println9=,n string constructor of 6=<>
System.out.println9s<>
?
?
public class )estCon,nhe
8
public static void main9String args:;<
8
6 b1 D new 69=%ava is simple=<>
?
?
output AA ,n construtor of /
,n string construtor of 6
&ava is simple

HE
.+ample == ) constructor %ith param under inheritance B 4
class /
8
/9 <
8
System.out.println9=,n constructor of /=<>
?

/9String s <
8
System.out.println9=,n string constructor of /=<>
System.out.println9=,n /= ' s<>
?
?
class 6 e+tends /
8
69String s <
8
super9s<>
System.out.println9=,n string constructor of 6=<>
System.out.println9=,n 6= ' s<>
?
?
public class )est/pp
8
public static void main9String args:;<
8
6 b1 D new 69=%ava is simple=<>
?
?
output AA ,n string construtor of /
,n / &ava is simple
,n string construtor of 6
,n 6 &ava is simple
super9 : )) ,t can be used to call super class methodsLconstructor
Multilevel inheritance))

.+ample => ) Constructor under Multilevel inheritance
H1
class /
8
/9 <
8
System.out.println9=,n constructor of /=<>
?
?
class 6 e+tends /
8
69 <
8
System.out.println9=,n constructor of 6=<>
?
?
class C e+tends 6
8
C9 <
8
System.out.println9=,n constructor of C=<>
?
?
public class )est/pp
8
public static void main9String args:;<
8
C c1 D new C9<>
?
?
output AA ,n construtor of /
,n construtor of 6
,n contructor of C
Pol,morphism
*olymorphism allows one interface to be used for a set of actions i.e. one name may
refer to diUerent functionality. *olymorphism allows a ob&ect to accept diUerent
re2uests of a client 9it then properly interprets the re2uest li#e choosing appropriate
method< and responds according to the current state of the runtime system, all
without bothering the user.
)here are two types of polymorphism A
H@
1. CompileBtime pol,morphism
@. Runtime Pol,morphism
,n compiletime *olymorphism, method to be invo#ed is determined at the compile
time. Compile time polymorphism is supported through the method overloadin'
concept in &ava.
Method overloading means having multiple methods with same name but with
diUerent signature 9number, type and order of parameters<.
$ere is the code of the e+ample )
class /8
public void fun19int +<8
System.out.println9=)he value of class / is A = ' +<>
?
public void fun19int +,int y<8
System.out.println9=)he value of class 6 is A = ' + ' = and = ' y<>
?
?
public class polyone8
public static void main9String:; args<8
/ ob&Dnew /9<>
LL 0ere compiler decides that fun19int<
is to be called and =int= will be printed.
ob&.fun19@<>
LL 0ere compiler decides that fun19int,int<is to be called and =int and int=
will be printed.
ob&.fun19@,H<>
?
?
,n rumtime polymorphism, the method to be invo#ed is determined at the run time.
)he e+ample of run time polymorphism is method overridin'. $hen a subclass
contains a method with the same name and signature as in the super class then it is
called as method overriding.
class /8
public void fun19int +<8
System.out.println9=int in Class / is A =' +<>
?
?
class 6 e+tends /8
public void fun19int +<8
System.out.println9=int in Class 6 is A =' +<>
?
?
public class polytwo8
public static void main9String:; args<8
HH
/ ob&>

ob&D ne% /9<> LL line 1
ob&.fun19@<> LL line @ 9prints =int in Class / is A @=<

ob&Dne% 69<> LL line H
ob&.fun19F<> LL line M 9prints ==int in Class 6 is A F=<
?
?
Method Overridin' ))
,t is used when a subclass has to replace a method of its superclass.
$henever such a method is invo#ed, &ava loo#s for a method of that
signature, in the class de"nition of the current ob&ect. ,f such a method is
not found then it loo#s for a matching signature in the superclass.
E+ample HF AA 3emo of method overriding
class /nimal
8
public void breath9 <
8
System.out.println9= 6reathing...=<>
?
?
class (ish e+tends /nimal
8
public void breath9 <
8
System.out.println9=6ubbling...=<>
?
?
public class )estRide
8
public static void main9String args:;<
8
(ish f D new (ish9<>
f.breath9<>
?
?
output AA bubbling...

HM
super 8e,%ord
)he super is &ava #eyword. /s the name suggest super is used to access the
members of the super class. ,t is used for two purposes in &ava.
)he "rst use of #eyword super is to access the hidden data variables of the super
class hidden by the sub class.
e.g. Suppose class / is the super class that has two instance variables as int a and
4oat b. class 6 is the subclass that also contains its own data members named a
and b. then we can access the super class 9class /< variables a and b inside the
subclass class 6 &ust by calling the following command.
super(memberD
0ere member can either be an instance variable or a method. )his form of super
most useful to handle situations where the local members of a subclass hides the
members of a super class having the same name. )he following e+ample clarify all
the confusions.
class /8
int a>
Eoat b>
void Show9<8
System.out.println9=b in super classA =
' b<>
?
?
class 6 e+tends /
8
int a>
Eoat b>
69 int p, Eoat 2<
8
a D p>
super.b D 2>
?
void Show9<
8
super.Show9<>
System.out.println9=b in super classA =
' super.b<>
System.out.println9=a in sub classA =
' a<>
?
public static void main9String:; args<
8
6 subob& D ne% 691, F<>
HF
subob&.Show9<>
?
?
Fse of super to call super class constructor) )he second use of the #eyword
super in &ava is to call super class constructor in the subclass. )his functionality can
be achieved &ust by using the following command.
super9paramBlist:D
0ere parameter list is the list of the parameter re2uires by the constructor in the
super class. super must be the "rst statement e+ecuted inside a super class
constructor. ,f we want to call the default constructor then we pass the empty
parameter list.
.+ample =1 ) method overriding - how to access original method
class /nimal
8
public void breath9 <
8
System.out.println9= 6reathing...=<>
?
?
class (ish e+tends /nimal
8
public void breath9 <
8
System.out.println9=6ubbling...=<>
?
public void newbreath9 <
8
super.breath9<>
?
?
public class )estRide
8
public static void main9String args:;<
8
(ish f D new (ish9<>
f.newbreath9<>
f.breath9<>
?
HC
?
output AA breathing...
bubbling...
D,namic method dispatch 9 Run time pol,morphism:
/ny subclass ob&ect reference can be given to a super class variable. ,t
is to suport runtime polymorphism. ,t lets us write code that wor#s with
many diUerent types of ob&ects, and decide on the actual ob&ect type at
runtime.
.+ample =2 ) Runtime polymorphism
class /
8
public void disp9 <
8
System.out.println9=printing /=<>
?
?
class 6 e+tends /
8
public void disp9 <
8
System.out.println9=printing 6=<>
?
?
class C e+tends 6
8
public void disp9 <
8
System.out.println9=printing C=<>
?
?
public class )est/pp
8
public static void main9String args:;<
8
/ a1 D new /9<> 6 b1 D new 69<>
C c1 D new C9<>
/ oref>

oref D a1> oref.disp9<>
oref D b1> oref.disp9<>
oref D c1> oref.disp9<>
HI
?
?
output AA printing /
printing 6
printing C
Abstract class
/ class is abstract if one or more methods in it are de"ned by the
abstract #ey word. / method is abstract when it has only declaration but no
e+pansion in the base class..o ob&ects can be instantiated from such a
class. $hen writing classes , we run across cases where we can provide
general code and it is upto the developer to customiPe it in a subclass. )o
ma#e sure he customiPes it, we ma#e the method abstract. Such a class is
also made abstract.
HQ
.+ample =3 ) 3emo of abstract class -- 1
abstract class /
8
abstract public void disp9 <>
?
class 6 e+tends /
8
public void disp9 <
8
system.out.println9=&ava is simple=<>
?
?
public class )est/pp
8
public static void main9String args:;<
8
6 b1 D new 69 <>
b1.disp9 <>
?
?

.+ample =; ) 3emo of abstract class -- @
abstract class /
8
abstract String get3ata9 <>
public void disp9 <
8
System.out.println9 get3ata9 < <>
?
?
class 6 e+tends /
8
String get3ata9 <
8
String s D =&ava is simple=>
return9s<>
?
?
public class )est/pp
8
public static void main9String args:;<
8
HV
6 b1 D new 69 <>
b1.disp9 <>
?
?
.ote A constructors, private, static methods can .-) be abstract.
&inal modi@er ))
)o stop overriding
)o stop ,nheritance
creating constants
/o stop overridin' ))
class /nimal
8
"nal void breath9 <
8
System.out.println9= 6reathing...=<>
?
?
class (ish e+tends /nimal
8
public void breath9 < ......WWWW 9 not allowed <
8
System.out.println9=6ubbling...=<>
?
?
/o stop inheritance ))
"nal class /nimal
8
public void breath9 <
8
System.out.println9= 6reathing...=<>
?
?
class (ish e+tends /nimal .....WWWWJ 9 no .. not allowed <
8
public void breath9 <
8
System.out.println9=6ubbling...=<>
?
?
/o create constants))
ME
"nal int a D @F>
a''> .....WWWWJ not allowed
a D FE> .....WWWWJ not allowed
isBa relation )) standard inheritance refers to is-a relation

class /
8
void disp9 <
8
System.out.println9=from /=<>
?
?
class 6 e+tends / LL 6 is-a /
8
69 <
8
disp9 <>
?
?
public class )est/pp
8
public static void main9String args:;<
8
6 b1 D new 69<>
?
?

hasBa relation )) ,t is a state when one ob&ect holds other ob&ect
instances.
class /
8
void disp9 <
8
System.out.println9=from /=<>
?
?
class 6
8
/ a1> LL 6 has-a /
M1
69 <
8
a1 D new /9 <>
a1.disp9 < > LL)he disp of / is avilable to ob& 6
?
?
public class )est/pp
8
public static void main9String args:;<
8
6 b1 D new 69<>
?
?
java Object class ))
Every class in &ava is derived automatically from &ava.lang.-b&ect class.
/ll classes in &ava are subclasses
Every ob&ect thus inherits certain methods. some of them
boolean eGuals9ob< AA used to chec# whether an ob&ect ob
e2uals to this one
protected void @nali0e9< AA called by garbage collector
when it is about to dispose ob&ect

Class 'etClass9< AA ,t gives the run time class of the ob&ect
int hashCode9< AA ,t gives a hashcode value of the ob&ect.
E+ample ME AA 3emo of -b&ect class
class /
8
public void disp9 <
8
System.out.println9=printing /=<>
?
?
class 6 e+tends /
8
public void disp9 <
8
M@
System.out.println9=printing 6=<>
?
?
class C e+tends 6
8
public void disp9 <
8
System.out.println9=printing C=<>
?
?
public class )est/pp
8
public static void main9String args:;<
8
/ a1 D new /9<> 6 b1 D new 69<>
C c1 D new C9<>
/ oref>

oref D a1> oref.disp9<>
System.out.println9 =ref is = ' oref.getClass9< <>
oref D b1> oref.disp9<>
System.out.println9 =ref is = ' oref.getClass9< <>
oref D c1> oref.disp9<>
System.out.println9 =ref is = ' oref.getClass9< <>
?
?
output AA printing /
ref is class /

printing 6
ref is class 6
printing C
ref is class C
Harba'e collection and memor, mana'ement
%ava has a built in process called garbage collector. ,t occurs
automatically , although we can not predict when it will happen. %ava itself
MH
dispose of the memory that no longer has reference to it. 0owever to ma#e
it happen we can set references to null
E+ample M1 AA 3emo of garbage collection
class /
8
void disp9 <
8
System.out.println9=from /=<>
?
?
public class )est/pp
8
public static void main9String args:;<
8
int a: ; D 8 1E,@E,HE ?>
/ b1 D new /9<> int l >
b1.disp9<>
l D a.length>
System.out.println 9 =lD= ' l <>
b1 D null> a D null> LL ma#ing them null
?
?
E+ample M@ AA 3emo of garbage collection Z "naliPe9< method
class )ester
8
public int #>
)ester9 int i <
8
# D i>
?
?

class /
8
int m1>
)ester t>
/9 <
8
MM
m1 D F>
t D new )ester9@FEE<>
?

void disp9 <
8
System.out.println9=from /=<>
?
protected void "naliPe9<
8
t D null> LL inner ob&ect to null
?
?
public class )est/pp
8
public static void main9String args:;<
8
/ b1 D new /9<>
b1.disp9<>
b1 D null>
?
?
interfaces )
)hey provide templates of behaviour, that other classes can implement.
)hey de"ne the design and classes that implement the interface must
provide the implementation of the design.

,n /bstract classes some methods may have de"nition, and leaving few
unde"ned. ,n interfaces no method can be de"ned.
)he data members in /bstract class can be variables or constants but
they are only constants in an interface. / class can e+tend only one
abstarct class. 6ut a class may implement multiple interfaces, and thus
provide an indirect way to multiple inheritance.
class *rinter
8
public void print9<
8
MF
LL set the params
LL print data .....
?
?

interface Copier
8
public void copy3ocument9 3ocument d<>
?

interface (a+
8
public void transmit3ocument93ocument d<>
?


class Multi(unction*rinter e+tends *rinter implements Copier, (a+
8
LL the content ...
?
.ote A / method inside an interface can not be declared private or
protected. )hey can carry public abstract modi"ers only. )he
members must be public, static "nal ma#ing them constants.
interface E+amp
8
public static "nal int a D H>
int b D F> LL eUectively public static "nal
public abstract void calc9 <>
void change9 <> LL eUectively public and abstract
?
E+tending an interface A
5i#e classes interface can inherit from other interfaces. )he sub
interface ac2uires all the method de"nitions and constants of the super
interfaces.
interface .ew+ero+ e+tends Copier, (a+
8
....
?
MC
Mar8er Interface
,n &ava language programming, interfaces with no methods are #nown as mar#er
interfaces. Mar#er interfaces are SerialiPable, Clonable, Single)hreadModel, Event
listener. Mar#er ,nterfaces are implemented by the classes or their super classes in
order to add some functionality.
e.g. Suppose you want to persist 9save< the state of an ob&ect then you have to
implement the SerialiPable interface otherwise the compiler will throw an error. )o
ma#e more clearly understand the concept of mar#er interface you should go
through one more e+ample.
Suppose the interface Clonable is neither implemented by a class named Myclass
nor itBs any super class, then a call to the method clone9< on MyclassBs ob&ect will
give an error. )his means, to add this functionality one should implement the
Clonable interface. $hile the Clonable is an empty interface but it provides an
important functionality.
.+ample >= ) 3emo of ,nterfaces

import &ava.io.R>

interface Student,nter
8
void get3ata9 < throws ,-E+ception>
void show3ata9<>
int calc)ot9<>
4oat calc*ercent9<>
void menu9<>
?
class Student implements Student,nter
8
int rno, m1,m@>
string name>
public void get3ata9 < throws ,-E+ception
8
3ata,nputStream d D new 3ata,nputstream9 System.in <>
System.out.print9 =Enter Rollno A= <>
rno D ,nteger.parse,nt9 d.read5ine9 < <>
System.out.print9 =Enter .ame A= <>
name D d.read5ine9 <>
System.out.println9 =Enter Sub 1 Mar# A= <>
m1 D ,nteger.parse,nt9 d.read5ine9 < <>
System.out.println9=Enter Sub @ Mar# A= <>
m@ D ,nteger.parse,nt9 d.read5ine9 < <>
MI
?
public void show3ata9 <
8
System.out.println 9 =Rollno D = ' rno<>

System.out.println 9 =.ame D = ' name<>
System.out.println 9 =mar#1 D = ' m1<>
System.out.println 9 =mar#@ D = ' m@<>
?
public int calc)ot9 <
8
return 9 m1 ' m@<>
?
public 4oat calc*ercent9 <
8
int t D m1' m@>
return 9 t L @ <>
?
public void menu9 <
8
System.out.println 9 =Enter 1 to get total=<>

System.out.println 9 =Enter @ to get percent=<>
?
?
public class )estStudent
8
public static void main9 String args: ; <
8
Student s D new Student9 <>
s.get3ata9<>
s.show3ata9<>
int tot>
4oat per>
s.menu9 <> LL to display menu
3ata,nputStream d D new 3ata,nputstream9 System.in <>
System.out.print9 =Enter choice A = <>
int n D ,nteger.parse,nt9 d.read5ine9 < <>

MQ
switch9 n <
8
case 1A tot D s.calc)ot9<>
System.out.println9=total D= ' tot<>
brea#>

case @A per D s.calc*ercent9<>
System.out.println9=percentD= ' per<>
brea#>

defaultA System.out.println9 =incorrect choice= <>
?
?
?
Partiall, implementin' an interface
Classes that partially implement an interface must be abstract as they
are only e+panding few methods.
.+ample >= )
interface /
8
void dispone9<>
void disptwo9<>
?
abstract class 6 implements /
8
void disptwo9<
8
system.out.println9=e+panded from b<>
?
?
class C e+tends 6
8
void dispone9 <
8
System.out.println9=e+panded from c=<>
?
?
public class )est/pp
8
public static void main9 string args:;<
8
MV
C #1 D new C9<>
#1.dispone9<>
#1.disptwo9<>
?
?
Inner classes ))
)hey are non static nested classes. )hey nest the de"nition of one
class inside another.
)hey are usefull while handling events such as user closing a window
etc.
.+ample >> )3emo of inner classes
class /
8
class 6
8
public void disp9 <
8
system.out.print9=inside 6 ..=<>
?
?
6 b1>

/9 <
8
b1 D new 69 <>
b1.disp9 <>
?
?

public class )est/pp
8
public static void main9String args:;<
8
/ a1 D new /9<>
?
?

when we instantiate -b&ect a1 of class /, it instantiates internal
ob&ect b1 of class 6.
FE
ProcessAuilder class ))
/n -perating system process can be created using this class, and it
manage all the process attributes. ,t is not at all synchroniPed.

E+ample MF AA 3emo of *rocess6uilder class
import &ava.io.R>
public class )est/pp
8
public static void main9String args< throws ,-E+ception
8
*rocess6uilder pb1>
pb1 D new *rocess6uilder9=notepad.e+e=,="rst.&ava=<>
pb1.start9 <>
?
?
F1
Chapter ?
.+ception $andlin'
E+ception is a runtime error , that may cause abnormal termination
of the program during its e+ecution. $hen an error occurs within a &ava
method , the method creates an e+ception ob&ect and hands it oU
9 )hrowing< to the runtime system. )his e+ception ob&ect contain
information about e+ception, its type, state of the program when it occured.
)he runtime system searches for appropriate bloc# of code to handle
the e+ception.
,f there is no appropriate handler, with in that bloc# the serach
progresses up through the call stac#, until an appropriate handler is found. ,f
no such handler is found, the runtime system stops and the program
terminates.
public class 3ivide
8
public static void main9String args:;<
8
System.out.println9=prog starts here..=<>
int a,b,c>
a D ,nteger.parse,nt9args:E;<>
b D integer.parse,nt9args:1;<>
c D aLb>
System.out.println9=cD=' c<>
System.out.println9=program ends here..=<>
?
?
Running with M cases as below would give a picture A
case 1 A &ava 3ivide M @
case @ A &ava 3ivide M
case H A &ava 3ivide a @
case M A &ava 3ivide M E
)o prevent interuption of the programs 4ow from e+ceptions such as
the ones shown above, handlers are used to catch such e+ceptions and
handle them appropriately through cleanup or message noti"cation.
F@
/here are three t,pes of .+ceptions)
1. Chec8ed .+ceptions B )hese are the e+ceptions which occur during the
compile time of the program. )he compiler chec#s at the compile time that
whether the program contains handlers for chec#ed e+ceptions or not. )hese
e+ceptions do not e+tend Runtime.+ception class and must be handled to
avoid a compile-time error by the programmer. )hese e+ceptional conditions
should be anticipated and recovered by an application. (urthermore Chec#ed
e+ceptions are re2uired to be caught.
Class.ot(oundE+ception
.oSuchMethodE+ception
,nterruptedE+ception
Fnchec8ed .+ceptions B 7nchec#ed e+ceptions are the e+ceptions which
occur during the runtime of the program. 7nchec#ed e+ceptions are internal
to the application and e+tend the java(lan'(Runtime.+ception that is
inherited from java(lan'(.+ception class. )hese e+ceptions cannot be
anticipated and recovered li#e programming bugs, such as logic errors or
improper use of an /*,. )hese type of e+ceptions are also called Runtime
e+ceptions that are usually caused by data errors, li#e arithmetic over4ow,
divide by Pero etc.
0ere is the list of unchec#ed e+ceptions.
/rray,nde+-ut-f6oundsE+c
eption
/rithmeticE+ception
.ull*ointerE+ception
@..rror B /n Error indicates serious problems that a reasonable application
should not try to catch. Most such errors are abnormal conditions. 0ence we
conclude that Errors and runtime e+ceptions are together called as unchec#ed
e+ceptions.
FH

)he e+ception classes can be e+plained as well seeing the hierarchy structureA
)he java(lan' pac#age de"nes several classes and e+ceptions. Some of these
classes are not chec#ed while some other classes are chec#ed.
.IC.P/IOS D.SCRIP/IO
C$.CJ
.D
FC$.CJ.D
/rithmeticE+ception
/rithmetic errors
such as a divide by
Pero
- TES
/rray,nde+-ut-f6oundsE+c
eption
/rrays inde+ is not
within array.length
- TES
Class.ot(oundE+ception
Related Class not
found
TES -
,-E+ception
,nput-uput "eld not
found
TES -
,llegal/rgumentE+ception
,llegal argument
when calling a
method
- TES
,nterruptedE+ception
-ne thread has been
interrupted by
another thread
TES -
.oSuchMethodE+ception .one+istent method TES -
.ull*ointerE+ception
,nvalid use of null
reference
- TES
.umber(ormatE+ception
,nvalid string for
conversion to
number
- TES
FM
/s you have come to #now that e+ceptions are -b&ects that means an ob&ect is
thrown when you throw an e+ception. Moreover only those ob&ects could be thrown
whose classes are derived from /hro%able.
,t is interesting to note here that the ob&ects of your own design could also be
thrown provided that they should be the subclass of some member of the )hrowable
family. /lso the throwable classes which are de"ned by you must e+tend .+ception
class.
$andlin' .+ceptions in java

,t is done using "ve #ey words try, catch, throw, throws, "nally
try
8
LL statements that may throw e+ception
?
catch9 E+ceptiontype-1 e<
8
LL statements to handle
?
catch9 E+ceptiontype-@ e<
8
LL statements to handle
?
"nally
8
LL clean up code or e+it code9optional<
?
)he code in the "nally bloc# always gets e+ecuted regardless of what
happens with in the try bloc#. ,t is used to close "les, data base connections
, Soc#ets etc.

$hen e+ception occurs the method may instantiate an e+ception ob&ect
and hand it to the run time system to deal with it.
)he e+ception ob&ect carry the following
1. )ype of e+ception - its class
@. $here it occured - stac# trace
H. Conte+t information - message and state

FF
)he arguement type in the catch clause is from throwable class or
one of its subclasses. -nce an e+ception is thrown , the bloc# from where it
is thown e+pires and control can not return bac# to the throw point.
%ava uses a termination model of handling e+ception rather than
resumption model.

/hro%able class ))

,t is the super class in the hierarchy, under &ava.lang.-b&ect. /n
e+ception ob&ect is an instance of throwable class or any of its sub class.
)he )hrowable class provides a set of methods apart from various
constructors
)hrowable9< A
)hrowable9String message< A
getMessage9< A retuns the message from the ob&ect or null
printStac#)race9< A print the stac# trace
/ stac# )race is a list of methods e+cecuted in se2uence that lead to the
e+ception.
E+ample MC AA
public class 3ivide
8
public static void main9String args:;<
8
System.out.println9=prog starts here..=<>
int a,b,c>
try
8
a D ,nteger.parse,nt9args:E;<>
b D integer.parse,nt9args:1;<>
c D aLb>
System.out.println9=cD=' c<>
?
catch 9 .umber(ormatE+ception e<
8
system.out.println9=,nvalid argumets=<>
?
FC
catch 9 /rithmeticE+ception e<
8
system.out.println9=Second /rg can not be Pero=<>
?
catch 9 /ray,nde+-ut-f6oundsE+ception e<
8
system.out.println9=pass proper args=<>
?

System.out.println9=program ends here..=<>
?
?

Order of Catch Aloc8s ))
)he order of catch bloc#s are important when there are multiple catch
bloc#s. )he e+ception subclasss must come before any of its super class.
-therwise the subclass e+ception never gets e+ecuted.
.+ample >2 ) incorrect ordering of E+ception
public class 3ivide
8
public static void main9String args:;<
8
System.out.println9=prog starts here..=<>
int a,b,c>
try
8
a D ,nteger.parse,nt9args:E;<>
b D integer.parse,nt9args:1;<>
c D aLb>
System.out.println9=cD=' c<>
?
catch 9 E+ception e<
8
System.out.println9=,t is = ' e=<>
?
catch 9 /rithmeticE+ception e<
8
System.out.println9=Second /rg can not be Pero=<>
?
System.out.println9=program ends here..=<>
FI
?
?
0ence it is improtant to handle right e+ception in the right conte+t.
ested tr, statements ))

Each time a try in entered , the conte+t of the E+ception is pushed on
to the stac#. ,f an inner try does not have a catch for an e+ception, the
stac# is unwound and catch belonging to ne+t try is inspected for a match.
.+ample >3 ) 3emo nested try
public class 3ivide
8
public static void main9String args:;<
8
System.out.println9=prog starts here..=<>
int a,b,c>
try
8
a D ,nteger.parse,nt9args:E;<>
b D ,nteger.parse,nt9args:1;<>
try
8
c D aLb>
System.out.println9=cD=' c<>
?

catch 9 /rithmeticE+ception e<
8
System.out.println9=Sec./rg cannot be Pero=<>
?

?
catch 9 .umber(otmatE+ception e<
8
System.out.println9=,nvalid argumets=<>
?

catch 9 /ray,nde+-ut-f6oundsE+ception e<
8
FQ
System.out.println9=pass proper args=<>
?

System.out.println9=program ends here..=<>
?
?
Redirectin' .+ceptions usin' 7thro%s7 ))
$hen an e+ception can occur in a method, then it is supposed to be
handled, or atleast e+plicitely warn the potential callers about its
possibility. )his is done using a throws clause in the method declaration so
that it can be passed to a diUerent method in the call stac#.

void 3ivide9 < throws E+ception-/, E+ception-6
8
?
E+ample MVAA demo of throws
public class )estthrows
8
public static void main9String args:;<
8
int i> int nDargs.length>
try
8
for9 iDE>iNn>i''<
dispnames9args:i;<>
?

catch 9 Class.ot(oundE+ception e<
8
System.out.println9=not found = ' e<>
?
?
static void dispnames9String s< throws Class.ot(oundE+ception
8
Class c D Class.for.ame9s<>
System.out.println9=class name = ' c.get.ame9<<>
?
?
/he Je,%ord 7 thro% 7 ))
FV
E+ceptions are thrown by run time. 6ut they can even be thrown by
using a throw statement.
throw N E+ception -b&ect G

)he E+ception ob&ect is an ob&ect of class )hrowable or any of its
subclass. ,n a speci"c case where an instance of E+ception ob&ect is to be
thrown, it ta#es the form as

throw new N E+ception -b&ect G
E+ample FE AA demo of )hrowtest
public class )estthrow
8
public static void main9String args:;< throws E+ception
8
int i1 D 1F>
int i@ D @E>
if 9i1 G i@<
throw new E+ception9=(irst numb can not be more=<>
else
System.out.print9=o#=<>
?
?

/hro%in' custom 9user de@ned: .+ception ))
7sefull to handle business speci"c error conditions.(or E+, while
withdrawal from ban#, an E+ception Min6al may be created. Such
E+ceptions are placed as a subclass of E+ception under )hrowable class.
)hey can be created using any method as below
1. )hrowable 7e+cep D new )hrowable9 <>
@. )hrowable 7e+cep D new )hrowable9=message=<>

H. class 7e+cep e+tends E+ception
8
public 7e+cep9<
8
...
?
public 7e+cep9String s<
8
...
CE
?
?
,t is thrown by using #eyword throw. ,t is also possible to override the
methods such as getmessage9<, toString9< etc.
.+ample ?1 ) demo of custom e+ceptions
import &ava.io.R>
class /geE+ception e+tends E+ception
8
int age>
/geE+ception9String mesg<
8
super9mesg<>
?
/geE+ception9 <
8
super9 <>
?
?
class young/geE+ception e+tends /geE+ception
8
young/geE+ception9int a1, String mesg<
8
super9=you are too young for= ' mesg<>
age D a1>
?
young/geE+ception9 <
8
super9 =too young=<>
?
?
class invalid/geE+ception e+tends /geE+ception
8
invalid/geE+ecption9String mesg<
8
super9mesg<>
?
invalid/geE+ception9int a1 <
8
super9 =,nvalidformat=<>
age D a1>
?
?
C1
public )estcustom
8
public static void main9String args:;<
8
int s/ges D 8 @1,1@,1Q,-F,MF?>
int i, nDs/ges.length>
try
8
for9 iDE> iNn> i''<
test/ges9s/ges:i;<>
?

catch 9 invalid/geE+ception e<
8
system.out.println9 e.getMessage9< <>
?
catch 9 young/geE+ception e<
8
System.out.println9 e.getMessage9< <>
?
?
static void test/ges9int a< throws invalid/geE+ception,
young/geE+ception
8
if 9a N E< throw
new invalid/geE+ception9a<>
if 9a ND1F< throw
new young/geE+ception9a,=&ava=<>
if 9a G ME< throw
new /geE+ception9=Retire. say no to &ava=<>

System.out.println9=you are allowed to learnJ=<>
?
?
Rethro%in' an .+ception ))

/n e+ception that is caught can once again be rethrown and can be
handled again. )he try bloc# &ust above the rethrown statement will catch
this ob&ect.
,t is used to propagate an e+ception.,t has no special synta+.
.+ample ?4 ) 3emo of rethrowing e+ceptions
C@
public class Rethrowtest
8
public static void main9String args:;<
8
System.out.println9=prog starts here..=<>
int a,b,c>
try
8
a D ,nteger.parse,nt9args:E;<>
b D integer.parse,nt9args:1;<>
calc9a,b<>
?

catch 9 /rithmeticE+ception e<
8
System.out.println9=0andled in main=<>
System.out.println9=...,nvalid argumets J=<>
?

catch 9 .umber(ormatE+ception e<
8
System.out.println9=,nvalid argumets=<>
?

catch 9 /ray,nde+-ut-f6oundsE+ception e<
8
System.out.println9=pass proper args=<>
?

System.out.println9=program ends here..=<>
?
static void calc9int a1, int b1<
8
try
8
int c1 D a1Lb1>
System.out.println9=c1D=' c1<>
?
catch 9 /rithmeticE+ception e<
8
CH
System.out.println9=rethrowing now..=<>
throw e>
?
?
?
CM
/o Print a Stac8 /race Messa'e
%&ava provides a method 'etMessa'e9: method that is used with an ob&ect of the
.+ception class to print errors to debug the process. ,nstead of this this method we
can get more information about the error process if we use print a stac8 trace from
the e+ception using the printStac8/race9: method that is the method of the
/hro%able class and prints the stac# trace to the console and provides the line
numbers of statements that called the methods in the current stac#.
try 8
LL ......
?
catch 9,-E+ception e< 8
LL ...........
System.out.print9=XotE+ceptionA='
e.printStac#)race9 < >
?
ASS.R/IOS 9 D.SIH AK CO/RAC/ : ))

)hey can be used to test the assumptions made by the programmer and
create software according to user re2uirements
/ssertions are three types

1. pre condition A /pplication must satisfy before calling an e+ternal
component
@. post condition A /pplication must satisfy this after the e+ecution of the
e+ternal component
H. invariant A /pplication must always satisfy this condition
E+ceptions test abnormal conditions where as /ssertions test the conditions
assumed by the programmer.
.+ample ?= ) 3emo /ssertions

public class )ester
8

public static void main9String args:;<
8
)ester d D new )ester9 <>
d.chec#9F,E<>
?

CF
void chec#9int a, int b<
8
assert bJDEA =the value b can not be Pero=>
double c D aLb>
System.out.println9=cD='c<>
?
?
compilation A &avac -source1.M )ester.&ava
running A &ava -ea )ester
Java(Ftil Pac8a'e
%ava 7tility pac#age is one of the most commonly used pac#ages in the &ava
program. )he 7tility *ac#age of %ava consist of the following componentsA
collections frame%or8
le'ac, collection classes

event model

date and time facilities

internationali0ation

miscellaneous utilit, classes such as string to#eniPer, random-
number generator and bit array
0ere are some of the description of the utility classes of this pac#ageA
Data Structure Classes
3ata Structure Classes are very useful classes for implementing standard
computer science data structuresA including 6itSet, 3ictionary, 0ashtable,
Stac# and Vector. )he Enumeration interface of &ava.util pac#age is used to
count through a set of values.
Date syst
)he 3ate class is used to manipulate calendar dates in a system-
independent fashion.
Strin'/o8eni0er
)his String)o#eniPer class is used to convert a String of te+t into its to#ens.
CC
Properties
)he properties table contains #eyLvalue pairs where both the #ey and the
value are Strings and the class is used by the System class to implement
System properties.
Observer and Observable
Classes that implement the -bserver interface can =watch= -bservable
ob&ects for state changes. $hen an -bservable ob&ect changes it noti"es all
of its -bservers of the change.
RandomBumber Henerator
)he Random .umber Xenerator class is used to generate the random-
numbers.
.numeration
)he Enumeration interface de"nes a generic programming interface for
iterating through a set of valu
.+ample ?> )) Demo of a stac8 class
LL 3emonstrate the Stac# class.
import &ava.util.R>
class Stac#3emo 8
static void showpush9Stac# st, int a< 8
st.push9new ,nteger9a<<>
System.out.println9=push9= ' a ' =<=<>
System.out.println9=stac#A = ' st<>
?
static void showpop9Stac# st< 8
System.out.print9=pop -G =<>
,nteger a D 9,nteger< st.pop9<>
System.out.println9a<>
System.out.println9=stac#A = ' st<>
?
public static void main9String args:;<
8
Stac# st D new Stac#9<>
System.out.println9=stac#A = ' st<>
showpush9st, M@<>
showpush9st, CC<>
showpush9st, VV<>
showpop9st<>
showpop9st<>
showpop9st<>
try 8
showpop9st<>
? catch 9EmptyStac#E+ception e< 8
CI
System.out.println9=empty stac#=<>
?
?
?
.+ample ?? )) Demo of a Date class
LL Show date and time using only 3ate methods.
import &ava.util.3ate>
public class 3ate3emo
8
public static void main9String args:;<
8
LL ,nstantiate a 3ate ob&ect
3ate date D new 3ate9<>
LL display time and date using toString9<
System.out.println9date<>
LL 3isplay number of milliseconds since midnight, %anuary 1,
LL1VIE XM)
long msec D date.get)ime9<>
System.out.println9=Milliseconds since %an. 1, 1VIE XM) D = '
msec<>
?
?
Chapter 1
Collections
%ava provides the Collections Frameor!. ,n the Collection Framework, a
collection represents the group of the ob&ects. /nd a collection framework is the
uni"ed architecture that represent and manipulate collections. )he collection
CQ
framewor# provides a standard common programming interface to many of the
most common abstraction without burdening the programmer with many
procedures and interfaces. ,t provides a system for organiPing and handling
collections. )his framewor# is based onA
,nterfaces that categoriPe common collection types.
Classes which proves implementations of the ,nterfaces.
/lgorithms which proves data and behaviors need when using collections i.e.
search, sort, iterate etc.
(ollowing is the hierarchical representation for the relationship of all four interfaces
of the collection framework which illustrates the whole implementation of the
framewor#.

3uring the designing of a software 9application< it need to be remember the
following relationship of the four basic interfaces of the framewor# are as followsA
)he Collection interface which is the collection of ob&ects. )hat permits the
duplication of the value or ob&ects.
Set is the interface of the collections framework which e+tends the Collection
but forbids duplicates.
/n another interface is the 5ist which also e+tends the Collection. ,t allows
the duplicates ob&ects on diUerent position because it introduces the
positional inde+ing.
/nd Map is also a interface of the collection framework which e+tends neither
Set nor Collection.
Some interfaces and classes of the collection framework are as followsA
I/.R&AC.S C5ASS.S
CV
Collection ,nterface
,terator ,nterface
Set ,nterface
5ist ,nterface
5ist,terator ,nterface
Map ,nterface
SortedSet ,nterface
SortedMap ,nterface
0ashSet Class
)reeSet Class
/rray5ist Class
5in#ed5ist Class
0ashMap Class
)reeMap Class
Vector Class
Stac# Class
Advanta'e of the Collections Frameor!)
)he collections framewor# oUers developers the following bene"tsA
,t increases the readability of your collections by providing a standard set of
interfaces which has to be used by many programmers in diUerent
applications.
,t ma#es your code more 4e+ible. Tou can ma#e the code 4e+ible by using
many interfaces and classes of the collection framework.
,t oUers many speci"c implementations of the interfaces. ,t allows you to
choose the collection that is most "tting and which oUers the highest
performance for your purposes.
)his collection is a framewor# supported in &ava.util pac#age. )hey
are used to group elements in various ways. )he framewor# has a set of
interfaces, and some implementations to manipulate collections.
Collection framewor# has many interfaces such as collection, Map, ,terator

Collection classes AA
)here are standard collection classes that implement collection
interface.
/bstractCollection A implement Collection interface.
,t is used to organiPe a collection which can not be
modi"ed.
/bstract5ist A E+tends /bstractCollection, and implement the 5ist
interface. ,t can access data randomly using an inde+ value.
/bstract[ueue A E+tends /bstractCollection and impl parts of the
2ueue interface.
/bstractSe2uential5ist A E+tends /bstract5ist into se2uential
IE

5in#ed5ist A E+tends /bstractSe2uential5ist where each element #nows
where is the ne+t

/rray5ist A ,mplements dynamic resiPable array, e+tends /bstract5ist
interface.

/rray3e2ueA ,mplements dynamic de2ue, by e+tending /bstract5ist and,
impl the 3e2ue ,nterface
/bstractSet A E+tends /bstractCollection and imple the Set interface

0ashSet A E+tends /bstractSet and imple the Set interface. ,t is used to
create a collection and store it in a hash table. Every
collection has
a uni2ue hash code. )he type of storing is called hashing.
Elements may
be stored in any order and it does not gurantee order.

)reeSet A E+tends /bstractSet to implement a set stored in tree form.
)he
elements are stored in a tree structure
Map classes A /bstractMap A ,mplement the Map interface

0ashMap A ,t e+tends the /bstractMap using a hash

)reeMap A ,t e+tends /bstractMap using a tree

/part from these , we see /rrays, Vector, Stac#, 0ashtable,
3ictionary, properties, and other classes which are not technically
members of this collection framewor#.
I1
.+ample ?1 ) 3emo of array class
import &ava.util.R>
class arrays
8
public static void main9String args:;<
8
int a:; D new int:1E;>
for9int i D V> i G E> i--<
array:i; D -i>
for9int i D E> i N a.length> i''<
System.out.print9a:i; ' = =<>
System.out.println9<>
/rrays.sort9a<>
for9int i D E> i N a.length> i''<
System.out.print9a:i; ' = =<>
System.out.println9<>
System.out.print9=(ound -F at position = '
/rrays.binarySearch9a, -F<<>
?
?
.+ample ?2 ) 3emo of Vector class
/ Vector class is similar to /rray5ist e+cept that Vector class is
synchroniPed. Multiple threads can not access it simultaneously. ,t
implement the dynamic array. ,t predates collection framewor#. ,t has
been rewritten to be compatible with collection framewor#
import &ava.util.R>
class )estvector
8
public static void main9String args:;<
8
Vector v D new Vector9F<>
System.out.println9=CapacityA = ' v.capacity9<<>

v.addElement9new ,nteger91E<<>
v.addElement9new ,nteger911<<>
I@
v.addElement9new ,nteger9@@<<>
v.addElement9new ,nteger9HH<<>
v.addElement9new ,nteger9MM<<>

v.addElement9new 3ouble9H.1M<<>
v.addElement9new (loat9H.1M<<>
System.out.println9=CapacityA = ' v.capacity9<<>
System.out.println9=SiPeA = ' v.siPe9<<>
System.out.println9=(irst itemA='9,nteger<v."rstElement9<<>
System.out.println9=5ast itemA= ' 9(loat< v.lastElement9<<>

if9v.contains9new ,nteger9HH<<<
System.out.println9=(ound H.=<>
,terator e D v.iterator9<>
while 9e.has.e+t9<<
8
s D 9String<v.ne+t9<>
System.out.print9s<>
?
?
?
output A
capacity A F
capacity A 1E
siPe A I
(irst item E
5ast item H.1M

(ound a H
1E 11 @@ HH MM H.1M H.1M
.+ample ?3 ) 3emo of /rray5ist 9 3ynamic and can grow <
,t holds only the ob&ects, and it can grow or shrin# at run time.

import &ava.util.R>
class arraylist
8
public static void main9String args:;<
8
/rray5istNStringG al D new /rray5istNStringG9<>
IH
al.add9=Red=<>
al.add9=6lue=<>
al.add9=Tellow=<>
al.add91, =$hite=<>
System.out.println9=7sing the add method=<>
System.out.println9al<>
al.remove9=$hite=<>
System.out.println9al<>
String l D al.get91<>
System.out.println9l<>
System.out.println9=7sing the ,terator interface=<>
String s>
,terator e D al.iterator9<>
while 9e.has.e+t9<<
8
s D 9String<e.ne+t9<>
System.out.print9s<>
?
?
?

IM
.+ample ?; ) 3emo of lin#edlist

import &ava.util.R>
class lin#edlist
8
public static void main9String args:;<
8
5in#ed5istNStringG ls D new 5in#ed5istNStringG9<>
ls.add9=6lue=<>
ls.add9=Xreen=<>
ls.add9=Tellow=<>
ls.add9=-range=<>
ls.add(irst9=Red=<>
ls.add5ast9=6lac#=<>
ls.add91, =Xrey=<>
System.out.println9ls<>
ls.remove9=6lac#=<>
System.out.println9ls<>
ls.remove5ast9<>
System.out.println9ls<>
System.out.println9=7pdating lin#ed list items=<>
ls.set9E, =&ava=<>
ls.set91, =C=<>
ls.set9@, =C''=<>
ls.set9H, =-racle=<>
ls.set9M, =/S*.net=<>
System.out.println9ls<>
?
?

IF
.+ample 1< ) 3emo of 0ashSet class

,t is set of uni2ue elements, and it uses a hash for storing data. /s it uses
hash methods such as add, remove, siPe etc and they ta#e same amount of
time. .o gurantee of order of storage.
import &ava.util.R>
class hashset
8
public static void main9String args:;<
8
0ashSetNStringG h1 D new 0ashSetNStringG9<>
h1.add9=Red=<>
h1.add9=6lue=<>
h1.add9=Xreen=<>
System.out.println9h1<>
int s D h1.siPe9< >
System.out.println9s<>

if9 h1.contains9=Red=<<
System.out.print9=Red present= <>

?
?

.+ample 11 ) 3emo of looping over all elements in a list
9 ,terator <
import &ava.util.R>
class iterator
8
public static void main9String args:;<
8
5in#ed5istNStringG l D new 5in#ed5istNStringG9<>
l.add9=,tem E=<>
l.add9=,tem 1=<>
l.add9=,tem @=<>
,teratorNStringG it D l.iterator9<>
while9it.has.e+t9<<
8
IC
System.out.print9it.ne+t9<<>
?
?
?
.+ample ??) 3emo of 5ist,terator

,t can 5oop over in both the directions

import &ava.util.R>
class listiterator
8
public static void main9String args:;<
8
5in#ed5istNStringG li D new 5in#ed5istNStringG9<>
li.add9=,tem E=<>
li.add9=,tem 1=<>
li.add9=,tem @=<>
li.add9=,tem H=<>
5ist,teratorNStringG lite D li.list,terator9<>
while9lite.has.e+t9<<
8
lite.set9=)his is = ' lite.ne+t9<<>
LR set9< is used to replace the element which is
returned by ne+t9< or previous9< by the current RL
?
while9lite.has*revious9<<
8
System.out.println9lite.previous9<<>
?
?
?
.+ample 14 ) 3emo of 0ashMap
0ash Maps allow the data to be stored as #eyLvalue pairs where
#ey,value are ob&ects. Map can be inde+ed with strings instead of numbers.
-n such Maps it is possible to access elements using strings or search them
using string value.

II
import &ava.util.R>
class hashmap
8
public static void main9String args:;<
8
0ashMapNString, StringG hm D new 0ashMapNString, StringG9<>
hm.put9=,tem E=, =Value E=<>LL to add #ey,value pair to map
hm.put9=,tem 1=, =Value 1=<>
hm.put9=,tem @=, =Value @=<>
hm.put9=,tem H=, =Value H=<>

Set s D hm.entrySet9<>LL get corresponding set
,terator it D s.iterator9<>
while9it.has.e+t9<<
8
Map.Entry mp D 9Map.Entry< it.ne+t9<>
System.out.println9mp.get\ey9< ' =L= ' mp.getValue9<<>
LL it prints the #ey, value pairs
?
System.out.print9hm.get9=,tem E=<<>LLsearch for corresponding value
?
?
IQ
.+ample 1= ) 3emo of 0ashtable class
,t imple the interfaces such as Map,Clonable,SerialiPable. ,t is used to store
values, in the form of map #ey with a value. )he =#ey= should implement the
hashcode, and e2uals method to store and retrieve values in a hashtable. ,t
was how maps were implemented before collection framewor#.
import &ava.util.R>
class )esthashtable
8
public static void main9String args:;<
8
0ashtableNString, StringG ht D new 0ashtableNString, StringG9<>
ht.put9=61=, =6illgates=<>
ht.put9=C@=, =Chouhan=<>
ht.put9=*H=, =*ush#al=<>
ht.put9=/M=, =/nu& Singh=<>

Enumeration e D ht.#eys9<>
while9e.hasMoreElements9<<
8
String s D 9String< e.ne+tElement9<>
System.out.println9=#ey = ' s ' =L= ' =Val= ' ht.get9s<<>
?
?
?
output A #ey C@ L val Chouhan
#ey /M L val /nu&
...e t c...
IV
.+ample 1> ) 3emo of 0ashtable class
import &ava.util.R>
class )esthashtable
8
public static void main9String args:;<
8
0ashtableNString, ,ntegerG ht D new 0ashtableNString, ,ntegerG9M<>
ht.put9=6illgates=, ,nteger9FF<<>
ht.put9=Chouhan=,,nteger9 CE<<>
ht.put9=*ush#al=, ,nteger9F@<<>
ht.put9=/nu&=, ,nteger9MC<<>

Vector NStringG v D ht.#eySet9<>
Collection.sort9v<>
Enumeration e D v.elements9<>
LL sorted list
while9e.hasMoreElements9<<
8
String s D 9String< e.ne+tElement9<>
System.out.println9=#ey = ' s ' =L= ' =Val= ' ht.get9s<<>
?
?
?
output A #ey /nu& L val MC
#ey 6illgates L val FF
...e t c... sorted on #ey 9string<
QE
.+ample 1? ) 3emo of enumeration
enum Mango 8
6roo#s, Manilla, /lphanso, \esar, Maya
?
class )estMango
8
public static void main 9String args:;<
8
Mango ap>
System.out.println9=0ere are all Mango constantA=<>
Mango allmangos:; D Mango.values9<>
for9Mango a A allmangos<
System.out.println9a<>
System.out.println9<>
ap D Mango.value-f9= \esar=<>
System.out.println9=ap contains='ap<>
?
?
Chapter 2
Multi /hreadin'
Q1
Multithreading is a concept, where by it is possible to achieve concurrent
e+ecution of multiple units of a single program. / program in &ava can have
multiple 4ow of controls and each 4ow of control is nothing but a small unit
of e+ecution, #nown as a thread. )hus a thread can run in parallel to the
other threads.
,n the multithreading concept, several multiple lightweight processes are run in a
single processLtas# or program by a single processor. (or E+ample, $hen you use a
%ord processor you perform a many diUerent tas#s such as printin'6 spell
chec8in' and so on. Multithreaded software treats each process as a separate
program.
,n %ava, the %ava Virtual Machine 9J"M: allows an application to have multiple
threads of e+ecution running concurrently. ,t allows a program to be more
responsible to the user. $hen a program contains multiple threads then the C*7
can switch between the two threads to e+ecute them at the same time.
(or e+ample, loo# at the diagram shown asA
,n this diagram, two threads are being e+ecuted having more than one tas#. )he
tas# of each thread is switched to the tas# of another thread.
Advanta'es of multithreadin' over multitas8in' )
Reduces the computation time.
,mproves performance of an application.
)hreads share the same address space so it saves the memory.
Conte+t switching between threads is usually less e+pensive than between
processes.
/ )hread runs inside a process and a process can contain one or more
threads. Multithreading allows a program to do more than one tas# at a time.
)his means that one process can have a thread that performs a calculation,
another thread that performs a service, and so forth.
Q@
/ thread is not a complete program by itself, and can not run on its own.
0owever, each thread has a begining, and an end, and a se2uential 4ow of
e+ecution at a single point of time.
/t any given point of time within the run time of the program, only one
thread will be e+ecuted by the processor. )he C*7 time will be divided into
slices, and it switches between threads and runs so fast that it appears as if
all threads are running at the same time.
3iUerences between multiprocesing and multithreading A
6oth fall in the category of Multitas#ing. )hey diUer in the level at
which concurrency is done. Concurrent processes in Multiprocesing have
their own separate address space and hence they can not access memory or
"les of other processes.
)hreads share resources li#e memory space, opened "les. )hough
they are running seperately, they also wor# together to form a greater unit. ,t
is better as a programming practice , to identify diUerent parts of a program
that can perform in paralell, and implement them into independent threads.

,n %ava *rogramming language, thread is a se2uential path of code e+ecution within
a program. Each thread has its own local variables, program counter and lifetime
Main /hread
$hen any standalone application is running, it "rstly e+ecute the main9: method
which runs in a thread, called the main thread. ,f no other threads are created by
the main thread, then program terminates when the main9< method complete its
e+ecution. )he main thread creates some other threads called child threads. )he
main9< method e+ecution can "nish, but the program will #eep running until the all
threads have completed its e+ecution.
Creatin' /hreads
)hread can be implemented through any one of two waysA
.+tendin' the java(lan'(/hread Class
Implementin' the java(lan'(Runnable Interface
QH
I( .+tendin' the java(lan'(/hread Class
(or creating a thread a class have to e+tend the )hread Class. (or creating a thread
by this procedure you have to follow these stepsA
1. E+tend the java(lan'(/hread Class.
@. -verride the run9 : method in the subclass from the )hread class to de"ne
the code e+ecuted by the thread.
H. Create an instance of this subclass. )his subclass may call a )hread class
constructor by subclass constructor.
M. ,nvo#e the start9 : method on the instance of the class to ma#e the thread
eligible for running.
/he follo%in' pro'ram demonstrates a sin'le thread creation e+tendin'
the 7/hread7 Class)
class My)hread e+tends )hread8
Strin' sDnull>
My)hread9String s1<8
sDs1>
start9<>
?
public void run9<8
System.out.println9s<>
?
?
public class Run)hread8
public static void main9String args:;<8

My)hread m1Dne% My)hread9=)hread started....=<>
?
?

QM
E+ample CC A 3emo of creating a thread by e+tending )hread class
class Samp)hread e+tends )hread
8
public Sampthread9String name<
8
super 9 name <>
?
public void run9<
8
System.out.println9=.ow inA = ')hread.current)hread9< <>
for9int i D E> iNDF > i''<
System.out.print9= = ' i<>
?
?

public class )estthread
8
public static void main9 String args:;<
8
Samp)hread t D new Samp)hread9=(irst=<>
t.start9 <>
System.out.println9=,t isA=')hread.current)hread9 <<>
?
?
output A
,t is A )hread:main,F,main;
.ow inA )hread:(irst,F,main;
E 1 @ H M F
QF
II( Implementin' the java(lan'(Runnable Interface
)he procedure for creating threads by implementing the Runnable ,nterface is as
followsA
1. / Class implements the Runnable ,nterface, override the run9< method to
de"ne the code e+ecuted by thread. /n ob&ect of this class is Runnable
-b&ect.
@. Create an ob&ect of /hread Class by passing a Runnable ob&ect as argument.
H. ,nvo#e the start9 : method on the instance of the )hread class.
/he follo%in' pro'ram demonstrates the thread creation implentin' the
Runnable interface)
class My)hread1 implements Runnable8
)hread t>
Strin' sDnull>
My)hread19String s1<8
sDs1>
tDne% )hread9this<>
t.start9<>
?
public void run9<8
System.out.println9s<>
?
?
public class Runable)hread8
public static void main9String args:;<8
My)hread1 m1Dne% My)hread19=)hread
started....=<>
?
?
0owever, this program returns the output same as of the output generated through
the previous program.
)here are two reasons for implementing a Runnable interface preferable to
e+tending the )hread ClassA
1. ,f you e+tend the /hread Class, that means that subclass cannot e+tend any
other Class, but if you implement Runnable interface then you can do this.
@. )he class implementing the Runnable interface can avoid the full overhead
of /hread class which can be e+cessive.
QC
E+ample CIA 3emo of threads implementing Runnable interface
class Samp)hread implements Runnable
8
)hread t>
public Samp)hread9String name<
8
t D new )hread9this, name<>
t.start9 <>
?
public void run9<
8
System.out.println9=.ow in A= ')hread.current)hread9< <>
for9int i D E> iNDF > i''<
System.out.print9i'= =<>
?
?

public class )estthread
8
public static void main9 String args:;<
8
Samp)hread + D new Samp)hread9=(irst=<>
System.out.println9=,t isA=')hread.current)hread9 <<>
?
?
output A ,t is A )hread:main,F,main;
.ow inA )hread:(irst,F,main;
E 1 @ H M F
QI
/hread 5ifeBc,cle ))
3uring the life time of a thread it can enter into F states and it can move
from one state to other in various ways.
1. .ewborn @. Runnable H. Running M. 6loc#ed F. 3ead

1. e% state L /fter the creations of )hread instance the thread is in this state
but before the start9< method invocation. /t this point, the thread is
considered not alive.

@. Runnable 9Read,BtoBrun: state L / thread start its life from Runnable
state. / thread "rst enters runnable state after the invo#ing of start9< method
but a thread can return to this state after either running, waiting, sleeping or
coming bac# from bloc#ed state also. -n this state a thread is waiting for a
turn on the processor.

H. Runnin' state L / thread is in running state that means the thread is
currently e+ecuting. )here are several ways to enter in Runnable state but
there is only one way to enter in Running stateA the scheduler select a thread
from runnable pool. ,t will be in this state until
,t dies
,t is bloc#ed for ,-
,t calls sleep9<, wait9<, yield9<
,t is preempted by a higher priority thread
,ts time slice e+pires
M. Dead state L / thread can be considered dead when its run9< method
completes. ,f any thread comes on this state that means it cannot ever run
again.
F. Aloc8ed B / thread can enter in this state because of waiting the resources
that are hold by another thread. / )hread enter into this state when ,t calls
sleep9<, suspend9<, wait9< . ,t calls ,-, or ,t is waiting for the monitor
QQ
Di-erent states implementin' MultipleB/hreads are)
/s we have seen diUerent states that may be occur with the single thread. /
running thread can enter to any non-runnable state, depending on the
circumstances. / thread cannot enters directly to the running state from non-
runnable state, "rstly it goes to runnable state. .ow lets understand the some non-
runnable states which may be occur handling the multithreads.
1 Sleepin' L -n this state, the thread is still alive but it is not runnable, it
might be return to runnable state later, if a particular event occurs. -n this
state a thread sleeps for a speci"ed amount of time. Tou can use the method
sleep9 : to stop the running state of a thread.

static void sleep9lon' millisecond: thro%s Interrupted.+ception
@ !aitin' for oti@cation L / thread waits for noti"cation from another
thread. )he thread sends bac# to runnable state after sending noti"cation
from another thread.

@nal void %ait9lon' timeout: thro%s Interrupted.+ception
@nal void %ait9: thro%s Interrupted.+ception
H Aloc8ed on IMO L )he thread waits for completion of bloc#ing operation. /
thread can enter on this state because of waiting ,L- resource. ,n that case
the thread sends bac# to runnable state after availability of resources.

M Aloc8ed for joint completion L )he thread can come on this state because
of waiting the completion of another thread.

F Aloc8ed for loc8 acGuisition L )he thread can come on this state because
of waiting to ac2uire the loc# of an ob&ect.
Methods of )hread class AA
Methods that can be applied appl, on a /hread)
Some ,mportant Methods de"ned in java(lan'(/hread are shown in the tableA
Method
Return
/,pe
Description
QV
get.ame9 < String Retrieve the name of the thread ob&ect or instance.
start9 < Void Start the thread by calling its run method.
run9 < Void
)his method is the entry point to e+ecute thread, li#e
the main method for applications.
sleep9 < Void
Suspends a thread for a speci"ed amount of time 9in
milliseconds<.
is/live9 <
6oolea
n
)his method is used to determine the thread is running
or not.
interrupt9 < void
)he method interrupt the threads on which it is
invo#ed.
yield9 < void
6y invo#ing this method the current thread pause its
e+ecution temporarily and allow other threads to
e+ecute.
&oin9 < void
)his method and join9lon' millisec: )hrows
,nterruptedE+ception. )hese two methods are invo#ed
on a thread. )hese are not returned until either the
thread has completed or it is timed out respectively.

wait9<, notify9<,notify/ll9< AA )hey are the methods of an ob&ect class. $hen
a thread calls wait9< , it enter into a bloc#ed state. 9i.e $ait 2ueue<. ,t
becomes ready only when another thread, associated with that ob&ect gives
a call notity9<. /ll threads waiting for a given ob&ect become ready if the call
is notify/ll9<
yield9< A ,f a thread is C*7 intensive, it may prevent others to run. )o /void
this happening , the thread may call yield9< , to allow others to get a chance.
when yield9< is called the thread moves to runnable state.

E+ample CQ AA demo of thread methods
public class Set)hread.ame
8
public static void main9String args:;<
8
)hread t D )hread.current)hread9<>
System.out.println9=Main threadBs original name = ' t.get.ame9< <>
t.set.ame9=Xaint=<>
System.out.println9=Main threadBs name is now = ' t.get.ame9< <>
?
?
VE
E+ample CV A 3emo of Multiple threads
class Custom)hread e+tends )hread
8
Custom)hread9String name<
8
super9name<>
start9<>
?
public void run9<
8
try
8
for9int i D E> i N M> i''<
8
System.out.println99)hread.current)hread9<<.get.ame9<' =
thread here...=<>
)hread.sleep91EEE<>
?
?
catch 9,nterruptedE+ception e<
8
?
System.out.println99)hread.current)hread9<<.get.ame9< '= ending.=<>
?
?
public class Multi3emo
8
public static void main9String args:;<
8
Custom)hread t1 D new Custom)hread9=(irst=<>
Custom)hread t@ D new Custom)hread9=Second=<>
Custom)hread tH D new Custom)hread9=)hird=<>
try
8
for9int iD E> iN 1E> i''<
8
System.out.println99)hread.current)hread9<<.get.ame9<' = thread
here...=<>

)hread.sleep91EEE<>
V1
?
?
catch 9,nterruptedE+ception e<
8
?
?
?
output A
(irst thread here..
)hird thread here..
Second thread here..
main thread here ...
Second thread here..
(irst thread here..
.....

(irst thread ending
)hird thread ending
Second thread ending
main thread here...
main thread here...
.. . .
join9: C isAlive9: methods)

)he following program demonstrates the join9: Z isAlive9: methodsA
class 3emo/live e+tends )hread 8
int value>
public 3emo/live9String str<8
super9str<>
valueDE>
start9<>
?
public void run9<8
tr,8
%hile 9value N F<8
System.out.println9get.ame9< ' =A = ' 9value'
'<<>
/hread.sleep9@FE<>
?
? catch 9E+ception e< 8?
System.out.println9=E+it from threadA = ' get.
V@
ame9<<>
?
?
public class 3emo%oin8
public static void main9String:; args<8
3emo/live da D ne% 3emo/live9=)hread a=<>
3emo/live db D ne% 3emo/live9=)hread b=<>
tr,8
System.out.println9=$ait for the child thread
s to "nish.=<>
da.&oin9<>
if 9Jda.is/live9<<
System.out.println9=)hread / not alive.=<>
db.&oin9<>
if 9Jdb.is/live9<<
System.out.println9=)hread 6 not alive.=<>
? catch 9E+ception e< 8 ?
System.out.println9=E+it from Main )hread.=<>
?
?

E+ample IE A 3emo of other methods &oin 9 <, is/live9<
/ thread calls &oin 9< method when it must wait for another thread to
complete its tas#.
class Custom)hread e+tends )hread
8
Custom)hread9String name<
8
super9name<>
start9<>
?
public void run9<
8
try
8
for9int iD E> iN M> i''<
VH
8
System.out.println99)hread.current)hread9<<.get.ame9<'= thread
here...=<>
)hread.sleep91EEE<>
?
?
catch 9,nterruptedE+ception e< 8 ?
System.out.println99)hread.current)hread9<<.get.ame9< ' ending.=<>

?
?
public class 3emoalive
8
public static void main9String args:;<
8
Custom)hread t1 D new Custom)hread9="rst=<>
Custom)hread t@ D new Custom)hread9=second=<>
Custom)hread tH D new Custom)hread9=third=<>
System.out.println9=(irst is aliveW A ='t1.is/live9<<>
System.out.println9=Second aliveWA= ' t@.is/live9<<>
System.out.println9=)hird aliveWA= ' tH.is/live9<<>
LR t1,t@,tH are child threads of main and to be terminated
before main terminates RL
try
8
t1.&oin9<>
t@.&oin9<>
tH.&oin9<>
?
catch 9,nterruptedE+ception e< 8 ?
System.out.println9="rst aliveW=' t1.is/live9<<>
System.out.println9=Second alivW= ' t@.is/live9<<>
System.out.println9=)hird aliveW= ' tH.is/live9<<>
?
?
output A
(irst thread here..
)hird thread here..
(irst aliveW true
Second thread here..
VM
. . . .
(irst ending
Second ending
)hird ending
(irst aliveW false
Second aliveW false
third aliveW false
/hread priorit, ))
$hen a new thread is created its priority is e2ual to the creating thread
priority. Every &ava thread has a priority between 1 and 1E and by deafult
each thread is given a normal priority F. )he constants de"ned in the thread
class are

)hread.M,.O*R,-R,)T 1
)hread.M/]O*R,-R,)T 1E
)hread..-RMO*R-R,)T F

)he methods set*riority9<, get*riority9< can be used to handle priority. )his
priority is used by the scheduler to allocate C*7 time.
Some &ava systems support time slicing. ,t it is available then the sheduler
ensures that several threads of e2ual priority get e+ecuted for a 2uantum
time in a round robin fashion. 5ow priority thread never runs as long as there
is a runnable high priority thread.
)he scheduling is also preemptive. )hat is higher thread, preempts the
lower one.
E+ample I1 A 3emo of priority
class Counter implements Runnable
8
)hread t>
int c D E>
boolean go4ag>
public Counter9int p<
8
t D new )hread9this<>
t.set*riority9p<>
?
VF
public void start9<
8
go4ag D true>
t.start9<>
?
public void run9<
8
while 9go4ag<
c''>
?
public void end9<
8
go4ag D false>
?
?
public class *riority3emo
8
public static void main9String args:;<
8
Counter t1 D new Counter9)hread..-RMO*R,-R,)T ' @<>
Counter t@ D new Counter9)hread..-RMO*R,-R,)T ' 1<>
Counter tH D new Counter9)hread..-RMO*R,-R,)T - 1<>
t1.start9<>
t@.start9<>
tH.start9<>

try 8
)hread.sleep9FEEE<>
?
catch 9,nterruptedE+ception e< 8 ?
t1.end9<>
t@.end9<>
tH.end9<>
System.out.println9=)hread 1 countedA = ' t1.c<>
System.out.println9=)hread @ countedA = ' t@.c<>
System.out.println9=)hread H countedA = ' tH.c<>

?
?
VC
output A
thread 1 counted 1QC11E@EHH
thread @ counted 1IMVQCV@VH
thread H counted @VFCF@@C
S,nchroni0ation ))
$hen more than one thread has to use a shared resource, &ava "nds a way
of ensuring that only one thread uses the resource at one point of time, and
this is called synchroniPation.

%ava uses the concept called monitors9Semaphores<. Monitor refers to
portion of the code in a program related to a resource or data that can be
occupied by only one thread at a time. Such
a region is also called critical section.
)he monitor holds an e+clusive loc#, that can be owned by only one ob&ect
at a time. ,t allows only one thread to e+ecute a synchroniPed method. $hen
the e+ecution is done, the loc# on the ob&ect is opened, and the monitor
alows the highest priority thread as#ing for it, to proceed.
$hen a thread calls , a non static sync method, the thread ac2uires a loc#
on that ob&ect. )he other threads calling the method enters into a wait state.
,f a thread calls a static sync method, other threads are free to call non static
sync methods on the same ob&ect.

VI
S,nchroni0ed methods ))
Methods can be synchroniPed using the following synta+
modifer synchroniPed rettype name9 parameters <
8
?
.+ample 24 )) Demo %h, s,nchroni0ation #
class Shared
8
void do$or#9String s<
8
System.out.println9=Starting = ' s<>
try 8
)hread.sleep99long< 9Math.random9< R FEE<<>
?
catch 9,nterruptedE+ception e< 8 ?
System.out.println9=Ending = ' s<>
?
?

class Custom)hread e+tends )hread
8
Shared sh>
public Custom)hread9Shared sh, String s<
8
super9s<>
this.sh D sh>
start9<>
?
public void run9<
8
sh.do$or#9)hread.current)hread9<.get.ame9<<>
?
?
public class Synch3emo
8
public static void main9String args:;<
VQ
8
Shared sh1 D new Shared9<>
Custom)hread t1 D new Custom)hread9sh1, =one=<>
Custom)hread t@ D new Custom)hread9sh1, =two=<>
Custom)hread tH D new Custom)hread9sh1, =three=<>
try 8
t1.&oin9<>
t@.&oin9<>
tH.&oin9<>
?
catch9,nterruptedE+ception e< 8 ?
?
?
output A Starting one
starting three
starting two
ending three
ending two
endig one
.+ample 2= ) Demo of s,nchroni0ed methods
class Shared
8
synchroniPed void do$or#9String s<
8
System.out.println9=Starting = ' s<>
try 8
)hread.sleep99long< 9Math.random9< R FEE<<>
?
catch 9,nterruptedE+ception e< 8 ?
System.out.println9=Ending = ' s<>
?
?

class Custom)hread e+tends )hread
8
Shared sh>
VV
public Custom)hread9Shared sh, String s<
8
super9s<>
this.sh D sh>
start9<>
?
public void run9<
8
sh.do$or#9)hread.current)hread9<.get.ame9<<>
?
?
public class Synch3emo1
8
public static void main9String args:;<
8
Shared sh1 D new Shared9<>
Custom)hread t1 D new Custom)hread9sh1, =one=<>
Custom)hread t@ D new Custom)hread9sh1, =two=<>
Custom)hread tH D new Custom)hread9sh1, =three=<>
try 8
t1.&oin9<>
t@.&oin9<>
tH.&oin9<>
?
catch9,nterruptedE+ception e< 8 ?
?
?
output Starting one
ending one
starting two
ending two
starting three
ending three
1EE
/ sub class can override a sync method of its super class )he overriden
method need not be sync.
,f a non sync method of an ob&ect uses the super9 < to call a sync method
of its parent class, the ob&ect is bloc#ed until the invocation is complete.

S,chroni0ed statements ))

/ part of the code can be placed under a monitor using the synta+ shown
below.
synchroniPed N ob&ect G N statements G

.+ample 2> ) Demo of s,nchroni0ation code boc8s 9statements:

class Shared
8
void do$or#9String s<
8
System.out.println9=Starting = ' s<>
try 8
)hread.sleep99long< 9Math.random9< R FEE<<>
?
catch 9,nterruptedE+ception e< 8 ?
System.out.println9=Ending = ' s<>
?
?

class Custom)hread e+tends )hread
8
Shared sh>
public Custom)hread9Shared sh, String s<
8
super9s<>
this.sh D sh>
start9<>
?
public void run9<
8
1E1
synchroniPed 9sh<
8
sh.do$or#9)hread.current)hread9<.get.ame9<<>
?
?
?
public class Synch3emo@
8
public static void main9String args:;<
8
Shared sh1 D new Shared9<>
Custom)hread t1 D new Custom)hread9sh1, =one=<>
Custom)hread t@ D new Custom)hread9sh1, =two=<>
Custom)hread tH D new Custom)hread9sh1, =three=<>
try 8
t1.&oin9<>
t@.&oin9<>
tH.&oin9<>
?
catch9,nterruptedE+ception e< 8 ?
?
?
outputA Starting one
ending one
starting two
ending two
starting three
endig three
Dead loc8s ))
$hen two or more threads are waiting for loc#s to be freed , and the loc#s
will never be freed. (or e+ample one thread of / tries to access the sync
method of 6, and 6 tries to access the sync of / then they will enter into
3eadloc# situation.
,t occurs if the programmer is not carefull while writing the sync methods.
3eamon )hreads AA
1E@
,t is a thread that runs only to serve other threads. ,t runs in the
bac#ground, when C*7 time is available. (or E+ in &ava garbage collector is
deamon thread.
/ thread can be made a deamon, by calling set3eamon9true< method. )o
"nd whether a thread is deamon or not is3eamon9< method can be used. /
deamon can create only a 3eamon thread.
Communication among )hreadsAA 9inter thread comm<
,t is achieved by using the -b&ect class methods such as wait9<, notify9<,
notify/ll9<. )hey are "nal methods of ob&ect class and can be called only
within a sync code

.+ample 2? ) demo of inter thread communication
class [ueue
8
int n>
synchroniPed int get9 <
8
system.out.println9= got A = ' n<>
return n>
?
synchroniPed void put9 int n <
8
this.n D n>
system.out.println9= put A= ' n<>
?
?
class *roducer implements Runnable
8
[ueue 2>
*roducer9 2ueue 2<
8
this.2 D 2>
new )hread9this,=producer=<.start9<>
?
public void run9 <
8
1EH
int i D E>
while 9i N 1E <
8
2.put9i''<>
?
?
?
class Consumer implements Runnable
8
[ueue 2>
consumer9 2ueue 2<
8
this.2 D 2>
new )hread9this,=consumer=<.start9<>
?
public void run9 <
8
int # D E>
while 9# N 1E <
8
2.get9<>
#''>
?
?
?
public class 3emocomm
8
public static void main9 String args:;<
8
[ueue sample D new [ueue9 <>
*roducer p D new *roducer9sample<>
consumer c D new consumer9sample<>
system.out.println9=3one=<>
?
?
output AA
put A E Xot A E *ut A 1 Xot A 1 put A @ Xot A @
put A H Xot A H *ut A M Xot A M put A F Xot A F
put A C Xot A C *ut A I Xot A I Xot A I Xot A I
put A Q put A V Xot A V
1EM
.ot corect result. /fter producer put I, the consumer started and got the
same I three times in a row. )hen producer resumed and puts Q, V
simultaneously and consumer consumes V
E+ample IE A inter thread communication - correct results
class [ueue
8
boolean 4ag D true>
int n>
synchroniPed int get9 <
8
if 9 J4ag<
8
system.out.println9= got A = ' n<>
notify9 <>
?
else
8
try
8
wait9 <>
?
catch 9 E+ception e< 8 ?
?
return n>
?
synchroniPed void put9 int n <
8
if 94ag<
8
this.n D n>
system.out.println9= put A = ' n<>
4ag D false>
notify9 <>
?
else
8
try
8
wait9 <>
?
catch 9 E+ception e< 8 ?
?

1EF
?
?
class *roducer implements Runnable
8
[ueue 2>
*roducer9 2ueue 2<
8
this.2 D 2>
new )hread9this,=producer=<.start9<>
?
public void run9 <
8
int i D E>
while 9i N 1E <
8
2.put9i''<>
?
?
?
class Consumer implements Runnable
8
[ueue 2>
consumer9 2ueue 2<
8
this.2 D 2>
new )hread9this,=consumer=<.start9<>
?
public void run9 <
8
int # D E>
while 9# N 1E <
8
2.get9<>
#''>
?
?
?
1EC
public class 3emocomm
8
public static void main9 String args:;<
8
[ueue sample D new [ueue9 <>
*roducer p D new *roducer9sample<>
consumer c D new consumer9sample<>
system.out.println9=3one=<>
?
?
output A
put A E Xot A E *ut A 1 Xot A 1 put A @ Xot A @
put A H Xot A H *ut A M Xot A M put A F Xot A F
put A C Xot A C *ut A I Xot A I put A I Xot A I
put A Q Xot A Q put A V Xot A V
S,nchroni0in' classes ))

Semaphore, Cyclic6arrier, Count3own5atch, E+changer are all classes
added to &ava to act as synchroniPers. Each of them have methods that the
threads may call.
Concurrent pro'rammin' ))

$hile writing multithreaded programs, some of the issues that may
create diUculties are
1. .o way to bac# oU from an attempt to ac2uire a loc# that is already
held or give up after waiting for a speci"ed time, or cancel a loc# attempt
after an interrupt.
@. Sync is done in bloc# structured fashion. .o way to ac2uire loc# in one
method and release it in another.
)hre are some drawbac#s in wait9<, notify9< and they are enhanced with
new mechanisms, and placed as a part of &ava.util.concurrent pac#age. )his
pac#age provide all the standard concurrency utilities. using this pac#age,
helps scalable, easy to write and maintainableapplication developement but
programmer is responsible to see that the applications a re free from
deadloc#, C*7 starvation.
1EI
Chapter 3
Pac8a'es
,t is a mechanism for grouping classes, interfaces and sub pac#ages. )he
&ava /*, itself is implemeted as a group of pac#ages.

1. )o organiPe the classes into groups and units
@. )o reduce problems with con4icts in names
H. )o provide protection to members and methods
M. )o identify classes.
Pac8a'e cate'ories in Java
%ava supports two types of pac8a'es as shown below in the hierarchy structureA
AuildBIn Pac8a'es in Core Java)
%ava pac#ages can be categoriPed in the hierarchy structure shown asA
*ac#ages in the %ava language begin with 7java7 or 7java+7 as we can found in both
hierarchy structure shown above. .ote that, the pac#age =&ava= also has
subpac#ages in which the pac#age 7a%t7 is further has a subpac#age called
7event7 that is imported to access classes and interfaces to handle the events "red
on the awt-component in a program.
1EQ
%ava has a hierarchial naming convention for pac#ages, #nown as dot 9 .<
notation.
(or E+, the %3\ has a pac#age called &ava at top level, and the ne+t level
includes names such as lang, io, awt, util etc
)he dot re4ects in the directory organiPation. Each level represents a
smaller and more speci"c grouping of classes.
/ccessing classes in a pac#ageAA

)wo ways 1. import statement
@. 7se fully 2uali"ed approach 9 no import needed<
E+ A 1 import pac#agename.R>
import pac#agename.classname>
or
@ &ava.awt.(ont f D new &ava.awt.(ont9 <>
/< )he import, imports all public classes in the pac#age, but not from sub
pac#ages. )o do that e+plicite import of each sub pac#age is needed.
6< import line comes after pac#age de"nition line.
C< )o resolve name con4icts of a class from more than one pac#age, use
full pac# name while 2ualifying the ob&ect
E+ A &ava.util.3ate d1 D new &ava.util.3ate9<>
&ava.s2l.3ate d@ D new &ava.s2l.3ate9<>
Create Kour O%n Pac8a'e
)he pac#age to which the source "le belongs is speci"ed with the #eyword pac8a'e
at the top left of the source "le, before the code that de"nes the real classes in the
pac#age.
Suppose we have a source "le called 7$ello!orld(java7 and we want to put this
"le in a pac#age 7m,pac8a'e7 then the following code is written as shown in the
given e+ampleA
pac8a'e mypac#age>
class 0ello$orld 8
public static void main 9Stri
ng args:;< 8
System.out.println9=0ello $o
rldJ=<>
?
?
1EV
6efore running this program ma#e sure to do the following thingsA
1. Create a directory 7m,pac8a'e7 .
@. Save the source "le as 7$ello!orld(java7 in the created directory.
H. Set the class path as set C5ASSPA/$ N (D C)*D
M. Xo to the 7m,pac8a'e7 directory and compile the program as
C)*m,pac8a'eOjavac
$ello!orld(java
F. Run the program.
,f you try to run this program, you will get the following e+ceptions 9or error<A
CAYmypac#ageG&ava 0ello$orld
E+ception in thread =main=
&ava.lang..oClass3ef(oundErrorA 0ello$orld 9wrong nameA
mypac#ageL0ello$orld<
at &ava.lang.Class5oader.de"neClass19.ative Method<
at &ava.lang.Class5oader.de"neClass97n#nown Source<
at &ava.security.SecureClass5oader.de"neClass97n#nown
Source<
at &ava.net.7R5Class5oader.de"neClass97n#nown Source<
at &ava.net.7R5Class5oader.access^EEE97n#nown Source<

)his is, because the class =$ello!orld7 belongs to the pac#age 7m,pac8a'e7. So
,f we want to run it, we have to tell the %VM about its full,BGuali@ed class name
as 9mypac#age.0ello$orld< instead of its plain class name 90ello$orld<. &ull,B
Guali@ed class name is the name of the &ava class that includes its pac#age
name.
o% run the pro'ram as sho%n)
CAYmypac#ageG&ava
mypac#age(0ello$orld
0ello $orldJ
/he %a,s to Compile the Pac8a'e)
Compile in the same director,) ,f you have a hierarchy of pac#ages to
compilation then you can compile the pac#age without going to the subdirectories
and specifying the complete directory path with the class . Suppose, you have a
hierarchy of pac#ages as =india(m,compan,(mainpac8a'e(m,pac8a'e7
including the class 7$ello!orld7 then type the following command shown asA
CAY&avac
CAYindiaYmycompanyYmainpac#ageYmypac#ageY0ell
o$ord(&ava

11E
)his command will reach to the last subdirectory and compile the class
7$ello!orld7(
Compile into the Di-erent Director,) -n the other hand, if you want to compile
the same pac#age available in the hierarchy manner to another directory 9location<
then synta+ is shown asA
C)*javac Bd Ptar'etQdirector,O
PcompleteQdirector,pathO
Suppose, you want to save the compiled pac#age to the location 7D)*m,folder7
then type the following command shown asA
CAY&avac Bd 3AYmyfolder CAY
indiaYmycompanyYmainpac#ageYmypac#ageY0ello$ord(&a
va
)his command puts the folder 7india7 along with its subfolders and the class "le
7$ello!orld(class7 to the new location as D)*m,folder.
$o% to import a pac8a'e
)here are two ways so that you can use the public classes stored in pac#age.
3eclaring the fully-2uali"ed class name. (or e+ample,
mypac#age.0ello$orld helloworld D ne%
mypac#age.0ello$orld9<>
7sing an 7import7 #eywordA (or e+ample,
import %orld(RD LL we can call any public
classes inside the m,pac8a'e pac#age
5ets see an e+ample importing the created pac#age into the another program "le.
pac8a'e importpac#age>
public class 0ello$orld 8
public void show9<8
System.out.println9=)his is the function of the class
0ello$orldJJ=<>
?
?
,n this program the pac#age =importpac8a'e7 is created under the 7c)*nisha7
directory that will be imported into another program "le to call the function of the
class 7$ello!orld7.
111
.ow ma#e a program "le named 7CallPac8a'e7 under the =c)*nisha7 directory
importing the pac#age 7importpac8a'e7.

import importpac#age.R>
class Call*ac#age8
public static void main9String:; args<8
0ello$orld h@Dne% 0ello$orld9<>
h@.show9<>
?
?
Out of the pro'ram)
C:\nisha\importpackage>javac
*.java
C:\nisha\importpackage>cd..
C:\nisha>javac CallPackage.java
C:\nisha>java CallPackage
This is the function of the class
ello!orld""
Ma#e sure to the directory structure for this program shown asA
Create Subpac#ages 9i.e. / *ac#age inside another pac#age<
$e can also put a pac#age inside an another pac#age. )he pac#ages that comes
lower in the naming hierarchy are called =subpac#age= of the corresponding
pac#age higher in the hierarchy i.e. the pac#age that we are putting into another
pac#age is called =subpac8a'e7( )he naming convention de"nes how to create a
uni2ue pac#age name, so that pac#ages that are widely used with uni2ue
namespaces. )his allows pac#ages to be easily managed. Suppose we have a "le
called =0ello$orld.&ava=. and want to store it in a subpac#age 7subpac8a'e7,
which stays inside pac#age 7importpac8a'e7. )he =0ello$orld= class should loo#
something li#e thisA
11@
pac8a'e importpac#age.subpac#age>
public class 0ello$orld 8
public void show9<8
System.out.println9=)his is the function of the class
0ello$orldJJ=<>
?
?
.ow import the pac#age 7subpac8a'e7 in the class "le 7CallPac8a'e7 shown asA

import importpac#age.subpac#age.R>
class Call*ac#age8
public static void main9String:; args<8
0ello$orld h@Dne% 0ello$orld9<>
h@.show9<>
?
?
Out of the pro'ram)
CAYnishaG&avac
CAYnishaYimportpac#ageYsubpac#ageY0ello
$orld.&ava
CAYnishaYimportpac#ageYsubpac#ageGcd..
CAYnishaYimportpac#ageGcd..
CAYnishaG&avac Call*ac#age.&ava
CAYnishaG&ava Call*ac#age
)his is the function of the class
0ello$orldJJ
Ma#e sure to the directory structure for this program shown asA
E+ample IC A 3emo of pac#ages
11H
LL Student.&ava "le in a subdirectory college

pac#age college>
public class Student
8
String rno, name>
public void setStudent9String rno,String name<
8
this.rno D rno> this.nameD name>
?
public void dispStudent9 <
8
System.out.println9=.ame A= ' name<>
System.out.println9=Rno A= ' rno<>
?
?
E+ample II A 3emo of pac#ages
LL )eacher.&ava "le in the same subdir college

pac#age college>
public class )eacher
8
String name, 2ual>
public void set)eacher9String name,String [ual<
8
this.name D name> this.2ualD 2ual>
?
public void disp)eacher9 <
8
System.out.println9=.ame A= ' name<>
System.out.println9=[ual A= ' 2ual<>
?
?

E+ample IQ A 3emo of pac#ages
LR )estpac#.&ava "le store in any directory under which
11M
*ac#age college was a subdirectory RL
import college.R>
public class )estpac#
8
public static void main9String args:;<
8
Student s D new Student9<>
)eacher t D new )eacher9<>
s.setStudent9=*reethi=, =R1EE1I=<>
t.set)eacher9=*ush#al=, =*h.3=<>
s.dispStudent9<>
t.disp)eacher9<>
?
?
3uring the compile time, when an ob&ect is encountered, for its class
de"nition the compiler loo#s at all imported pac#ages and if "nds, it
proceeds further with out including any code.
3uring run time, the interpretor calls a class loader, and this loader loads
the corresponding class.

Chapter ;
Java Applets
!!!))
11F
)he $$$ is a collection of electronic documents that are lin#ed together.
)hese documents are #nown as web pages and a collection of related web
pages is #nown as web site.
/ web site resides on a server computer that are located around the world
and the information on the $$$ is always accessible.
!eb Aro%ser)
$eb browser is a program that is used to access $$$. ,t allows the users
to view the web pages and to navigate betwen them. )hey are also called
universal clients as they are common to the clients for all web based
applications
!eb Server )
,t is a server program running on a computer whose purpose is to serve web
pages to the other computers when re2uested.
E+ A /pache , ,,S, i*lanet
$/M5 )
,t is a mar#up language 7sed to create documents on $$$. ,t gives
guidelines for displaying information through tags. )ags are enclosed within
angular brac#ets N G.
FR5 )
,t is a uni2ue address used to identify each web page or a resource on the
internet. ,t indicates where the page is stored on the net. ,t is called the
internet address of a resource on the $$$. /long with the protocol to
access. )hey are used by browser to connect to a speci"c server and to get
a speci"c document or page.
E+ A httpALLwww.infosys.comLinde+.html
protocolALLServer3omain.ameL*ath name
protocolALLip addressL*ath .ame

)he 7R5 may contain port to connect to, and also the data typed by the user
in the form to be submitted to the application
E+A httpALLeshopAQEQELshoppingLSend3ataWname D prasadZphone D @FCIQ
$//P )
$eb browsers and web servers communicate with each other using 0))*
protocol. ,t is a simple protocol, stateless and allows clients to communicate
with server. ,t is an application level protocol and transmit any resources
identi"ed by a 7R5. ,t is called re2uestLresponce based protocol, because
the clients sends a re2uest to a server, and the server listen and respond
bac#.
11C
0))* 1.E was the original version. )he client would initiate and close the
connection to the server on each re2uest. )he performance is poor because
it has to ma#e new )C*L,p connection for every re2uest.
(or e+ample if a page inde+.html is accessed by the client and the page
contain 1E image "les in its body, the browser has to initiate and close the
connection 11 times. )he client has to open a new )C*L,* connection and
places a re2uest for the resource, and on receipt close the connection and
repeat it for each picture to be downloaded.
0))* 1.1 latest version, and here the connection once established is
maintained until the browser is closed. ,t is called persistent connection. So
many re2uests can occur within a single )C*L,* connection.
APP5./S
)hey are small &ava programs used in internet computing. )hey can display
graphics, play sounds, accept user inputs, create animation perform
arithmetic operations and enable creation of interactive web documents.
/pplets are used when we need something dynamic to be included in a web
page. )hey are event driven window based &ava programs.
1. /pplets do not use function main9<
@. )hey run inside a web page.
H. )hey can not read or write any "les in the local system
M. )hey can not run any programs in the local system
F. )hey are restricted from using libraries of other languages.
C. )hey can not communicate with any site other than the one
that served the web page.
/pplets are e+ecuted in a web browser, or in a special window called
=/ppletviewer= provied by the %3\. 6rowsers allow many applets in a single
page where as appletviewer show them in seperate windows.
11I
/pplet class AA
,t provide the foundation for creating applets and it is subclassed as shown
below.
&ava.lang.-b&ect
_
&ava.awt.Component
_
&ava.awt.Container
_
&ava.awt.*anel
_
&ava.applet./pplet
Methods of /pplet class
void init9< A
void start9< A
void stop9< A
void destroy9< A
void paint9< A
7R5 getCode6ase9< A
7R5 get3ocument6ase9<A
,mage get,mage9< A

/ppletconte+t get/ppletConte+t9< A

-nce an /ppletBs =.class= "le is created it is uploaded to an ,S* or viewed on
the local machine, by setting its protection for read.
init9< A
,t is called when the applet is loaded or reloaded for the "rst time into a
browser. ,t is called only once in the life cycle. )he browser calls this method
after the constructor of the applet is called.
6ut most of the initiliPation is done in the init9< such as creating helper
ob&ects, seting up fonts, images , reading and parsing parameters.
11Q
start9< A
,t is called after the init9< is completed. ,t is also called whenever the user
leaves a page and returns bac#. ,t is called when you minimiPe and then
ma+imiPe a page.
7nli#e init9< it can happen many times through the life cycle.
stop9< A
,t runs when the user leaves the current web page. 6y default, when the user
leaves the web page, or a window minimiPed, any threads the applet had
started will continue running. 6y using this method we can suspend such
threads, and restart them when the applet is viewed again.

destroy9< A
,t is called to terminate the applet. ,t runs either before the applet e+its or
before the browser e+its. ,t is usefull for cleanup operations such as releasing
memory after the applet is removed, #illing threads, closing
networ#,database connections or releasing all resources that were initialiPed
during an applets initialiPation.

*aint9< A
)he paint9< is used by applet to draw something to the screen. ,t can be
called several times in the life cycle of an applet. ,t is a method inherited
from Component class. ,t ta#es one parameter of type Xraphics class. $hen
paint9< is called, an instance of Xraphics class is created by the browser and
handed over to the applet.
,t gets e+ecuted every time the
1 applet is minimiPed, or ma+imiPed, or

@ when the applet is initialiPed and the browser is placed
behind another window on the screen and then brought
forward again.

H 6rowser window is moved to a diUerent position on screen.
E+ample Q1 AA
import &ava.applet./pplet>
11V
import &ava.awt.R>
public class /ppe+ e+tends /pplet
8
public void paint9Xraphics g<
8
g.drawString9=0ello from %avaJ=, CE, 1EE<>
?
?
/estin' Applets )

)here are two ways.
1. 7sing /pplet tags in 0)M5 pages and then view the applet through
browser window by downloading web page.

@. 7sing /pplet tags in source code as comments to view the the applet
with applet viewer.

Runnin' in bro%ser %indo%)

N htmlG
NheadG NtitleG (irst /pplet NLtitleGNLheadG
NbodyG
Napplet code D =/ppe+= width D @EE height D @EEG
NLappletG
NLbodyG
NLhtmlG
to run the applet save the above html "le as a webpage and then open it
through any browser.
1@E
Runnin' usin' Appletvie%er )

cAYG appletviewer /ppe+

/he s,nta+ of an applet ta'
N appletG

:codebase D url6ase;
code D class"le
width D pi+els
height D pi+els
:name D applet instance .ame;
........
:param name D para.ame value D =paramvalue=;
NLappletG
code6ase A ,t specify the directory which is to be searched for the
applets .class "le. .ormally the directory of the 0)Ml "le is searched for
the .class "le. )his will be in the form of a 7R5. 6ut applets =.class= "le need
not be in the same host where 0)M5 "le is loaded.
E+ A Codebase D httpALLwww.au.ac.in
)hen 0)M5 "le can be anywhere but =.class=, "le is searched from
the above 7R5.
getCode6ase9<, get3ocument6ase9< can give the directory of applet
codes =.class= "le, and 0)M5 document "les.
code A ,t refers to the name of applets, =.class= "le. ,t is relative to the
base 7R5 but not absolute 7R5
.ame A ,t referes to the name of the applets instance ,t is used by
applets to communicate with each other on the same 0)M5 page. the
method get/pplet9< de"ned under /ppletConte+t interface can be used to
get the instance name.

width, height A )hey refer to the siPe of panel in the browser window.
param A ,t specify name ,value pairs. )he value can be obtained using
get*arameter9< method.
E+ample Q@ AA 3emo of life cycle
1@1
import &ava.applet.R>
import &ava.awt.R>
LR N/**5E) C-3ED/ppe+.class $,3)0D@EE 0E,X0)D@EE G NL/**5E)G
RL
public class /ppe+ e+tends /pplet
8

String msg D = =>
public void init9<
8
set6ac#ground9Color.blue<>
msg D msg'=init9< A =>
?
public void start9<
8
msg D msg'=start9< A =>
?

public void stop9<
8
msg D msg'=stop9< A =>
?
public void destroy9<
8
msg D msg'=destroy9< A =>
?
public void paint9Xraphics g<
8
msg D msg'=paint9< A =>
g.drawString9msg,CE,1EE<>
?
?
E+ample QH AA 3emo of passing parameters
import &ava.applet.R>
import &ava.awt.R>
LR N/**5E) C-3ED/ppe+.class $,3)0D@EE 0E,X0)D@EE G
1@@
N*/R/M ./ME D msg V/57E D =%ava is simpleJ=G
NL/**5E)G RL
public class /ppe+ e+tends /pplet
8
public void paint9Xraphics g<
8
g.drawString9get*arameter9=msg=<, CE, 1EE<>
?
?
E+ample QM AA 3emo of Console ,-
import &ava.applet.R>
import &ava.awt.R>
public class /ppe+ e+tends /pplet
8
public void paint9Xraphics g<
8
g.drawString9=0ello from %avaJ=, CE, 1EE<>
System.out.println9=0ello from %avaJ=<>
?
?
E+ample QF AA 3emo of codebase, docbase methods

LR Napplet codeD=3bases= widthDHEE heightDFEG
NLappletG RL
public class 3bases e+tends /pplet
8

public void paint9Xraphics g<
8
String msg>
7R5 u D getCode6ase9<> LL get code base
msg D =Code baseA = ' u.toString9<>
g.drawString9msg, 1E, @E<>
u D get3ocument6ase9<> LL get document base
msg D =3ocument baseA = ' u.toString9<>
1@H
g.drawString9msg, 1E, ME<>
?
?
E+ample QC AA 3emo of image loading
steps A
create an image ob&ect
associate a graphics "le with the image ob&ect
display the image
import &ava.applet.R>
import &ava.awt.R>
public class /ppe+ e+tends /pplet
8
public void init9<
8
,mage p>
p D get,mage9getCode6ase9<,=imagesLrunning.gif=<>
?
public void paint9Xraphics g<
8
g.draw,mage9p,E,E,1EE,1EE,this<>
?
?
get,mage9< ta#es two parameters. / base 7R5, and a string giving the path
or "lename in relation to 7R5.
E+ample QI AA 3emo of /udio clip
import &ava.applet.R>
import &ava.awt.R>
public class /ppe+ e+tends /pplet
8
public void init9<
8
/udioClip p>
p D get/udioClip9getCode6ase9<,=songsL&ana.audio=<>
?
public void paint9Xraphics g<
8
1@M
p.loop9<>
?
?
E+ample QQ A3emo of /udio Clip
import &ava.applet.R>
import &ava.awt.R>
import &ava.net.R>
LR Napplet code D =Sound3emo= width D HEE height D HEEG
Nparam name D sname value D ="leAYYcAY&ana.au=G
NLappletG RL

public class Sound3emo e+tends /pplet
8

String sf>
/udioClip ac>
7R5 u D null>
String msg D = =>
public void init9<
8
sf D get*arameter9=sname=<>
?
public void start9<
8
if sf JD null
8
try
8
u D new 7R59sf<>
?
catch9Malformed7R5E+ception e<
8
msg D =malformed 7R5 string =>
?
ac D get/udioClip9u<>
?
?

public void paint9Xraphics g<
8
1@F
g.drawString9=playing= ,1E,FE<>
ac.loop9<>
g.drawString9msg,1E,1EE<>
?
?

/ppletConte+t interface A
,t can be used to get information from the applets e+ecution env. $ith in
an applet once the conte+t is obtained, we can bring other documents into
view by show3ocument9< method.
getCode6ase9<, get3ocument6ase9< can be used to get 7R5 ob&ects of
applets byte code, 0)M5 "les.
E+ample QV A Communication with a browser A
)he e+ample below is an applet which re2uest the browser to how another
web page. )he Show3emo.&ava, applet will instruct the browser to display
the Samppage.html. (or testing we have a html page by name
showtest.html which can be viewed by internet e+plorer.
/. showtest.html
N htmlG
NheadG NtitleG /ction page NLtitleGNLheadG
NbodyG
Napplet code D =Show3emo= width D HEE height D HEEG
Nparam name D dname value D ="leAYYcAYSamppage.html=G
NLappletG
NLbodyG
NLhtmlG
6. Show3emo.&ava
import &ava.applet.R>
import &ava.awt.R>
import &ava.net.R>
public class Show3emo e+tends /pplet
8

String doc>
1@C
/ppletConte+t ac>
7R5 u D null>
String msg D = =>
public void init9<
8
ac D get/ppletConte+t9<>
doc D get*arameter9=dname=<>
?
public void start9<
8
if doc JD null
8
try
8
u D new 7R59doc<>
?
catch9Malformed7R5E+ception e<
8
msg D =malformed 7R5 string =>
?
ac.show3ocument9 u, =new$indow=<>
?
?

public void paint9Xraphics g<
8
g.drawString9=Communicating= ,1E,FE<>
g.drawString9msg,1E,1EE<>
?
?

C. Samppage.html A
N htmlG
NheadG NtitleG 3isplaying new page NLtitleGNLheadG
NbodyG
)his is to demonstrate applets power to show
other documents
NLbodyG
NLhtmlG
E+ample VE AA
1@I
LR Napplet codeD=statusdemo.class= widthD@EE height D@EEG
NLappletG RL
import &ava.applet.R>
import &ava.awt.R>
public class statusdemo e+tends /pplet
8
public void init9<
8
set6ac#ground9Color.pin#<>
?
public void paint9Xraphics g<
8
g.drawString9= te+t in applet window = ,1E,@E<>
showStatus9=,t shows te+t in a seperate status window=<>
?
?
E+ample V1 A ,mage display- threads
LR Napplet codeD,mage/pplet widthDHEE heightD@EEG
NLappletG RL
import &ava.awt.R>
import &ava.applet.R>
public class ,mage/pplet e+tends /pplet implements Runnable
8
,mage img>
boolean drawn D false> LL determines whether to draw
)hread t>
public void init9<
8
img D get,mage9getCode6ase9<,=),*S.gif=<>
t D new )hread9this<>
t.start9<>
?
public void run9<
8
while 9true< LL in"nite loop
8
try
1@Q
8
)hread.sleep9FEE<> LL wait for half second
repaint9 <> LL ,t invo#es paint9<
?
catch9E+ception e< 8 ?
?
?
public void paint9Xraphics g<
8
LL draw image if image is not alredy drawn otherwise do nothing
LL also toggle drawn 4ag
if 9drawn<
8
drawn D false>
?
else
8
g.draw,mage9img, @E,@E,this<>
drawn D true>
?
?
?
1@V
Chapter 1<
Abstarct !indo% /ool8it
)he %(C provides two framewor#s for building X7, based applications.
)hey are 1. /$) @. S$,.XS
)he /$) has a set of classes that provide user interface elements such as
window, menu, button,list, etc. and controls for colors, and fonts.
A!/ $ierarch, ))
Component
_
Container
_
OOOOOOOOOOOOO
_ _
*anel $indow
O_OOOOOO
_ _ _
/pplet 3ialog (rame
Some #ey elements re2uired to create a X7, are
ComponentAA
Component is an abstract class. ,t provide support for managing events,
drawing of components, handling #eyboard and mouse inputs, positioning
,siPing windows and painting output.
,t is responsible for remembering the current foreground and bac#ground
colors and font. Methods commonly used are AA
add9 <
add]++5istener9<
remove]++5istener
repaint9<
setVisible9<
setSiPe9<
ContainerAA
1HE
,t has additional methods, and allow other components, or container to be
nested within it. / container is responsible for laying the position of
components by using layout managers.
commonly used methods are A
remove9<
set5ayout9<
!indo%)
)he window class creates a top-level window. / top-level window is not
contained within any other ob&ects> ,t sits directly on the des#top. Xenerally,
you wonBt create $indow ob&ects directly. ,nstead, its
subclass (rame or dialog are used to have window creation.
methods commonly used are A

show9<
hide9<
add$indow5istener9 <

&rame)
(rame is a subclass of $indow and has a title bar, menu bar, borders and
resiPing corners.
methods AA setSiPe9 <
set)itle9 <

3ialog AA
)hey are the pop up windows which can accept input from the user. )hey are
two types
1. Modal @. Modeless
*anelAA
,t is subclass of Container. ,t adds no new methods but simply implements
container. *anel is the super class of /pplets. $hen screen output is directed
to an applet, it is drawn on the surface of a *anel ob&ect. / *anel is a window
that does not contain a title bar, menu bar or border. ,t can not be a top
level window. 9 $hen you run an applet using an applet viewer, the applet
viewer provides the title and border <.
1H1
.vent $andlers )
/n event is generated when an action occurs such as mouse clic# on a
button, or enter #ey pressed on a te+t "eld. )hey are handled by listener
classes which implement listener interfaces.
Canvas AA
,t is a blan# window but not a part of /pplet or (rame. ,t is a drawing
surface used for drawing images and graphics operations.

/6S)R/C) $,.3-$,.X )--5\,) - 7, components
5abel AA / te+t string to label other components
6utton AA / simple push button.
Canvas AA / base class for creating your own controls.
Chec#bo+ AA / combination of chec# bo+ and radio buttons.
Choice AA / drop-down list control.
5ist AA / list bo+.
Menu AA / drop-down menu from the windowBs toolbar.
*anel AA /n area where we group controls, paint images or graphics.
ScrollbarAA 0oriPontal and vertical scroll bars.
)e+t(ieldAA / single-line te+t entry "eld.
)e+t/rea AA / multiple-line te+t entry "eld
5abel ))
Some of the methods de"ned in the 5abel class areAA
Method /ction

String get)e+t9< Returns a string containing this labelBs te+t
void set)e+t9String< Changes the te+t of this label
E+ample V@ A 3emo of 5abel

import &ava.awt.R>
1H@
public class 5abel)est e+tends /pplet
8
5abel l1,l@,lH>
(ont f1>
public void init9 <
8

f1 D new (ont 9 =0elvetica= , (ont.6-53, 1M<>
set(ont9f1<>
l1 D new 5abel9=$elcome =<>
add9l1<>
l@ D new 5abel9=)o 5earn %ava=<>
add9l@<>
lH D new 5abel9=Course=<>
add9lH<>
?
?
Autton ))
Methods AA String get5abel9 < ,
void set5abel9String <
E+ample VH A 3emo of 6utton
import &ava.awt.R>
import &ava.applet.R>
public class 6utton)est e+tends /pplet
8
6utton b1,b@>
public void init9 <
8

b1 D new 6utton 9=Rewind=<>
add9b1<>
b@ D new 6utton 9=*lay=<>
add9b@<>
1HH
?
?
Chec8Ao+ ))
Methods
String get5abel9< Returns a string containing chec#bo+Bs label
void set5abel9String< Changes the te+t of the chec#bo+Bs label
boolean getState9< Returns true or false, based on whether the
chec#bo+ is selected or not

void setState96oolean state< Changes the chec#bo+Bs state to selected
9true< or unselected 9false<
E+ample VM A 3emo of Chec#bo+
import &ava.applet.R>
import &ava.awt.R>
public class Chec#bo+)est e+tends /pplet
8
Chec#bo+ c1,c@,cH>
public void init9 <
8
c1 D new Chec#bo+9=Shoes=<>
add9c1<>
c@ D new Chec#bo+9=Soc#s=, true<>
add9c@<>
cH D new Chec#bo+9=Shirt=<>
add9cH<>
?
?
E+ample VF A 3emo of Radio bo+
import &ava.awt.R>
public class Radio)est e+tends &ava.applet./pplet
8
1HM
Chec#bo+Xroup cg>
Chec#bo+ c1,c@,cH>
public void init9 <
8
cg D new Chec#bo+Xroup 9 <>
c1 D new Chec#bo+9=Red=, cg, false<>
add9c1<>

c@ D new Chec#bo+9=6lue=, cg, false<>
add9c@<>
cH D new Chec#bo+9=Tellow=, cg, false<>
add9cH<>
?
?
Choice ))
int get,temCount9< Xets number of items in the control

String get,tem9int inde+< Xets strings at speci"ed inde+
int getSelected,nde+9< Xets inde+ of the currently selected item

String getSelected,tem9< Xets string representation of Choice
E+ample VC A 3emo of Choice
import &ava.awt.R>
public class Choice)est e+tends &ava.applet./pplet
8
Choice ch>
public void init9 <
8
ch D new Choice9 <>
ch.add9=apples=<>
ch.add9=oranges=<>
ch.add9=strawberies=<>
ch.add9=bananas=<>
add9ch <>
?
?
1HF
/e+t&ield ))
String get)e+t9< gets the te+t contained.
void set)e+t 9String te+t< sets the te+t.
void setEchoChar9char echoChar< Sets the echo character.
E+ample VI A 3emo of )e+t(ield
import &ava.awt.R>
public class )e+t(ield)est e+tends &ava.applet./pplet
8
5abel l1,l@>
)e+t(ield t1,t@>
public void init9 <
8
l1 D new 5abel9=name=<>
add9l1<>
t1 D new )e+t(ield9@E<>
add9t1<>
l@ D new 5abel9=password=<>
add9l@<>
t@ D new )e+t(ield9@E<>
t@.setEchoChar9BRB<>
add9t@<>
?
?
/e+tArea))
int getColumns9< Returns the number of columns in the )e+t/rea
int getRows9< Returns the number of rows in the )e+t/rea

insert 9String te+t, int inde+< inserts te+t at the speci"ed position.

void replaceRange9String te+t, int r, int c<
Replaces the e+isting te+t from the indicated start to end positions
with te+t speci"ed.
1HC
E+ample VQ A 3emo of )e+t/rea
import &ava.awt.R>
public class )e+t/rea)est e+tends &ava.applet./pplet
8
String letter D = %ava ,s simpleYn = '
= ,t is ob&ect oriented, Yn = '
= ,t is machine independant =>
)e+t/rea ta>
public void init9 <
8
ta D new )e+t/rea9letter, 1E, MF<>
add9ta<>
?
?
5ist ))
int : ; getSelected,nde+s9< Xets inde+ of the currently selected item
String: ; getSelected,tems9< Xets string representation of Choice
E+ample VV A 3emo of 5ist
import &ava.awt.R>
public class 5ist)est e+tends /pplet
8
5ist lt D new 5ist9H,true<>
public void init9 <
8
lt.add9=Red=<>
lt.add9=6lue=<>
lt.add9=Xreen=<>
lt.add9=6lac#=<>
add9lt<>
?
?
ScrollAar))
int getValue9< Xets current value of Scrollbar
void setValue9int value< Sets value of Scrollbar to a given value
1HI
E+ample 1EE A 3emo of Scrollbar
import &ava.awt.R>
public class Scroll e+tends /pplet
8
Scrollbar b1 D new Scrollbar9Scrollbar.VER),C/5, 1E, 1, 1, 1EE<>
public void init9 <
8
add9b1<>
?
?
E+ample 1E 1 A 3emo of (rame window
import &ava.awt.R>
import &ava.applet./pplet>
public class (rame)est/pplet e+tends /pplet
8
(rame w>
5abel l1,
)e+t(ield t1>
public void init 9 <
8
LL constructs frame with title
wD new (rame 9= My .ew window =<>
LLsets the layout of frame
w.set5ayout 9new (low5ayout9 <<>

l1 Dnew 5abel 9=.ameA =<>
w.add 9l1<>

t1 D new )e+t(ield 9@E<>
w.add 9t1<>
w.resiPe 9HEE,@EE<>
w.show9 <>
1HQ
?
?
E+ample 1E@ A Standlone programming with X7,
public class 3emotest e+tends (rame
8
5abel l1,l@>
)e+t(ield t1,t@>
public 3emotest9 <
8
l1 D new 5abel9=.ame=<>
add9l1<>
t1 D new )e+t(ield9@E<>
add9t1<>
l@ D new 5abel9=*assword=<>
add9l@<>
t@ D new )e+t(ield9@E<>
t@.setEchoChar9BRB<>
add9t@<>

resiPe9@EE,@EE<>
show9<>
?
public static void main9String args:;<
8
3emotest s>
s D new 3emotest9<>
?
?
5a,out Mana'ers
(low 5ayout AA
,t arranges components horiPontally from left to right li#e words in a page. ,t
is default for *anels. ,f the components do not "t in one row then a new row
is started.
6order 5ayout AA
1HV
,t arranges components around the four borders of a container. )he four
sides are referred to as .orth, South, East and $est. )he middle area is
called the center. Every (rame has 6order5ayout, as its default layout
manager.
(or containers other than a (rame, to install a 6order5ayout, we do the
followingA
set5ayout9 new 6order5ayout9< <
Xrid 5ayout AA
,t is used to set a matri+ of components in a rectangular grid along a number
of rows and columns. Each cell in the grid is the same height as the other
cells, and each width is the same width as the other cells.
set5ayout9new Xrid5ayout 9H,M<<>
Card 5ayout AA
,t presents diUerent screens to a user based on a stac# of cards. -ne can
4ip to the "rst, second or last card using methods de"ned by Card5ayout.
Each container in the group is card.
/ name is given to each card and we can display a card by using a
method show9 < as A

show9 container of all cards, name of card<>
$e can add a container to a card by add9< method
add9name , container<>

Xrid6ag 5ayoutAA
,t is similar to the Xrid5ayout layout manager because the *anel is divided
into a grid of cells with rows and columns. ,n Xrid6ag5ayout, however the
individual components,can be resiPed by assigning weights. )he helper
class Xrid6agConstraints holds all the information needed by the
Xrid6ag5ayout class to properly position and siPe each 7, component. )he
following is a list of the Xrid6agConstraints member variables and their
default values that are used to de"ne 7, components placementA
)he constraints can be created by the Xrid6agConstraints ob&ect using its
constructor and set the following constraints for the individual components
using setConstraints9 < method.
` grid+, gridy
1ME
` weight+, weighty
` gridwidth, gridheight
` "ll
` Xrid6agConstraint..-.E
` Xrid6agConstraint.0-R,a-.)/5 ,
` Xrid6agConstraint.VER),C/5

` Xrid6agConstraint.6-)0
` ,nsets
` /nchor
` ipad+,ipady
E+ample 1EH A 3emo of 4owlayout
import &ava.awt.R>
public class 3emo4ow e+tends /pplet
8
6utton b1,b@,bH,bM>
(low5ayout 4>
public void init9 <
8
b1 D new 6utton9=%ava=<>
b@ D new 6utton9=-racle=<>
bH D new 6utton9=]M5=<>
bM D new 6utton9=%avaScript=<>

4 D new (low5ayout9(low5ayout<>
set5ayout94<>
add9b1<>
add9b@<>
add9bH<>
add9bM<>
?
?
1M1
E+ample 1EM A 3emo of gridlayout
import &ava.awt.R>
public class 3emogrid e+tends /pplet
8
6utton b1,b@,bH,bM>
Xrid5ayout gr>
public void init9 <
8
b1 D new 6utton9=%ava=<>
b@ D new 6utton9=-racle=<>
bH D new 6utton9=]M5=<>
bM D new 6utton9=%avaScript=<>

gr D new Xrid5ayout9@,@<>

set5ayout9gr<>
add9b1<>
add9b@<>
add9bH<>
add9bM<>
?
?
E+ample 1EF A 3emo of 6orderlayout
import &ava.awt.R>
public class 6order e+tends /pplet
8
6order5ayout br>
6utton b1,b@,bH,bM,bF>

public void init9<
8
br D new 6order5ayout9<>
b1 D new 6utton9=&ava=<>
b@ D new 6utton9=oracle=<>
bH D new 6utton9=sybase=<>
bM D new 6utton9=c''=<>
bF D new 6utton9=,)=<>
1M@

set5ayout9br<>
add9=.orth=, b1<>
add9=South=, b@<>
add9=East=, bH<>
add9=$est=, bM<>
add9=Center=, bF<>
?
?
E+ample 1EC A 3emo of Cardlayout
import &ava.awt.R>
public class 3emoCard e+tends /pplet
8
Card5ayout ca D new Card5ayout9 <>
5abel : ; lb D new 5abel:F;>
LL /n array of 5abels to display as static te+t on each card
public void init9 <
8
LL /ssign the static te+t to each element in the array
lb:E; D new 5abel9=*ersonal 3etails=<>
lb:1; D new 5abel9=(inancial 3etails=<>
lb:@; D new 5abel9=Contact 3etails=<>
lb:H; D new 5abel9=3ispatch 3etails=<>
lb:M; D new 5abel9=Credit 3etails=<>
set5ayout9ca<>
for 9int i D E> i N F> i''<
8
LL /dd each element to the Card 5ayout.
add9=Card = ' i, lb:i;<>
LL3isplay each element of the Card on to the applet.
ca.show9this,=Card = ' i<>
?
?
?
1MH
E+ample 1EI A 3emo of grid bag layout
public class 3emogridbag e+tends /pplet
8
6utton b1,b@,bH,bM,bF,bC>
Xrid6ag5ayout gl>
Xrid6agConstriants gbc>
public void init9 <
8
b1 D new 6utton9=%ava=<>
b@ D new 6utton9=-racle=<>
bH D new 6utton9=]M5=<>
bM D new 6utton9=%Script=<>
bF D new 6utton9=%@EE=<>
bC D new 6utton9=C''=<>

gl D new Xrid6ag5ayout9 <>
gbc D new Xrid6agConstraints9 <>
set5ayout9gl<>
gbc."ll D Xrid6agConstraints.6-)0>
gbc.anchor D Xrid6agConstraints.CE.)ER>
gbc.gridwidth D 1>
gbc.weight+ D 1.E>
gl.setConstraints9b1,gbc<>
add9b1<>
gbc.gridwidth D Xrid6agConstraints.REM/,.3ER>

gl.setConstraints9b@,gbc<>
add9b@<>
gbc.gridwidth D Xrid6agConstraints.REM/,.3ER>

gl.setConstraints9bH,gbc<>
add9bH<>
gbc.weight+ D E.E>
gbc.weighty D 1.E>
gbc.gridheight D @>
gbc.gridwidth D 1>
1MM

gl.setConstraints9bM,gbc<>
add9bM<>

gbc.gridwidth D Xrid6agConstraints.REM/,.3ER>

gbc.gridheight D 1>
gl.setConstraints9bF,gbc<>
add9bF<>
gbc.gridwidth D Xrid6agConstraints.REM/,.3ER>

gbc.gridheight D 1>
gl.setConstraints9bC,gbc<>
add9bC<>
?
?
.+ample 1<3 ) Demo of Canvas
class Canarea e+tens Canvas
8
public void paint9 Xraphics g<
8
set(oreXround9color.green<>
g."ll-val9HE,E,QE,QE<>
g.drawString9=hello %ava=,FE,1EE<>
?
?
public class 3emoCan e+tends /pplet
8
public void init9 <
8
Canarea c D new Canarea9 <>
set6ac#ground9color.red<>
c.setSiPe9@EE,@EE<>
c.set6ac#ground9color.blue<>
c.setVisible9true<>
add9c<>
?
1MF
?
.+ample 1<; ) Panel demo
public class 3emopan e+tends (rame
8
*anel p, sp1, sp@>

public 3emopan9 <
8
setSiPe9HEE,HEE<>
setVisible9true<>
set)itle9=*anel 3emo=<>
set6ac#ground9Color.yellow<>
set5ayout9 new (low5ayout 9 < <>
p D new *anel9 <>
p.set5ayout9 new (low5ayout 9 < <>

sp1 D new *anel9 <>
sp1.set5ayout9 new (low5ayout 9 < <>

sp@ D new *anel9 <>
sp@.set5ayout9 new (low5ayout 9 < <>

p.setSiPe9@FE,@FE<>
p.setVisible9true<>
p.set6ac#ground9Color.red<>
add9p<>
sp1.setVisible9true<>
sp1.set6ac#ground9Color.blue<>
p.add9sp1<>
sp@.setVisible9true<>
sp@.set6ac#ground9Color.pin#<>
p.add9sp@<>
?
public static void main9String args:;<
8
3emopan s>
s D new 3emopan9<>
?
?
1MC
Chapter 11
Dele'ation .vent Modellin'
$hen an event occurs programmer has H options
1. ,gnore the event
@. 5et the component manage the event
H. 3elegate its handling to some other ob&ect called 5istener


/ccording to delegation modeling, (or e+ample when a 6utton clic# occurs ,
then the listener if connected can listen to the event, and then invo#e a
method action performed.
6utton clic#
_
_
5istener listens,and creates an /ctionEvent ob&ect
_
_
*asses this ob&ect to action*erformed9 < method
Control 5istener Methods and .vents
received
-------- -------------
------------------------------------------
6utton /ction5istener action*erformed9/ctionEvent e<
5ist
Menultem
)e+t(ield
Chec#bo+ ,tem5istener itemStateChanged9,temEvent
e<
Choice
1MI
5ist
Chec#bo+ Menu,tem
3ialog(rame $indow5istener
window-pened9$indowEvent e<
windowClosing9$indowEvent e<
windowMinimiPed9$indowEvent e<

Scrollbar /d&ustment5istener
ad&ustmentValueChanged9 /d&ustmentEvent e<
Canvas Mouse5istener mouse*ressed9MouseEvent e<
3ialog mouseReleased9MouseEvent e<
(rame mouseEntered9MouseEvent e<
*anel mouseE+ited9MouseEvent e<
$indow mouseClic#ed9MouseEvent e<

Component \ey5istener #ey)yped9\eyEvent e<
#ey*ressed9\eyEvent e<
#eyReleased9\eyEvent e<
Component (ocus5istener focusXained9(ocusEvent e<
focus5ost9(ocusEvent e<
)e+tComponent )e+t5istener
te+tValueChanged9)e+tEvent e<
.vents and methods
Action.vent ))
,t occurs,
1. $hen a button is clic#ed
@. $hen a menu item is selected
H. $hen a list item is double clic#ed
M. $hen enter #ey pressed in te+t "eld

method AA getSource9 < gives the source that made this event
Item.vent ))
1MQ
,t occurs,
1. $hen a chec# bo+ is selectLdeselected
@. when a choice item is selectLdeselected
H. $hen a list item selectLdeselected
M. $hena chec#bo+ menu item selectLdeselected

method AA get,temSelectable9 < gives reference to the item
selected component.
get,tem9< gives reference to the item that caused the event

Adjustment.vent )) It occurs6
1. $hen a scroll bar thumb is moved
method AA get/d&ustable9 < gives the ob&ect that caused the event
getValue9< gives the new value

/e+t.vent )) It occurs6
1. $hen content of te+t is changed in )e+t(ield, )e+t/rea

Mouse.vent )) It occurs6
1. $hen user clic#s or moves the mouse pointer
method AA get]9<, getT9< gives +,y screen coordinates of mouse
position
getClic#Count9< gives clic# count for an event
!indo%.vent )) ,t occurs,
1. $hen a window minimiPed, opened, activated etc.,
&ocus.vent )) It occurs6
1. $hen a component gains or loses focus

Je,.vent ))
1. ,t is generated by the user during interaction
from #eyboard
method AA get#eyCode9< gives the #ey code for a given char
get\eyChar9< gives char de"ned by a #ey code
1MV
.+ample 111 ) Demo Autton .vents
public class 3emobutt e+tends /pplet implements /ction5istener
8
)e+t(ield t1, t@, tH>
5abel l1,l@,lH>
6utton b1,b@>
Xrid5ayout gl>

public void init9<
8
gl D new Xrid5ayout9M,@<>
set5ayout9gl<>

l1 D new 5abel9=(irstnumb= <>
add9l1<>
t1 D new )e+t(ield91E<>
add9t1<>
l@ D new 5abel9=Secondnumb= <>
add9l@<>
t@ D new )e+t(ield91E<>
add9t@<>
lH D new 5abel9=Result = <>
add9lH<>
tH D new )e+t(ield91E<>
add9tH<>
b1 D new 6utton9=/33=<>
add9b1<>
b1.add/ction5istener9this<>
b@ D new 6utton9=S76=<>
add9b@<>
b@.add/ction5istener9this<>
?
public void action*erformed9/ctionEvent e<
8
if9e.getSource9< DD b1<
8
1FE
int p D ,nteger.parse,nt9 t1.get)e+t9< < '
,nteger.parse,nt9 t@.get)e+t9< <>
tH.set)e+t9 String.value-f9p< <>
?
if9e.getSource9< DD b@<
8
int p D ,nteger.parse,nt9 t1.get)e+t9< < -
,nteger.parse,nt9 t@.get)e+t9< <>
tH.set)e+t9 String.value-f9p< <>
?
?
?
.+ample 114 ) Demo Chec8Ao+ .vents
import &ava.applet.R>
import &ava.awt.R>
import &ava.awt.event.R>
LR N/**5E) C-3EDchec#s.class $,3)0D@EE 0E,X0)D@EE G
NL/**5E)G RL
public class chec#s e+tends /pplet implements ,tem5istener
8
Chec#bo+ c1, c@, cH>
)e+t(ield t1>

public void init9<
8
c1 D new Chec#bo+9=1=<>
add9c1<>
c1.add,tem5istener9this<>
c@ D new Chec#bo+9=@=<>
add9c@<>
c@.add,tem5istener9this<>
cH D new Chec#bo+9=H=<>
add9cH<>
cH.add,tem5istener9this<>

t1 D new )e+t(ield9@E<>
add9t1<>
?
public void itemStateChanged9,temEvent e<
1F1
8
if9e.get,temSelectable9< DD c1 ZZ c1.getState9< <
8
t1.set)e+t9=Chec# bo+ 1 selected J=<>
?
else
if9e.get,temSelectable9< DD c@ ZZ c@.getState9< <
8
t1.set)e+t9=Chec# bo+ @ selectedJ=<>
?
else
if9e.get,temSelectable9< DD cH ZZ cH.getState9< <
8
t1.set)e+t9=Chec# bo+ H selectedJ=<>
?
?
?
.+ample 11= )Demo Radio .vents
public class radios e+tends /pplet implements ,tem5istener
8
Chec#bo+Xroup cg>
Chec#bo+ r1, r@, rH>
)e+t(ield t1>
public void init9<
8
cg D new Chec#bo+Xroup9<>
r1 D new Chec#bo+9=CSE=, false, cg<>
add9r1<>
r1.add,tem5istener9this<>

r@ D new Chec#bo+9=ECE=, false, cg<>
add9r@<>
r@.add,tem5istener9this<>

rH D new Chec#bo+9=EEE=, false, cg<>
add9rH<>
rH.add,tem5istener9this<>

t1 D new )e+t(ield9@E<>
1F@
add9t1<>
?
public void itemStateChanged9,temEvent e<
8
String # D 99Chec#bo+< e.get,temSelectable9<<.get5abel9<>
t1.set)e+t9=Radio button = ' # ' = clic#edJ=<>
?
?
.+ample 11> ) Demo /e+t Area
public class 3emoreplace e+tends /pplet implements /ction5istener
8
)e+t/rea ta1>
6utton b1>
public void init9<
8
ta1 D new )e+t/rea9=.ow is the time.=, F, @E,
)e+t/rea.SCR-556/RSO6-)0<>
add9ta1<>
b1 D new 6utton9=Replace selected te+t=<>
add9b1<>
b1.add/ction5istener9this<>
?
public void action*erformed 9/ctionEvent e<
8
if9 e.getSource9< DD b1 <
8
ta1.replaceRange9 =0ello from %avaJ= , ta1.getSelectionStart9< ,
ta1.getSelectionEnd9< < >
?
?
?
.+ample 11? ) Demo 5ist .ventsB sin'le select
public class list e+tends /pplet implements /ction5istener
8
5ist l1>
)e+t(ield t1>
1FH
public void init9<
8
t1 D new )e+t(ield9@E<>
add9t1<>
l1 D new 5ist9M<>
l1.add9=,tem 1=<>
l1.add9=,tem @=<>
l1.add9=,tem H=<>
l1.add9=,tem M=<>
l1.add9=,tem F=<>
l1.add9=,tem C=<>
l1.add9=,tem I=<>
l1.add9=,tem Q=<>
l1.add9=,tem V=<>
add9l1<>
l1.add/ction5istener9this<>
?
public void action*erformed9/ctionEvent e<
8
if9e.getSource9< DD l1<
8
String n D 9 95ist< e.getSource9< <.getSelected,tem9<>
t1.set)e+t9 n <>
?
?
?
.+ample 111 ) Demo Multiselect B 5ist .vents
public class multiselect e+tends /pplet implements /ction5istener
8
5ist l1>
)e+t(ield t1>
6utton b1>
String s:;>
public void init9<
8
t1 D new )e+t(ield9ME<>
add9t1<>
1FM
l1 D new 5ist9M, true<>
l1.add9=,tem 1=<>
l1.add9=,tem @=<>
l1.add9=,tem H=<>
l1.add9=,tem M=<>
l1.add9=,tem F=<>
l1.add9=,tem C=<>
l1.add9=,tem I=<>
l1.add9=,tem Q=<>
l1.add9=,tem V=<>
add9l1<>
b1 D new 6utton9=Show selections=<>
b1.add/ction5istener9this<>
add9b1<>
?
public void action*erformed9/ctionEvent e<
8
String ot D new String9=Tou selectedA=<>
if9e.getSource9< DD b1<
8
s D l1.getSelected,tems9<>
for9int i D E> i N s.length> i''<
8
ot 'D = = ' s:i;>
?
t1.set)e+t9ot<>
?
?
?
.+ample 112 ) Demo Choice .vents
public class choice e+tends /pplet implements ,tem5istener,
/ction5istener
8
)e+t(ield t1, t@>
Choice c1>
1FF
6utton b1>

public void init9<
8
t1 D new )e+t(ield9@E<>
t@ D new )e+t(ield9@E<>
b1 D new 6utton9=Remove 5isteners=<>
add9t1<>
add9t@<>
c1 D new Choice9<>
c1.add9=,tem 1=<>
c1.add9=,tem @=<>
c1.add9=,tem H=<>
c1.add9=,tem M=<>
add9c1<>
add9b1<>
c1.add,tem5istener9this<>
b1.add/ction5istener9this<>
?
public void itemStateChanged9,temEvent e<
8
if9 e.get,temSelectable9< DD c1 <
8
String n D 99Choice<e.get,temSelectable<<.getSelected,tem9<>
t1.set)e+t9=Tou chose = ' n<>
?
?
public void action*erformed9/ctionEvent e<
8
if9 e.getSource9< DD b1 <
8
,tem5istener:; al D c1.get,tem5isteners9<>
for 9int iDE> iNal.length> i''<
8
c1.remove,tem5istener9al:i;<>
t@.set)e+t9=5istener Removed=<>
?
?
?
1FC
?
1FI
.+ample 113 ) Demo Scroll .vents
public class 3emoscroll e+tends /pplet implements /d&ustment5istener
8
Scrollbar hS1, hS@, vS1, vS@>
)e+t(ield t1>
public void init9<
8
set5ayout9new 6order5ayout9<<>
hS1 D new Scrollbar9Scrollbar.0-R,a-.)/5, 1, 1, 1, 1EE<>
add9=.orth=, hS1<>
hS1.add/d&ustment5istener9this<>
vS1 D new Scrollbar9Scrollbar.VER),C/5, 1, 1, 1, 1EE<>
add9=$est=, vS1<>
vS1.add/d&ustment5istener9this<>
hS@ D new Scrollbar9Scrollbar.0-R,a-.)/5, 1, 1, 1, 1EE<>
add9=South=, hS@<>
hS@.add/d&ustment5istener9this<>
vS@ D new Scrollbar9Scrollbar.VER),C/5, 1, 1, 1, 1EE<>
add9=East=, vS@<>
vS@.add/d&ustment5istener9this<>
t1 D new )e+t(ield9<>
add9=Center=, t1<>
?
public void ad&ustmentValueChanged9/d&ustmentEvent e<
8
if9e.get/d&ustable9< DD hS1<
8
hS@.setValue9hS1.getValue9<<>
t1.set)e+t9=(rom 0oriPontal = ' hS1.getValue9<<>
?
if9e.get/d&ustable9< DD vS1<
8
vS@.setValue9vS1.getValue9<<>
t1.set)e+t9=(rom Vertical = ' vS1.getValue9<<>
?
if9e.get/d&ustable9< DD hS@<
1FQ
8
hS1.setValue9hS@.getValue9<<>
t1.set)e+t9=(rom 0oriPontal = ' hS@.getValue9<<>
?
if9e.get/d&ustable9< DD vS@<
8
vS1.setValue9vS@.getValue9<<>
t1.set)e+t9=(rom Vetical = ' vS@.getValue9<<>
?
?
?
.+ample 11; ) Demo Mouse .vents
public class Mouse3emo e+tends /pplet implements Mouse5istener,
MouseMotion5istener
8
String strD= =>
int ]DE,TDE>
public void init9<
8
addMouse5istener9this <>
addMouseMotion5istener9 this<>
?
public void mouseClic#ed9MouseEvent e<
8
]DE> TD1E>
strD =Mouse Clic#ed=>
repaint9 < >
?
public void mouseEntered9MouseEvent e<
8
]DE> TD1E>
strD =Mouse Entered=>
repaint9 < >
?
public void mouseE+ited9MouseEvent e<
8
1FV
]DE> TD1E>
strD =Mouse E+ited=>
repaint 9 < >
?
public void mouse*ressed9MouseEvent e<
8
]De.get]9<> TDe.getT9 < >
strD =Mouse 3own=>
repaint9 < >
?

public void mouseReleased9MouseEvent e<
8
] D e.get]9< > TDe.getT9< > strD=Mouse 7p=> repaint9<>
?
public void mouse3ragged9MouseEvent e<
8
]De.get]9<> TDe.getT9<> strD=3ragging Mouse =>
showStatus 9 =3ragging at=' e.get]9<' =,=' e.getT9< <>
repaint9<>
?
public void mouseMoved9MouseEvent e<
8
showStatus 9 =Moving mouse at=' e.get]9<'=,= ' e.getT9< <>
?
public void paint9Xraphics g<
8
g.drawString9str, ], T<>
?
?
.+ample 14< ) demo Je, .vents
public class 3emo#ey e+tends /pplet implements \ey5istener
8
String te+t D ==>
public void init9<
8
add\ey5istener9this<>
re2uest(ocus9<>
1CE
?
public void paint9Xraphics g<
8
g.drawString9te+t, E, 1EE<>
?
public void #ey)yped9\eyEvent e<
8
te+tD =\ey Character=>
te+t D te+t ' e.get\eyChar9<>
repaint9<>
?
public void #ey*ressed9\eyEvent e<
8 ?
public void #eyReleased9\eyEvent e<
8
te+t D =\ey 5ocation=>
te+t D te+t ' e.get\ey5ocation9<>
?
?
.+ample 141 ) Demo card la,out
class card*anel e+tends *anel
8
6utton b>
5abel l>
card*anel9card app, String cardnumb<
8
b D new 6utton9=.e+t card=<>
b.add/ction5istener9app<>
add9b<>
l D new 5abel9=)his is card = ' cardnumb<>
add9l<>
?
?
public class card e+tends /pplet implements /ction5istener
8
int inde+ D 1>
Card5ayout cl>
1C1
Card*anel p1, p@, pH>
public void init9<
8
cl D new Card5ayout9<>
set5ayout9cl<>

p1 D new card*anel9this, =one=<>
p@ D new card*anel9this, =two=<>
pH D new card*anel9this, =three=<>

add9="rst=, p1<>
add9=second=, p@<>
add9=third=, pH<>

cl.show9this, ="rst=<>
?
public void action*erformed9/ctionEvent event<
8
switch9''inde+<
8
case 1A cl.show9this, ="rst=<>
brea#>
case @A cl.show9this, =second=<>
brea#>
case HA cl.show9this, =third=<>
brea#>
?
if9inde+ DD H< inde+ D E>
repaint9<>
?
?
.+ample 144 ) Demo Hridba' 5a,out
public class 3emogridbag e+tends /pplet implements /ction5istener
8
6utton b1, b@, bH>
)e+t(ield t1>
public void init9<
1C@
8
Xrid6ag5ayout gr D new Xrid6ag5ayout9<>
Xrid6agConstraints con D new Xrid6agConstraints9<>
set5ayout9gr<>
con.weighty D 1>
con."ll D Xrid6agConstraints.6-)0>
con.weight+ D 1>
b1 D new 6utton9=6utton 1=<>
gr.setConstraints9b1, con<>
b1.set/ctionCommand9=button 1=<>
add9b1<>
b1.add/ction5istener9this<>
con.weight+ D @>
b@ D new 6utton9=6utton @=<>
gr.setConstraints9b@, con<>
b@.set/ctionCommand9=button @=<>
add9b@<>
b@.add/ction5istener9this<>
con.weight+ D 1>
bH D new 6utton9=6utton H=<>
con.gridwidth D Xrid6agConstraints.REM/,.3ER>
gr.setConstraints9bH, con<>
bH.set/ctionCommand9=button H=<>
add9bH<>
bH.add/ction5istener9this<>
t1 D new )e+t(ield9<>
con.gridwidth D Xrid6agConstraints.REM/,.3ER>
gr.setConstraints9t1, con<>
add9t1<>
?
public void action*erformed9/ctionEvent e<
8
String m D 996utton< e.getSource9<<.get/ctionCommand9<>
t1.set)e+t9=Tou clic#ed = ' m <>
?
?
Adapter classes ))
1CH
)hey are the classes that have already implemented the event interfaces
with empty methods. )hen we may override any method of choice as per the
need. (or E+. Mouse5istener has F methods that we must implement, but
when a Mouse/dpater class is used in its place then, we may override only
the re2uired methods.
.+ample 14= )) Demo of inner adapter class
public class 3emoapp e+tends /pplet
8
String s D =0ello to %avaJ=>
public void init9<
8
addMouse5istener9new Mouse/dapter9<
8
public void mouse*ressed9MouseEvent e<
8
s D =6ye to %avaJ=>
repaint9<>
?
? <>
?
public void paint9Xraphics g<
8
g.drawString9s,CE,1EE<>
?
?
Creatin' %indo% Applications
.+ample 14> ) Demo frame %indo%

public class )est$in e+tends /pplet implements /ction5istener
8
6utton b1, b@>
3emowin wind>
1CM
public void init9<
8
b1 D new 6utton9=3isplay the window=<>
add9b1<>
b1.add/ction5istener9this<>
b@ D new 6utton9=0ide the window=<>
add9b@<>
b@.add/ction5istener9this<>
wind D new 3emowin9=%ava window=<>
wind.setSiPe9HEE, @EE<>
?
public void action*erformed9/ctionEvent e<
8
if9e.getSource9< DD b1< 8
wind.setVisible9true<>
?
if9e.getSource9< DD b@< 8
wind.setVisible9false<>
?
?
?
class 3emowin e+tends (rame implements Mouse5istener,$indow5istener
8
5abel l>
3emowin9String title<
8
super9title<>
set5ayout9 new (low5ayout9< <>
l D new 5abel9=0ello from %avaJ )his is a frame window.=<>
add9l<>

addMouse5istener9this<>

LL )his is to e+it when the window is closed
add$indow5istener9 new $indow/dapter9<
8
public void windowClosing9$indowEvent e<
1CF
8
setVisible9false<>
LL we can also use, System.e+it9E<>
?
? <>
?
public void mouse*ressed9MouseEvent e<
8

if9 9 e.getModi"ers9< Z ,nputEvent.67))-.1OM/S\ < DD
,nputEvent.67))-.1OM/S\ <
8
l.set)e+t9 =5eft mouse down at ='e.get]9<'=,='e.getT9< <>
?
else
8
l.set)e+t9 =Right mouse down at='e.get]9<'=,=' e.getT9< <>
?
?
public void mouseClic#ed9MouseEvent e<

8
l.set)e+t9 =Mouse clic#ed at = ' e.get]9<'=,='e.getT9< <>
?
public void mouseReleased9MouseEvent e<
8
l.set)e+t9=)he mouse button went up.=<>
?
public void mouseEntered9MouseEvent e<
8
l.set)e+t9=)he mouse entered.=<>
?
public void mouseE+ited9MouseEvent e<
8
l.set)e+t9=)he mouse e+ited.=<>
?
1CC
?
Menu)
-b&ect
_

MenuComponent
_
OOOOOOOOOOOO
_ _
Menu,tem Menu6ar
_
OOOOOOOOOOOOOOO
_ _
Chec#bo+Menu,tem Menu
_
_
*opupMenu
,n &ava there is an abstract class called MenuComponent, for menu related
classes.
/ Menu6ar class, implements a menubar which is attached to a frame
window
Menu class, implements a single pull down menu, that is attached to a menu
bar or other menu.
Menu,tem class, implements items that can be selected from a pull down
Menu. Chec#bo+Menu,tem class implements menu items, that may be
che#ed on or oU for toggle purpose.
)here is a seperate MenuContainer interface providing a set of methods,
which are implemented by Menu6ar class and Menu class. (rames also
implement this class.

1CI
.+ample 14? ) Demo of Menus
public class 3emomenu e+tends /pplet implements /ction5istener
8
6utton b1>
)estwind menu$indow>
public void init9<
8
b1 D new 6utton9=3isplay the menu window=<>
add9b1<>
b1.add/ction5istener9this<>
menu$indow D new )estwind9=SampleMenus=<>
menu$indow.setSiPe9@EE, @EE<>
?
public void action*erformed9/ctionEvent e<
8
if9e.getSource9< DD b1< 8
menu$indow.setVisible9true<>
?
?
?
class )estwind e+tends (rame implements /ction5istener
8
Menu6ar mb>
Menu m>
Menu,tem mi1, mi@, miH>
5abel l>
)estwind9String title<
8
super9title<>
l D new 5abel9=0ello from %avaJ=<>
set5ayout9new Xrid5ayout91, 1<<>
add9l<>
mb D new Menu6ar9<>
m D new Menu9=(ile=<>
1CQ
mi1 D new Menu,tem9=,tem 1=<>
m.add9mi1<>
mi1.add/ction5istener9this<>
mi@ D new Menu,tem9=,tem @=<>
m.add9mi@<>
mi@.add/ction5istener9this<>
miH D new Menu,tem9=,tem H=<>
m.add9miH<>
miH.add/ction5istener9this<>
mb.add9m<>
setMenu6ar9mb<>
add$indow5istener9new $indow/dapter9<
8
public void windowClosing9$indowEvent e<
8
setVisible9false<>
?
? <>
?
public void action*erformed9/ctionEvent e<
8
if9e.getSource9< DD mi1<
l.set)e+t9=Tou chose item 1=<>
else
if9e.getSource9< DD mi@<
l.set)e+t9=Tou chose item @=<>

else if9e.getSource9< DD miH<
l.set)e+t9=Tou chose item H=<>
?
?
.+ample 141 ) Demo of Menus6 submenu6 Chec8Menuitem etc(6
public class 3emomenu1 e+tends /pplet implements /ction5istener
8
6utton b1>
)estwind menu$indow>
1CV
public void init9<
8
b1 D new 6utton9=3isplay the menu window=<>
add9b1<>
b1.add/ction5istener9this<>
menu$indow D new )estwind9=SampleMenus=<>
menu$indow.setSiPe9@EE, @EE<>
?
public void action*erformed9/ctionEvent event<
8
if9event.getSource9< DD b1<
8 menu$indow.setVisible9true<> ?
?
?
class )estwind e+tends (rame implements /ction5istener, ,tem5istener
8

Menu6ar mb>
Menu m, s>
5abel l>
Menu,tem mi1, mi@, miM>
Menu,tem si1, si@, siH>
Chec#bo+Menu,tem miH>
)estwind9String title<
8
super9title<>
l D new 5abel9=0ello from %avaJ=<>
set5ayout9new Xrid5ayout91, 1<<>
add9l<>
mb D new Menu6ar9<>
m D new Menu9=(ile=<>
mi1 D new Menu,tem9=,tem 1=<>
mi1.add/ction5istener9this<>
m.add9mi1<>
mi@ D new Menu,tem9=,tem @=<>
1IE
mi@.add/ction5istener9this<>
m.add9mi@<>
m.addSeparator9<>
miH D new Chec#bo+Menu,tem9=Chec# ,tem=<>
miH.add,tem5istener9this<>
m.add9miH<>
m.addSeparator9<>
s D new Menu9=Sub menus=<>
si1 D new Menu,tem9=Sub item 1=<>
si@ D new Menu,tem9=Sub item @=<>
siH D new Menu,tem9=Sub item H=<>
si1.add/ction5istener9this<>
si@.add/ction5istener9this<>
siH.add/ction5istener9this<>
s.add9si1<>
s.add9si@<>
s.add9siH<>
mi@.add9s<>
m.addSeparator9<>
miM D new Menu,tem9=E+it=<>
miM.add/ction5istener9this<>
m.add9miM<>
mb.add9m<>
setMenu6ar9mb<>
add$indow5istener9 new $indow/dapter9<
8
public void windowClosing9$indowEvent e<
8
setVisible9false<>
?
? <>
?
public void action*erformed9/ctionEvent e<
8
1I1
if9e.getSource9< DD mi1<
label.set)e+t9=Tou chose item 1=<>?
else
if9e.getSource9< DD mi@<
8
mi@.setEnabled9false<>
l.set)e+t9=Tou chose item @=<>
?
else
if9e.getSource9< DD si1<
l.set)e+t9=Tou chose sub item 1=<>

else
if9e.getSource9< DD si@<
l.set)e+t9=Tou chose sub item @=<>

else
if9e.getSource9< DD siH<
l.set)e+t9=Tou chose sub item H=<>
else
if9e.getSource9< DD miM<
setVisible9false<>
?
?
public void itemStateChanged 9,temEvent e<
8
if9e.getSource9< DD miH<
8
if9 9 9Chec#bo+Menu,tem< e.get,temSelectable9< <.getState9< <
l.set)e+t9=,tem H is chec#ed=<>
else
l.set)e+t9=,tem H is not chec#ed=<>
?
?
?
.+ample 142 ) Demo of Pop up menus
$hen we right clic# on some application menus called, pop up appear
1I@
public class popup e+tends /pplet implements /ction5istener,
Mouse5istener
8
5abel l>
*opupMenu pp>
Menu,tem mi1, mi@, miH, miM>

public void init9<
8
pp D new *opupMenu9=Menu=<>
mi1 D new Menu,tem9=,tem 1=<>
mi1.add/ction5istener9this<>
mi@ D new Menu,tem9=,tem @=<>
mi@.add/ction5istener9this<>
miH D new Menu,tem9=,tem H=<>
miH.add/ction5istener9this<>
miM D new Menu,tem9=,tem M=<>
miM.add/ction5istener9this<>

pp.add9mi1<>
pp.addSeparator9<>
pp.add9mi@<>
pp.addSeparator9<>
pp.add9miH<>
pp.addSeparator9<>
pp.add9miM<>
add9pp<>
l D new 5abel9=0ello from %avaJ=<>

add9l<>
addMouse5istener9this<>
?
public void mouse*ressed9MouseEvent e<
8
if9e.getModi"ers9< JD E< 8
1IH
pp.show9 this, e.get]9<, e.getT9< <>
?
?
public void mouseClic#ed9MouseEvent e<8 ?
public void mouseReleased9MouseEvent e<8 ?
public void mouseEntered9MouseEvent e<8 ?
public void mouseE+ited9MouseEvent e<8 ?
public void action*erformed9/ctionEvent e<
8

if9e.getSource9< DD mi1<
l.set)e+t9=Tou chose item 1=<>

else if9e.getSource9< DD mi@<
l.set)e+t9=Tou chose item @=<>

else if9e.getSource9< DD miH<
l.set)e+t9=Tou chose item H=<>

else if9e.getSource9< DD miM<
l.set)e+t9=Tou chose item M=<>
?
?
Dialo' Ao+
/ 3ialog class can create a 3ialog bo+. ,t is a sub class of window class. ,t
will not have menubar, and can not be resiPed. )hey are popup windows, and
accept input from user and always depend on other windows. 0nece it is
always created from an e+isting window.
)here are two types.
Modal AA ,t does not allow the user to interact with any other window while
it is displyed, and it is on top of all
1IM
ModelessAA ,t allow the user to interact with other windows. for E+ a
message bo+ displaying the status of installation process, is modeless
dialogue as the user can perform other &obs while installation is under
progress.
.+ample 143 ) Demo of Dialo' Ao+es
class mydialogue e+tends 3ialogue implements /ction5istener
8
label l> 6utton b1,b@>
mydialogue9 par, title<
8
super9par, title, true<>
setSiPe9@EE,@EE<>
set5ayout9 new (low5ayout9 < <>

l D new 5abel9=selected 2uit option=<>
add9l<>

b1 D new 6utton9=-\=<>
add9b1<>
b1.add/ction5istener9this<>
b@ D new 6utton9=Cancel=<>
add9b@<>
b@.add/ction5istener9this<>
?
public void action*erformed9/ctionEvent e<
8
dispose9 <>
?
?
class my(rame e+tends (rame implements /ction5istener
8
my(rame9 String title <
8
super9title<>
Menubar mb D new Menu6ar9 <>
setMenu6ar9mb<>
1IF
Menu m D new Menu9=(ile=<>
Menu,tem mi1,mi@>
mi1 D new Menu,tem9=.ew=<>
mi@ D new Menu,tem9=[uit=<>
mb.add9m<>
mi@.add/ction5istener9this<>
?
public void action*erformed9/ctionEvent e<
8
if 9e.getSource9< DD mi@<
8
mydialogue d D new mydialogue9this, =3emo 3ialogue=<>
d.setVisible9true<>
dispose9<>
?
?

?
public class 3emodialogue e+tends /pplet
8
my(rame f>
public void init9 <
8
f D new my(rame9= frame window=<>
f.setSiPe9HEE,HEE<>
?
public void start9 <
8
f.setVisible9true<>
?
public void stop9 <
8
f.setVisible9false<>
?
?
1IC
.+ample 14; ) Demo of mini calculator
class glass e+tends *anel
8
)e+t(ield t1>
glass9 <
8
t1 D new )e+t(ield9@E<>
add9t1<>
?
?
class digits e+tends *anel
8
6utton bE,b1,b@,bH,bM,bF,bC,bI,bQ,bV>
6utton bp,bs,bm,bd,bpo,be,bon>

digits9 <
8
setlayout9 new Xrid5ayout9F,M<<>
bE D new 6utton9=E=<> add 9bE<>
b1 D new 6utton9=1=<> add 9b1<>
b@ D new 6utton9=@=<> add 9b@<>
bH D new 6utton9=H=<> add 9bH<>
bM D new 6utton9=M=<> add 9bM<>
bF D new 6utton9=F=<> add 9bF<>
bC D new 6utton9=C=<> add 9bC<>
bI D new 6utton9=I=<> add 9bI<>
bQ D new 6utton9=Q=<> add 9bQ<>
bV D new 6utton9=V=<> add 9bV<>
bp D new 6utton9='=<> add 9bp<>
bs D new 6utton9=-=<> add 9bs<>
bm D new 6utton9=R=<> add 9bm<>
bd D new 6utton9=L=<> add 9bd<>
bpo D new 6utton9=.=<> add 9bpo<>
be D new 6utton9=D=<> add9be<>
1II
bon D new 6utton9=-.L-((=<> add9bon<>
?
?
public class 3emocal e+tends /pplet implements /ction5istener
8
4oat m,n> char f>
glass p> digits d>

public void init9 <
8
setlayout9new 6order5ayout9 <<>

p D new glass9 <> add9 p, 6order5ayout..-R)0 <>
d D new digits9 <> add9 d, 6order5ayout.CE.)ER <>
d.bE.add/ction5istener9this<>

d.b1.add/ction5istener9this<>
d.b@.add/ction5istener9this<>
d.bH.add/ction5istener9this<>
d.bM.add/ction5istener9this<>
d.bF.add/ction5istener9this<>
d.bC.add/ction5istener9this<>
d.bI.add/ction5istener9this<>
d.bQ.add/ction5istener9this<>
d.bV.add/ction5istener9this<>

d.bp.add/ction5istener9this<>
d.bs.add/ction5istener9this<>
d.bm.add/ction5istener9this<>
d.bd.add/ction5istener9this<>
d.bpo.add/ction5istener9this<>
d.be.add/ction5istener9this<>
d.bon.add/ction5istener9this<>
?
public void actionperformed9/ctionEvent e<
1IQ
8
if9 e.getSource9 < DD d.bo<
p.t1.set)e+t9 9p.t1.get)e+t9 < ' d.bE.getlabel9 < <>

if9 e.getSource9 < DD d.b1<
p.t1.set)e+t9 9p.t1.get)e+t9 < ' d.b1.getlabel9 < <>
if9 e.getSource9 < DD d.b@<
p.t1.set)e+t9 9p.t1.get)e+t9 < ' d.b@.getlabel9 < <>

if9 e.getSource9 < DD d.bH<
p.t1.set)e+t9 9p.t1.get)e+t9 < ' d.bH.getlabel9 < <>

if9 e.getSource9 < DD d.bM<
p.t1.set)e+t9 9p.t1.get)e+t9 < ' d.bM.getlabel9 < <>

if9 e.getSource9 < DD d.bF<
p.t1.set)e+t9 9p.t1.get)e+t9 < ' d.bF.getlabel9 < <>

if9 e.getSource9 < DD d.bC<
p.t1.set)e+t9 9p.t1.get)e+t9 < ' d.bC.getlabel9 < <>

if9 e.getSource9 < DD d.bI<
p.t1.set)e+t9 9p.t1.get)e+t9 < ' d.bI.getlabel9 < <>

if9 e.getSource9 < DD d.bQ<
p.t1.set)e+t9 9p.t1.get)e+t9 < ' d.bQ.getlabel9 < <>

if9 e.getSource9 < DD d.bV<
p.t1.set)e+t9 9p.t1.get)e+t9 < ' d.bV.getlabel9 < <>
if9 e.getSource9 < DD d.bp<
8
m D (loat.parse(loat9p.t1.get)e+t9 < <>
p.t1.set)e+t9= =<>
1IV
f D BpB>
?
if9 e.getSource9 < DD d.bs<
8
m D (loat.parse(loat9p.t1.get)e+t9 < <>
p.t1.set)e+t9= =<>
f D BsB>
?
if9 e.getSource9 < DD d.bm<
8
m D (loat.parse(loat9p.t1.get)e+t9 < <>
p.t1.set)e+t9= =<>
f D BmB>
?
if9 e.getSource9 < DD d.bd<
8
m D (loat.parse(loat9p.t1.get)e+t9 < <>
p.t1.set)e+t9= =<>
f D BdB>
?
if9 e.getSource9 < DD d.bpo<
8
p.t1.set)e+t9 p.t1.get)e+t9 < ' d.bpo.get5abel9 < <>
?
if9 e.getSource9 < DD d.bon<
8
p.t1.set)e+t9 = =<>
?
if9 e.getSource9 < DD d.be<
8
if 9 f DD BpB<
8
n D 9m ' (loat.parse(loat9p.t1.get)e+t9 < < <>
p.t1.set)e+t9 String.value-f9n<<>
?

if 9 f DD BsB<
8
n D 9m - (loat.parse(loat9p.t1.get)e+t9 < < <>
p.t1.set)e+t9 String.value-f9n<<>
1QE
?
if 9 f DD BmB<
8
n D 9m R (loat.parse(loat9p.t1.get)e+t9 < < <>
p.t1.set)e+t9 String.value-f9n<<>
?
if 9 f DD BdB<
8
n D 9m L (loat.parse(loat9p.t1.get)e+t9 < < <>
p.t1.set)e+t9 String.value-f9n<<>
?
?
?
?
.+ample 1=< ) Demo of Menus
class )estwind e+tends (rame implements /ction5istener
8
Menu6ar mb>
Menu m1,m@>
)e+t(ield t>
Menu,tem mi1, mi@,miH, miM>

)estwind9String title<
8
super9title<>
t D new )e+t(ield9@E<>
set5ayout9new Xrid5ayout91, 1<<>
add9t<>
mb D new Menu6ar9<>

m1 D new Menu9=study=<>
mi1 D new Menu,tem9=MC/=<>
mi1.add/ction5istener9this<>
m1.add9mi1<>
mi@ D new Menu,tem9=6.)ech=<>
mi@.add/ction5istener9this<>
m1.add9mi@<>

1Q1
m@ D new Menu9=*lace=<>
miH D new Menu,tem9=7niversity=<>
miH.add/ction5istener9this<>
m@.add9miH<>
miM D new Menu,tem9=/U College=<>
miM.add/ction5istener9this<>
m@.add9miM<>
setMenu6ar9mb<>
add$indow5istener9 new $indow/dapter9<
8
public void windowClosing9$indowEvent e<
8
setVisible9false<>
?
? <>
?
public void action*erformed9/ctionEvent e<
8
if9e.getSource9< DD mi1<
t.set)e+t9=Tour study is MC/=<>?
else
if9e.getSource9< DD mi@<
t.set)e+t9=Tour study is 6.)ech=<>

else
if9e.getSource9< DD miH<
t.set)e+t9=Tou are in 7niv=<>

else
if9e.getSource9< DD miM<
t.set)e+t9=Tou are in ab coll=<>
?
?
public class 3emomenu e+tends /pplet implements /ction5istener
8
1Q@
6utton b1,b@>
)estwind w>
public void init9<
8
b1 D new 6utton9=3isplay=<>
add9b1<>
b1.add/ction5istener9this<>
b@ D new 6utton9=hide=<>
add9b@<>
b@.add/ction5istener9this<>
w D new )estwind9=Student info=<>
w.setSiPe9@EE, @EE<>
?
public void action*erformed9/ctionEvent e<
8
if9e.getSource9< DD b1<
8 w.setVisible9true<> ?
if9e.getSource9< DD b@<
8 w.setVisible9false<> ?
?
?
.+ample 1=1 ) Demo of Panel

class Coursemenu e+tends *anel
8
Chec#bo+ c1, c@,cH>
)e+t(ield t1>
Chec#bo+Xroup cg>

Coursemenu9 <
8
set5ayout9 new Xrid5ayout9M,1<<>
cg D new Chec#bo+Xroup9 <>
c1 D new Chec#bo+9=6asics=, cg, false<>
add9c1< >
1QH
c@ D new Chec#bo+9=$eb=, cg, false<>
add9c@< >

cH D new Chec#bo+9=graphics=, cg, false<>
add9cH<>
t1 D new )e+t(ield9HE<> add9t1<>
?
?
class Contentmi+ e+tends *anel
8
Chec#bo+ i1,i@,iH,iM,iF,iC>
Contentmi+9 <
8
set5ayout9 new Xrid5ayout9H,@< <>
i1 D new Chec#bo+9=Ms occe =<> add9i1<>
i@ D new Chec#bo+9=oracle=<> add9i@<>

iH D new Chec#bo+9=%EE F.E =<> add9iH<>
iM D new Chec#bo+9= ..E) =<> add9iM<>

iF D new Chec#bo+9=/nimation =<> add9iF<>
iC D new Chec#bo+9=Maya =<> add9iC<>
?
?
public class 3emo,)school e+tends /pplet implements ,tem5istener
8
Coursemenu p1> Contentmi+ p@>

public void init9 <
8
set5ayout9 new Xrid5ayout91,@< <>

p1 D new Coursemenu9<> add9p1<>
p@ D new Contentmi+9<> add9p@<>

p1.c1.additem5istener9this<>
p1.c@.additem5istener9this<>
p1.cH.additem5istener9this<>
?
1QM
public void itemStateChanged9,temEvent e<
8
if9 e.get,temSelectable9< DD p1.c1 <
8
p@.i1.setState9true<>
p@.i@.setState9true<>

p@.iH.setState9false<>
p@.iM.setState9false<>
p@.iF.setState9false<>
p@.iC.setState9false<>
p1.t1.set)e+t9=course fee Rs MFEEL-=<>

?
if9 e.get,temSelectable9< DD p1.c@ <
8
p@.i1.setState9false<>
p@.i@.setState9false<>

p@.iH.setState9true<>
p@.iM.setState9true<>
p@.iF.setState9false<>
p@.iC.setState9false<>
p1.t1.set)e+t9=course fee Rs VFEEL-=<>
?
if9 e.get,temSelectable9< DD p1.cH <
8
p@.i1.setState9false<>
p@.i@.setState9false<>

p@.iH.setState9false<>
p@.iM.setState9false<>
p@.iF.setState9true<>
p@.iC.setState9true<>
p1.t1.set)e+t9=course fee Rs 1MFEEL-=<>

?
1QF
?
?
.+ample 1=4 ) Demo of Movin' MarGuee
public class Mar2uee e+tends /pplet implements Runnable
8
int +DE,yDE,wDE>
)hread p D null>
public void init9 <
8
+ D siPe9<.width>
y D siPe9<.height>
w D +>
?

public void start9 <
8
p D new )hread9this<>
p.start9<>
?
public void run9<
8
while9true<
8
repaint9<>
+ D +-1E>
if9+ NE < + D w>

try
8
)hread.sleep9FEE<>
?
catch9,nterruptedE+ception e<
8 ?
?
?
public void paint9Xraphics g<
8
1QC
g.drawString9=&ava=, +,y<>
?
?
1QI
Chapter 11
IO Streams C &iles
%ava uses streams to handle ,L- operations through which the data is 4owed
from one location to another. (or e+ample, an InputStream can 4ow the data from
a dis# "le to the internal memory and an OutputStream can 4ow the data from
the internal memory to a dis# "le. )he dis#-"le may be a te+t "le or a binary "le.
/ Stream is an abstraction for the source or destination of data. )he source
or destination can be anything , dis#, memory buUer, networ# connection.
/ Stream will have methods to operate on the data from the source or
destination tied with them.
)ypes of Stream
/n ,nput stream reads data where as an output stream write data. 6yte
streams read or write bytes where as charcter streams read or write
characters.
Stream methods are synchroniPed and they will wait for the data to be
avialable then perform operation, and return. 5owlevel streams wor# with
raw bytes, as stored by the "le system and
usefull for ta#ing an image of the data stored.
0ighlevel streams wor# with charcter and primitive types , ob&ects and
provide meaningful entries for the programmer. ,t is possible to chain
streams to provide new functionality.
6yte Streams

1QQ
)hey can handle only Q-bit 6ytes. )hey are abstracted by classes
,nputStream and -utputStream . )here are specialiPed classes derived from
above abstract classes ,to handle reading and writing bytes.
)he subclasses inherited from the InputStream class can be seen in a hierarchy
manner shown belowA
)he classes inherited from the OutputStream class can be seen in a hierarchy
structure shown belowA
-utputStream is also inherited from the -b&ect class. Each class of the
outputStreams provided by the &ava.io pac#age is intended for a diUerent purpose.
)he (ile,nputStream handles byte oriented inputs from "les. )he
6uUered,nputStream can use methods to move bac#wards in a buUered
stream. ,n a 6uUered-uptutStream we dont haver to write data to dis# for
each byte, but it can buUered and force a 4ush operation at once.
)he 3ata,nputStream can handle data in primitive types.

.+ample 1>< ) Demo of of &ileInputStream
1QV
import &ava.io.R>
public class 3emo)est
8
public static void main9String args:;< throws E+ception
8
(ile,nputStream f D new (ile,nputStream 9=3emo)est.&ava=<>
int len D f.avilable9<>
System.out.println9=/vailable bytesA = ' len<>
System.out.println9=Reading 1LF of "le....=<>
byte b:; D new byte:lenLF;>
f.read9b<>
LL convert byte array into string
System.out.println9new String9b, E, b.length <<>
System.out.println9=S#ipping =<>

f.s#ip9lenLF<>
System.out.println9=Reading ne+t 1LF of "le....=<>
if 9f.read9b< JD lenLF<
8
System.out.println9=Could not get =<>
?
else 8
System.out.println9new String9b, E, b.length< <>
?
f.close9<>
?
?
1VE
.+ample 1>1 ) Demo of of &ileOutputStream
import &ava.io.R>
public class (demo
8
public static void main9String args:;< throws E+ception
8
byte data:; D =)his is a string of te+t.=.get6ytes9<>
(ile-utputStream f1 D new (ile-utputStream9="le1.t+t=<>
for 9int i D E> i N data.length> i''<
8
f1.write9data:i;<>
?
(ile-utputStream f@ D new (ile-utputStream9="le@.t+t=<>
f@.write9data<>
(ile-utputStream fH D new (ile-utputStream9="leH.t+t=<>
fH.write9data, F, 1E<>
f1.close9<>
f@.close9<>
fH.close9<>
?
?
.+ample 1>4 ) Demo of DataOutputStream C DataInputStream
)hey permit reading or writing of primitive data types. /fter read we have to
use methods to convert them to character, or string inorder to understand

import &ava.io.R>
public class 3emo3ata,-
8
public static void main9String:; args< throws ,-E+ception
8
3ata-utputStream out D new 3ata-utputStream9 new
(ile-utputStream9=datas.t+t= <<>
double:; prices D 8 V.VV, M.VV, 1F.VV, H.VV ?>
int:; units D 8 1@, C, 1E, V ?>
String:; descs D 8 =mangos=, =oranges =, =apples=, =corn=?>
for 9int i D E> i N prices.length> i''<
8
1V1
out.write3ouble9prices:i;<>
out.writeChar9BYtB<>
out.write,nt9units:i;<>
out.writeChar9BYtB<>
out.writeChars9descs:i;<>
out.writeChar9BYnB<>
?
out.close9<>
LL now read the data from the "le
3ata,nputStream in D new 3ata,nputStream9 new
(ile,nputStream9=datas.t+t=<<>
double price>
int unit>
String desc>
double total D E.E>
try 8
while 9true<
8
price D in.read3ouble9<>
in.readChar9<> LL throws out the tab
unit D in.read,nt9<>
in.readChar9<> LL throws out the tab
desc D in.read5ine9<>
System.out.println9 price <>
System.out.println9 unit <>
System.out.println9 desc <>
total D total ' unit R price>
?
?
catch 9E-(E+ception e<
8
?

in.close9<>
?
?
Character Streams
1V@
)hey support Reader, $riter /bstract classes for reading or writing 1C bit
charcter inputs or outputs. )hese abstract classes have child classes to
support operations.
-b&ect
_
Reader
_
OOOOOO _ OOOOOOOOO
_ _
6uUeredReader ,nputStreamReader
_
(ileReader
-b&ect
_
$riter
_
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
_ _ _
6uUered$riter -utputStream$riter *rint$riter
_
(ile$riter
)he ,nputStreamReader can read data from #eyboard thorugh System.in, and
its counter part is -utputStream$riter.
(ileReader, (ile$riter classes can handle streams from "les. 6uUeredReader
can read line by line instead of character by char.
*rin$riter can send formated outputs.
.+ample 1>= ) Demo of &ile!riter
import &ava.io.R>
class 3emotest
8
public static void main9String args:;< throws E+ception
8
char data: ; D8 B)B, BhB, BiB, BsB, B B ,

BiB, BsB, B B ,

BaB, B B ,
1VH

B6B , doB, doB, d#e ?>
(ile$riter f D new (ile$riter9="le1.t+t=<>
for 9int i D E> i N data.length> i''<
8
f.write9data:i;<>
?
(ile$riter f@ D new (ile$riter9="le@.t+t=<>
f@.write9data<>
(ile$riter fH D new (ile$riter9="leH.t+t=<>
fH.write9data, F, 1E<>
fH.append9= made in &ava =<>
f1.close9<>
f@.close9<>
fH.close9<>
?
?
.+ample 1>> ) Demo of Au-eredReader
$e use this class to create character based stream that reads from a "le line
by line instead of character by character.
import &ava.io.R>
public class 3emo)est
8
public static void main9String args:;< throws E+ception
8
(ileReader f D new (ileReader9="leH.t+t=<>
6uUeredReader bf D new 6uUeredReader9f<>
while9 true <
8
String + D bf.read5ine9 <>
if 9 + DD null < brea#>
else
System.out.println9+<>
?
bf.close9 <>
f.close9 <>
1VM
?
?
.+ample 1>? ) Demo of InputStreamReader
,t is used to read the data typed from the #eyboard.
import &ava.io.R>
class ,nputStreamReader3emo
8
public static void main9String args:;<
8
try
8
int c>
,nputStreamReader ir D new ,nputStreamReader9System.in<>
while 9 9c D ir.read9< < JD -1<
8
System.out.print9 9char< c<>
?
?
catch 9,-E+ception e<
8 ?
?
?
Object Seriali0ation
,t is a process of writing ob&ects to a stream, and reading them bac# when
wanted.
$e use -b&ect,nputStream, -b&ect-utputStream classes respectively which
are derived from ,nputStrem, -utputStream classes to handle the -b&ects
which are called ob&ect streams.
.+ample 1>1 ) Demo of Object streams(
)o serailiPe an ob&ect it should implement a SerialiPable interface.
import &ava.io.R>
class .ewString implements SerialiPable
1VF
8
String d>
public .ewString9 String p<
8
d D p>
?
public void dispdata9 <
8
System.out.println9d<>
?
?
public class 3emo)est
8
public static void main9String args:;<
8
.ewString i1, o1>
i1 D new .ewString9==<>
o1 D new .ewString9=0ello from %avaJ=<>
try
8
(ile-utputStream fo D new (ile-utputStream 9=testob&.dat=<>
-b&ect-utputStream ofo D new -b&ect-utputStream9fo<>
ofo.write-b&ect9o1<>
ofo.4ush9<>
ofo.close9<>
(ile,nputStream "D new (ile,nputStream 9 testob&.dat=<>
-b&ect,nputStream o" D new -b&ect,nputStream9"< >
i1 D 9.ewString<o".read-b&ect9<>
i1.dispdata9<>
o".close9<>
?
catch9E+ception e< 8 ?
System.out.println9i1<>
?
?
1VC
.+ample 1>2 ) Demo of Object streams(
)o serailiPe an ob&ect it should implement a SerialiPable interface.
import &ava.io.R>
import &ava.util.R>
class Student implements SerialiPable
8
int htno>
String name>
public Student9int +, String p<
8
htno D +>
name D p>
?
public Student9 <
8 ?

public int get0tno9 <
8
return htno>
?
public String get.ame9 <
8
return name>
?
?
public class 3emo-b&
8
public static void main9String args:;<
8
Student i1, i@, o1,o@>
o1 D new Student9@1H, =*reethi=<>
o@ D new Student91@H, =*ush#al=<>
try
8
(ile-utputStream fo D new (ile-utputStream 9=student.dat=<>
1VI
-b&ect-utputStream ofo D new -b&ect-utputStream9fo<>
ofo.write-b&ect9o1<>
ofo.write-b&ect9o@<>
ofo.4ush9<>
ofo.close9<>
(ile,nputStream "D new (ile,nputStream9=student.dat=<>
-b&ect,nputStream o" D new -b&ect,nputStream9"< >
i1 D 9Student<o".read-b&ect9<>
i@ D 9Student<o".read-b&ect9<>
o".close9<>
?
catch9E+ception e<
8 ?
System.out.println9i1<>
System.out.println9i@<>
?
?

Stream/o8eni0er
,t is used to brea# the input stream into to#ens, such as words.
E+ample 1MQ A 3emo of Stream)o#eniPer.
import &ava.io.R>
class 3emo)est
8
public static void main9String args:;< throws E+ception
8
(ileReader f D new (ileReader9="le.t+t=<>
Stream)o#eniPer st D new Stream)o#eniPer9f<>
String s>
while9st.ne+t)o#en9< JD Stream)o#eniPer.))OE-(<
8
if9st.ttype DD Stream)o#eniPer.))O$-R3<
1VQ
System.out.println9st.sval<>
?

f.close9<>
?
?
&ile Streams
)hey are used to store the path and the name of the "le or a 3irectory. ,t
is not useful in retrieving or storing data. )he (ile ob&ect can be used to
create, rename, delete a "le.
/ directory is &ust a list of "les. Each "le in &ava is an ob&ect of (ile class.
(ile class can identify information such as last modi"cation, date, time and
navigation through subdirectories.
.+ample 1>; ) Demo of &ile Class(
import &ava.io.R>
class (ile3emo
8
public static void main9String args:;<
8
(ile f1 D new (ile9="le.t+t=<>
System.out.println9=(ileA = ' f1.get.ame9<<>
System.out.println9 9f1.is(ile9< W ' is a "le=<>
System.out.println9=SiPeA = ' f1.length9<<>
System.out.println9=*athA = ' f1.get*ath9<<>
System.out.println9=*arentA = ' f1.get*arent9<<>
System.out.println9=/bsolute *athA = ' f1.get/bsolute*ath9<<>
System.out.println9=(ile was last modi"edA = ' f1.lastModi"ed9<<>
System.out.println9f1.e+ists9< W =(ile e+ists= A =(ile does not
e+ist=<>
System.out.println9f1.canRead9< W =(ile can be read from= A =(ile
cannot

be read from=<>
System.out.println9f1.can$rite9< W =(ile can be written to= A =(ile
cannot be

written to=<>
1VV
System.out.println9f1.is3irectory9< W =(ile is a directory= A =(ile is
not a directory=<>
System.out.println9f1.is(ile9< W =is a true "le= A ,s not a special "le=<>
System.out.println9f1.is/bsolute9< W =is absolute= A =is not
absolute=<>
?
?
ReEection API
Re4ection /*, is a powerful techni2ue to "nd-out the environment as well as
to inspect the class itself. )he classes of Re4ection /*, are the part of the
pac#age &ava.lang.re4ect and the methods of Re4ection /*, are the parts of
the pac#age &ava.lang.class.
,t allows the user to get the complete information about interfaces, classes,
constructors, "elds and various methods being used.
Retrievin' the class name throu'h ReEection API
/ more generic way, how to retrieve the name of the class that re4ects the
pac#age name by using the get.ame9< method.
import &ava.lang.re4ect.R>
public class Democlass
8
public static void main9String:; args<
8
Class cls D &ava.lang.,nteger.class>
String info>
info D cls.get.ame9<> LL ,t will show &ava.
lang.,nteger
System.out.println9info<>
?
?
Hettin' the method name used in the Application
we describe how to retrieve method name by using the getMethods9< method.
3e"ne a class named =3emomethod= and then create an ob&ect of this class and get
the reference of &ava.util.,nteger.class into it. .ow retrieve the method name by
using the getMethods9< method.
import &ava.lang.re4ect.R>
public class Demomethod
@EE
8
public static void main9Str
ing:; args<
8
Class
cls D &ava.lang.,nteger.class>
Method m
D cls.getMethods9<:E;>
String info>
info D m.get.ame9<>
System.out.println9info<>
?
?
Hettin' information about Constructor
.ow we discuss, how to retrieve the information about the constructor by
using the getConstructors9< method. 3eclare a class =3emocon= and then
create an ob&ect of this class and ta#e the reference of the class
&ava.util.,nteger.class into it. Ma#e a Constructor named con. .ow retrieve
the name of the constructor by using the getConstructors9< method.
import &ava.lang.re4ect.R>
public class Democon
8
public static void main9String:; args<
8
Class cls D &ava.lang.String.class>
Constructor con D cls.getConstructors9<
:E;>
String name>
name D con.get.ame9<> LL,tBll show &av
a.lang.String
System.out.println9name<>
?
?
&indin' out the object of the class
.ow we tell how to retrieve an ob&ect name that re4ects the pac#age name
by using the ob&ect.getClass9< method.
Create a class =3emoob&ect= with an ob&ect Chec#bo+. .ow retrieve an
ob&ect name that re4ects the pac#age name by using the ob.getClass9<
method.
import &ava.lang.re4ect.R>
import &ava.awt.R>
@E1
public lass Demoob&ect8
public static void main9String:; args<
8
Chec#bo+ bos D ne% Chec#bo+9<>
print.ame9bos<>
?
static void print.ame9-b&ect ob<
8
Class cls D ob.getClass9<>
String st D cls.get.ame9<>
System.out.println9st<>
?
?
@E@

Das könnte Ihnen auch gefallen