Java
Java
INDEX
2 SATEESH N
SATEESH N
INTRODUCTION
J av a wa s st a r t e d b y t h e f ol l o wi n g 5 p e o p l e :
J a m e s G o sl i n g , P a t ri c k N a u g h t o n , Mi k e S h er i d a n , C h ri s W r at h , E d F r a n k
T h e se p e o p l e d e si g n e d a l a n g u a g e c a l l e d O A K i n 1 9 7 0 ’ s f o r c o n su m e r
e l e c t r o ni c s. B u t O AK wa s f a i l u r e . T h e l a n g u a g e O A K wa s e n h a n c e d wi t h i n t e r ne t
su p p o r t a n d r e l e a se d i n t h e m a r k e t i n 1 9 9 5 wi t h t h e n e w n a m e J AV A .
I m p o r t an t F e a t u r e s o f J AV A :
O b j e ct O r i e nt e d P r o g r am m i n g l a n g u a g e .
P r o g r a m m i n g su p p o r t f o r i nt e r n e t .
R o b u st p r o g r a m m i n g l a n g u a g e .
Strongly typed language : W e c a n ’ t a s si g n a v a ri a b l e t o a n o t h e r v a ri a b l e , i f
t h e r a n g e f o r t h e ri g h t si d e v a ri a b l e i s l a r g e r t h a n t h e l ef t si d e v a ri a bl e .
Ex : i n t i ; char ch; ch = i; / / e rr o r
i = ch; // ok
A l l o ws u s t o d e si g n a p p l e t s a n d a p p l i c a t i o ns.
S u p p o r t n e t wo r k i n g , d i st ri b u t e d p r o g r am m i ng .
S u p p o r t s m ul t i m e d i a.
P l a t f orm i n d e p e n d e n t .
Interpreted
Secure
Mul ti threaded
Dynamic
Portable
A r c h i t e c t u r e n e u t r al
F e a t u r e s R e m o v e d f r o m C a n d C+ + :
No M o r e T y p e d ef s, D ef i n e s, o r Pr e p r o c e s so r
No M o r e S t r u ct u r e s o r U n i o n s
No Enum s
No M o r e F u n ct i o n s
No M o r e M ul t i p l e I n h e r i t a n c e
No M o r e G ot o S t at em e n t s
No M o r e O p e r a t o r O v e rl o a d i n g
No M o r e A u t om at i c C o e r ci o n s : a ssi g n i n g i n t t o f l o a t wi t h o u t t y p e c a st i n g .
No M o r e P o i nt e r s
3 SATEESH N
SATEESH N
P r o g ra mm i n g i n JA V A
I n j av a t h e p r o g r am s a r e g e n e r a l l y d i v i d e d i n t o 2 c a t e g o r i e s.
i . Appli cati ons & i i . A p pl e t s
i . A p p l i c a t i o n : A n a p p l i c a t i o n i s n o r m al p r og r a m t h a t r u n s o n a n i n d i v i d u a l sy st e m .
i i . A p p l e t : A n a p pl e t i s a p r o g r am d e si g n e d i n J av a a n d wi l l b e p l a c e d o n t h e se rv e r,
t h e a p p l e t wi l l b e d o w n l o a d e d f o rm t h e s e rv e r t o t h e c l i e n t a l o n g wi t h t h e H T M L
d o c u m e n t a n d r u n s i n t h e c l i e n t s W E B b r ow se r . i . e . , a n a p p l et wi l l r u n a s a p a r t o f
W EB d o c u m e nt .
A n a p p l e t c a n c o n t a i n c om p o n e n t s l i k e b u t t o n s, c h e c k b o x e s e t c . ,
A n a p p l e t c a n o p e n c o n n e c t i o n s wi t h n e t wo r k se rv e r s, d a t a b a se se r v e r s e t c,
More generally and less technically an application is a stand-alone program, normally launched from
the command line, and which has more or less unrestricted access to the host system. An applet is a program
which is run in the context of an applet viewer or web browser, and which has strictly limited access to the host
system. For instance an applet can normally not read or write files on the host system whereas an application
normally can.
F i r s t J a va p ro g r am
Example: First.java
c o m p il i n g a J A VA p r o gr a m : W h e n ev e r we c o m pi l e a j av a p r o g r am , t h e
c o m pi l e r c r e a t e s a n i n t e rm e di a t e f i l e , wh i c h c o n t a i n s t h e b yt e c o d e of t h e p r o g r am .
D : \ > j av a c F i r st . j av a ( E nt e r )
C r e at e s f i r st . cl a ss
Byte code
T o r u n , t h e j av a i n t e r p r et e r sh o u l d b e u se d , wh i c h r e a d s t h e i n st r u c t i o n s f r o m
t h e b y t e c o d e a n d ex e c u t e s t h em .
D : \ > j av a F i r st ( Enter )
Ex e c u t e s f i r st . cl a ss
4 SATEESH N
SATEESH N
Your first program, First.java, will simply display "First Java Program". To create this program, you will:
Create a source file. A source file contains text, written in the Java programming language, that you
and other programmers can understand. You can use any text editor to create and edit source files.
Compile the source file into a bytecode file. The compiler, javac, takes your source file and
translates its text into instructions that the Java Virtual Machine (Java VM) can understand. The
compiler converts these instructions into a bytecode file. .
Run the program contained in the bytecode file. The Java interpreter installed on your computer
implements the Java VM. This interpreter takes your bytecode file and carries out the instructions by
translating them into instructions that your computer can understand.
A program written in a high-level language cannot be run directly on any computer. First, it has to be
translated into machine language. This translation can be done by a program called a compiler. A compiler
takes a high-level-language program and translates it into an executable machine-language program. Once
the translation is done, the machine-language program can be run any number of times, but of course it can
only be run on one type of computer (since each type of computer has its own individual machine language). If
the program is to run on another type of computer it has to be re-translated, using a different compiler, into the
appropriate machine language.
There is an alternative to compiling a high-level language program. Instead of using a compiler, which
translates the program all at once, you can use an interpreter, which translates it instruction-by-instruction, as
necessary. An interpreter is a program that acts much like a CPU, with a kind of fetch-and-execute cycle. In
order to execute a program, the interpreter runs in a loop in which it repeatedly reads one instruction from the
program, decides what is necessary to carry out that instruction, and then performs the appropriate machine-
language commands to do so.
Acronym for Java Virtual Machine. An abstract computing machine, or virtual machine, JVM is a
platform-independent execution environment that converts Java bytecode into machine language and
executes it. Most programming languages compile source code directly into machine code that is designed to
run on a specific microprocessor architecture or operating system, such as Windows or UNIX. A JVM -- a
machine within a machine -- mimics a real Java processor, enabling Java bytecode to be executed as actions
or operating system calls on any processor regardless of the operating system. For example, establishing a
socket connection from a workstation to a remote machine involves an operating system call. Since different
operating systems handle sockets in different ways, the JVM translates the programming code so that the two
machines that may be on different platforms are able to connect.
A Java Virtual Machine starts execution by invoking the method main of some specified class, passing
it a single argument, which is an array of strings.
5 SATEESH N
SATEESH N
A platform is the hardware or software environment in which a program runs. We've already
mentioned some of the most popular platforms like Windows 2000, Linux, Solaris, and MacOS. Most platforms
can be described as a combination of the operating system and hardware. The Java platform differs from most
other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.
The Java platform has two components: The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API)
C o m me n t s i n Ja v a C o d e
C o d e c o m m e n t s a r e pl a c e d i n so u r c e f i l e s t o d e sc r i b e wh a t i s h a p p e n i n g i n t h e
c o d e t o so m e o n e wh o m i g h t b e r e a d i n g t h e f i l e , t o c om m e nt - o u t l i n e s o f c o d e t o i so l a t e
t h e so u r c e o f a p r o b l em f o r d e b u g g i n g p u r p o se s, o r t o g e n e r a t e A PI d o c um e n t a t i o n .
T o t h e se e n d s, t h e J av a l a n g u a g e su p p o r t s t h r e e k i n d s of c om m e n t s:
d o u b l e sl a sh e s, C - st y l e , a n d d o c c om m e n t s.
D o u b l e S l a sh e s : D o u b l e sl a sh e s ( / / ) a r e u se d i n t h e C + + p r o g r a m m i n g l a n g u a g e ,
a n d t e l l t h e c om p i l e r t o t r e a t ev e ry t hi n g f r om t h e sl a sh e s t o t h e e n d of t h e l i n e a s t ex t .
Ex: / / A V e r y Si m pl e Ex am p l e cl a ss
C - S t yl e C o m m e n t s : I n st e a d o f d o u b l e sl a s h e s, y o u c a n u s e C - st y l e c o m m e nt s ( / * * / ) t o
e n c l o se o n e o r m o r e l i n e s of c o d e t o b e t r e a t e d a s t e x t .
Ex: / * T h e se a r e C - st y l e c om m e nt s* /
D o c C o m m e n t s : T o g e n e r a t e d o c um e n t a t i o n f o r y o u r p r o g r am , u se t h e d o c c o m m e n t s
( / * * * / ) t o e n c l o se l i n e s o f t ex t f o r t h e j av a do c t o o l t o f i n d . T h e j av a d o c t o o l l o c a t e s t h e
d o c c o m m e n t s e m b e d d e d i n so u r c e f i l e s a n d u se s t h o se c o m m e n t s t o g e n e r a t e A PI
docum entati on.
Ex: / * * T hi s c l a ss d i sp l a y s st u d e n t d e t a i l s a t
* t h e c o n so l e .
*/
6 SATEESH N
SATEESH N
Operators in Java :
Assignment Operators :
Assignment operator : =
Arithmetic operation and then assignment: +=, -=, *=, /=, %=
Bitwise operation and then assignment: &=, |=, ^=
Shift operations and then assignment: <<=, >>=, >>>=
Arithmetic Operators :
Addition : + Subtraction : - Multiplication : *
Division : / Modulo : % Unary minus : - (negation of the value)
Comparison Operators :
Lessthan Greaterthan Lessthan or equalto Greaterthan or equalto equal to not equal to
< > <= >= == !=
Bitwise Operators :
Compliment AND OR XOR ShiftLeft ShiftRight-Signed ShiftRight-unsigned
~ & | ^ << >> >>>
Other Operators
?: Conditional Operator (primitive type) Type Cast
7 SATEESH N
SATEESH N
C o n t ro l St a te me n t s :
S e l e c t i o n St a t em e n t s:
if switch
L o o p S t a t em e n t s:
while do – while for
J u m p S t a t em e nt s:
break continue return
u si n g b r e a k a s a f o rm of g o t o :
S y n t ax : break label;
Example : G o to _ b r e a k . j a v a
Before break.
Note: Although goto is a reserved word, currently the Java language does not support the goto statement. Use
labeled breaks instead.
8 SATEESH N
SATEESH N
D a t a ty p e s i n J a va
Ex: boolean b;
b = true; or b = f al se ;
if(b==true) i f ( b = = f a l se )
if (b) checks f or if(b==true)
int i = 1;
i f (i ) i nv al i d , b e c a u se i i s n o t a B o o l e a n d a t at y p e
i f (i ! = 0 ) ok
KeyWords
abstract assert boolean break byte case
catch char class const continue default
do double else enum extends false
final finally float for goto if
implements import instanceof int interface long
native new null package private protected
public return short static strictfp super
switch synchronized this throw throws transient
true try void volatile while
Notes: -- The goto keyword is not used. (In modern language design, such jumping between
lines of code is considered very bad programming practice.)
-- const is also not used.
-- assert is a new keyword added with Java 1.4
-- enum is a new keyword added with Java 5.0.
Java is case sensitive so in principle you could use these words if you change any character to
uppercase. But that's not recommended!
9 SATEESH N
SATEESH N
Arrays
A n a r r a y i s a c o l l e c t i o n of v al u e s a l l a r e b e l o n g i n g t o t h e sa m e d a t a t y p e a n d
r e f e r r e d wi t h t h e sa m e n a m e t o a c c e ss a n y e l e m e n t of a n a r r a y i t s p o si t i o n sh o u l d
b e g i v e n wh i c h i s k n o wn a s i n d e x . I n j av a a r r a y i n d ex i n g st a r t s f r om 0 .
S y n t ax : data type v a ri a bl e n am e [ ] ;
Ex: int arr[ ];
I n t h e a b ov e st a t em e n t t h e a r r a y wi l l b e c re a t e d wi t h o u t a n y si z e . W e sh o u l d
a l l o c at e m em o r y u si n g t h e n e w o p e r a t o r b ef o r e a c c e ssi n g t h e a r r a y .
arr[0] = 10;
arr[1] = 20;
i f we d o n ’ t a ssi g n o r r e a d t h e v al u e s f o r r e m ai n i n g l o c a t i o n s, b y d ef a u l t t h e y wi l l
b e f i l l e d wi t h 0 ’ s.
P i ct o r i al r e p r e se n t a t i o n :
arr
10 20
0 1 2 3 4
i n t a rr [ ] = n e w i n t [ 5 ] ;
i nt [ ]arr = new i nt[5];
length property : E a c h a r r a y c o n t a i n s t he l e n g t h p r o p e r t y , wh i c h c o n t a i n s t h e n o . o f
e l em e n t s i n t h e a r r a y .
E x : Sy st e m . o u t . p ri n t l n ( a r r . l e n g t h ); / / d i sp l a ys t h e n o . of l o c a t i o n i . e. , 5 f o r t h e a b ov e ex .
I n i t i al i z i n g a n a r r a y : W h e n we i n i t i a l i z e an a r r a y a t t h e t i m e of c r e a t i n g t h e a r r a y t h e
n e w o p e r a t o r sh o u l d n o t b e g i v e n .
/ / E x a mp l e : O n e D Ar r I n i . j a v a
10 SATEESH N
SATEESH N
/ / E x a mp l e : O n e D Ar r . j a v a
class OneDArr
{
public static void main(String args[]) Out put:
{
int a[],i; value of a[0] is: 10
a=new int[5]; value of a[1] is: 20
a[0]=10; value of a[2] is: 0
a[1]=20; value of a[3] is: 0
value of a[4] is: 0
for(i=0;i<a.length;i++)
{
System.out.println("value of a["+i+"] is: "+a[i]);
}
}
}
T w o – D i m e n s io n a l A r r a y s : I n J av a , i n a 2 - d a r r a y a l l t h e r o w s n e e d n o t
c o n t a i n t h e sa m e n o . of c o l um n s.
int a[ ] [ ] ;
a = new i nt [3] [ ]; / / 3 r o ws
a[0][0] = 10;
a[0][1] = 20;
P i ct o r i al r e p r e se n t a t i o n :
a
0 0,0 0,1 0,2 0,3
0 1 2 3 4
i n t a[ ] [ ] = n e w i n t [ 3 ] [ 5 ] ;
i n t [ ] [ ] a = n e w i n t [ 3] [ 5 ] ;
I n i t i al i z i n g a 2 – D A r r a y :
/ / E x a mp l e : T w o D Aa r r I n i . j a v a
// initialize the 2-d array and display the elements in matrix format
class TwoDAarrIni
{
public static void main(String args[])
{
int a [ ] [ ] = { { 1, 2, 3, 4},
{ 1, 2, 3},
{ 1, 2, 3, 4, 5} } ;
11 SATEESH N
SATEESH N
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print("\t a["+i+"]["+j+"] : "+a[i][j]);
}
System.out.println(); Out put:
}
} a[0][0] : 1 a[0][1] : 2 a[0][2] : 3 a[0][3] : 4
} a[1][0] : 1 a[1][1] : 2
a[2][0] : 1 a[2][1] : 2 a[2][2] : 3
/ / E x a mp l e : T w o D Ar r . j a v a
// assigning elements into the array and display the elements
class TwoDArr
{
public static void main(String args[])
{
int a[][],i,j,k=1;
a=new int[3][];
a[0]=new int[4];
a[1]=new int[2];
a[2]=new int[3];
for(i=0;i<a.length;i++)
{
for(j=0;j<a[i].length;j++) Out put:
{
a[i][j]=k; a[0][0] : 1 a[0][1] : 2 a[0][2] : 3 a[0][3] : 4
k++; a[1][0] : 5 a[1][1] : 6
} a[2][0] : 7 a[2][1] : 8 a[2][2] : 9
}
for(i=0;i<a.length;i++)
{
for(j=0;j<a[i].length;j++)
{
System.out.print("\t a["+i+"]["+j+"] : "+a[i][j]);
}
System.out.println();
}
}
}
a r g s a rr a y : T h e a r g s a r r a y wh i c h wa s g i v e n i n t h e m ai n ( ) c o n t ai n s a l l t he
a r g u m e n t s g i v e n b y t h e u se r a t t h e c om m a nd l i n e .
/ / E x a mp l e : C o m m Ar g s . j a v a
//Give the command ling arguments at the time executing the program and display
them
class CommArgs
{
public static void main(String args[])
{
System.out.println("Total no. of Argument(s): "+args.length);
System.out.println();
12 SATEESH N
SATEESH N
if(args.length<1)
{
System.out.println("Insufficient Arguments - should give min. 1 arg");
return;
}
Out put:
for(int i=0;i<args.length;i++)
{ Total no. of Argument(s): 3
System.out.println("args["+i+"]: "+args[i]); args[0]: red
} args[1]: green
} args[2]: blue
}
C l a s s : A cl a ss i s a c o l l e c t i o n of D a t a m e m b e r s (v a r i a bl e s) t h a t c o n t ai n i nf o rm at i o n
n e c e s sa r y t o r e p r e se n t t h e c l a ss a n d M e t h o d s ( f u n c t i o n s) t h a t p e rf o rm o p e r a t i o n s o n
t h e d a t a m em b e r s o f t h e c l a ss. . O n c e a c l a s s i s c r e a t e d , a n y n o . o f i n st a n c e s o f t h e
c l a ss c a n b e c r e a t e d i n t h e p r o g r a m . The definition of a class creates a user-defined data type and
names the members of the class. It does not allocate memory for any objects of that type! That is done by
operator new.
O b j e c t : O bj e c t i s a n i n st a n c e of t h e cl a s s o r a n o b j e c t i s t h e b a si c r u n - t i m e e n t i t y .
// Example: Cl a s s a n d O b j . j a v a
// Define a class and create an instance for the class, and access the member
data and member functions of the class through the instance.
class Student
{
int sno; String sname;
void assign()
{
sno=10;
sname="Sateesh";
}
void display()
{
System.out.println("\n Student no. : "+sno+"\n Student name: "+sname);
}
}
class ClassandObj
{
public static void main(String args[])
{ Out put:
Student s;
Student no. : 10
s= new Student(); Student name: Sateesh
s.assign(); Student no. : 10
s.display(); Student name: Sateesh
Student t= new Student();
t.assign();
t.display();
}
}
13 SATEESH N
SATEESH N
C O N S TR U C T O R S
A c o n st r u c t o r i s a sp e c i a l m em b e r f u nc t i o n wh i c h i s c a l l e d a u t om at i c a l l y
wh e n e v e r a n i n st a n c e o f t h e c l a ss i s c r e a t e d . T h e n a m e o f t h e c o n st r u c t o r sh o u l d b e
e q u a l t o t h e n a m e o f t h e c l a ss. C o n st r u c t o r s a r e g e n e r a l l y u se d f o r i n i t i a l i zi n g t h e
v a ri a b l e s of t h e cl a ss. A c o n st r u c t o r m ay o r m a y n o t t a k e a n y a r g um e n t s, b u t a
c o n st r u c t o r wi l l n o t r e t u r n a n y v al u e . C o n st r u c t o r s c a n b e ov e r l o a d e d .
t h is : t h i s k e y wo r d , t h e t hi s r ef e r e n c e v a r i a b l e al wa y s r e f e r s t o t h e c u r r e n t cl a ss. I t
c a n b e a p p l i e d i n 3 c a t e g o r i e s.
i . t o r ef e r t o t h e f u n ct i o n s o f t h e c u r r e n t cl a s s. Ex : t hi s. d i sp l a y ( ) ;
i i . t o r ef e r t o t h e v ar i a bl e s o f t h e c u r r e n t cl a s s. Ex : t hi s. sn o
i i i . t o c al l a c o n st r u c t o r f r om a n o t h e r c o n st r u c t o r . Ex : t h i s( );
/ / E x a mp l e : C o n s t r u c to r 1 . j a v a
class Vals
{
int x,y;
void dispx()
{
System.out.println("\n val of X: "+x);
}
void dispy()
{
System.out.println("\n val of Y: "+y);
}
void dispxy()
{
this.dispx(); // or dispx();
this.dispyx(); // or dispy();
}
}
14 SATEESH N
SATEESH N
class Constructor1
{
public static void main(String args[]) Out put:
{
val of x : 10
Vals s = new Vals(10,20); val of y : 20
s.dispxy();
}
}
// Example : Co n s t ru c t o r 2 . j a v a
// ii. to refer to the variables of the current class. & constructor over
loading, 1st constructor doesn’t contain arguments and 2nd constructor contain
two arguments. Ex: this.sno
Overloading Constructors
class Student
{
int sno; String sname;
Student() // 1st constructor , used when no arguments specified
{
sno=11;
sname="Raj";
}
Student(int stno,String stname) //2nd constructor,used when arguments specified
{
this.sno=stno;
this.sname=stname;
}
void accept(int stno, String stname)
{
this.sno=stno;
this.sname=stname;
}
void display()
{
System.out.println("\n Student no. : "+sno+"\n Student name: "+sname);
}
}
class Constructor2
{
public static void main(String args[])
{
/ / E x a mp l e : C o n s t r u c to r t t o Co n s t ru c t o r . j a v a
class Vals
{
int x,y;
Vals(int p,int q)
{
this.x=p;
this.y=q;
}
Vals()
{
this(10,20);
}
void display()
{ Out put:
System.out.println("\n Val of X: "+x+"\n Val of Y: "+y);
} Val of x : 10
} Val of y : 20
Vals s = new Vals( ); //calls 2nd constructor which calls 1st constructor
Vals t = new Vals(50,60); //calls 1st constructor
s.display();
t.display();
}
}
S t a t i c me m be r s & S t a ti c me t ho d s
S t a t i c m e m b e r s : W h e n ev e r a v a ri a b l e i s sp e c i f i e d a s st a t i c su c h v a ri a bl e wi l l be
c r e a t e d o n l y o n c e i n t h e m e m o r y f o r a l l t h e i n st a n c e s o f t h e c l a ss. A l l t h e i n st a n c e s o f
t h e c l a ss wi l l sh a r e t h e sa m e v al u e of t h e st a t i c v a ri a b l e. A st a t i c v a ri a b l e of a cl a ss
c a n a l so b e a c c e ssi b l e u si n g t h e n am e of t he c l a ss.
Out put:
/ / E x a m p l e : S t a t i cM e m b e r . j a v a
Val of z : 77
class Vals
Val of z : 99
{
int x,y; Val of s.x : 10
static int z=77; Val of s.y : 20
} Val of s.z : 99
class StaticMember
Val of t.x : 50
{
Val of t.y : 60
public static void main(String args[])
Val of t.z : 99
{
System.out.println("\n Val of Z: "+Vals.z); Val of z : 99
16 SATEESH N
SATEESH N
Vals s = new Vals();
Vals t = new Vals();
S t a t i c m e t h o d s : A st a t i c f u n c t i o n of a c l as s c a n b e a c c e s si b l e u si n g t h e n a m e o f t h e
c l a ss a l so . A st a t i c f u n c t i o n c a n a c c e ss o n l y o t h e r st a t i c m em b e r of t h e cl a ss.
/ / E x a m p l e : StaticMethod. j a v a
class Vals
{
int x,y;
static int z=77;
void display()
{
System.out.println("\n Values are: "+x+"\t"+y+"\t"+z);
}
class StaticMethod
{
public static void main(String args[])
{
Vals.print(); //calling static function using class name i.e., vals
Value is : 77
s.x=10; s.y=20; s.z=99;
t.x=50; t.y=60; Values are : 10 20 99
17 SATEESH N
SATEESH N
S t a t i c B lo c k s
I f a cl a ss c o n t a i n s st a t i c b l o ck s a l l su c h b l o c k s wi l l b e e x e c ut e d f i r st wh e n e v e r
t h e c l a ss i s l o a d e d .
// Example : StaticBlocks.java
Static initializer blocks are used to execute some piece of code before executing any constructor or
method while instantiating a class. Static initializer blocks are also typically used to initialize static fields.
Class2.java
18 SATEESH N
SATEESH N
Garbage Collection
When an object no longer has any valid references to it, it can no longer be accessed by the program it is
useless, and therefore called garbage.
Java performs automatic garbage collection periodically, returning an object's memory to the system for
future use. This process is called garbage collection.
In other languages, the programmer has the responsibility for performing garbage collection
An object is eligible for garbage collection when there are no more references to that object.
References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can
explicitly drop an object reference by setting the variable to the special value null. Remember that a program
can have multiple references to the same object; all references to an object must be dropped before the object
is eligible for garbage collection.
F i n al i ze r s
• J av a al l o ws y o u t o d e f i n e a m e t h o d t ha t i s a u t o m at i c al l y c al l e d b ef o r e o b j e ct i s
returned to heap.
• F i n a l i z e r: M e t h o d t h a t al l o ws r e so u r c e s t o b e f r e e d b e f o r e o bj e c t i s g a r b a g e
c o l l e ct e d .
v oi d f i n al i z e ( )
{ . . . }
• M u st b e c al l e d f i n a l i z e ( ).
• F i n al i z e r n o t al l o we d t o h av e a r g um e n t s.
• I m m e d i at e l y b ef o r e o b j e ct i s g a r b a g e c o l l e c t e d , J av a r u n t i m e wi l l c a l l f i n al i z e ( ) ;
• F i n al i z e r sh o u l d b e u se d o n l y a s a l a st - d i t c h ef f o r t t o r e c ov e r a sse t s b e f o r e t h e y a r e
l o st f o r ev e r .
• M o st J av a c l a sse s d o n ’ t r e q u i r e a f i n al i z e m et h o d .
* J av a ’ s g a r b a g e c o l l e c t i o n m e c h a n i sm t a k es c a r e o f m em o r y l e a k s.
* Finalizer is Not a Destructor
Example: Finalizer_Ex1.java
class TestClassA
{
protected void finalize() // override finalization method
{
System.out.println("Finalizing TestClassA object");
}
}
class TestClassB
{
protected void finalize() // override finalization method
{
System.out.println("Finalizing TestClassB object");
}
}
19 SATEESH N
SATEESH N
class Finalizer_Ex1
{
//controlling class
public static void main(String[] args)
{
//Guarantee finalization of all objects on exit
System.runFinalizersOnExit(true);
Output :
//Instantiate two objects to be finalized
TestClassA objA = new TestClassA(); Terminating....
TestClassB objB = new TestClassB(); Finalizing TestClassB object
Finalizing TestClassA object
System.out.println("Terminating....");
}
}
The Java runtime system performs memory management tasks for you. When your program has
finished using an object, that is, when there are no more references to an object, the object is finalized
and is then garbage collected. These tasks happen asynchronously in the background. However, you can
force object finalization and garbage collection using the appropriate method in the System class.
Finalizing Objects :
Before an object is garbage collected, the Java runtime system gives the object a chance to clean up
after itself. This step is known as finalization and is achieved through a call to the object's finalize method.
You can force object finalization to occur by calling System's runFinalization method.
System.runFinalization();
This method calls the finalize methods on all objects that are waiting to be garbage collected.
System.gc();
You might want to run the garbage collector to ensure that it runs at the best time for your program
rather than when it's most convenient for the runtime system to run it. For example, your program may wish to
run the garbage collector right before it enters a compute or memory intensive section of code or when it
knows there will be some idle time.
Note that the garbage collector requires time to complete its task. The amount of time that gc requires
to complete varies depending on certain factors: How big your heap is and how fast your processor is, for
example. Your program should only run the garbage collector when doing so will have no performance impact
on your program.
20 SATEESH N
SATEESH N
E x a m p l e : GC_Finalizer_Ex.j a v a
/** Example shows garbage collector in action, Note that the finalize() method of
object GC1 runs without being specifically called and that the id's of garbage
collected objects are not always sequential. */
class GC_Finalizer_Ex
{
public static void main(String[] args)
{
Runtime rt = Runtime.getRuntime();
System.out.println("Available Free Memory: " + rt.freeMemory());
for(int i=0; i<10000; i++ )
{
GC1 x = new GC1(i);
}
System.out.println("Free Memory before call to gc(): " + rt.freeMemory());
System.runFinalization();
System.gc();
System.out.println("Free Memory after call to gc(): " + rt.freeMemory());
}
}
class GC1
{
String str;
int id;
GC1(int i)
{
this.str = new String("abcdefghijklmnopqrstuvwxyz");
this.id = i;
}
21 SATEESH N
SATEESH N
Overloading Methods
• D i f f e r e n t m e t h o d s c a n h av e t h e sam e n a m e
• T h e si g n a t u r e of a m et h o d i s t h e m e t h o d’ s n a m e a n d t h e p a r am e t e r t y p e s ( i n cl u d i n g
t h e o r d e r of t h e p a r am et e r s)
• I n a cl a ss, a l l m et h o d s m u st h av e di f f er e n t si g n a t u r e s
• E . g. , t h e a b s m e t h o d i n t h e M a t h cl a ss
class Person_name
{
/* Overloaded Methods */
return fn+space+ln;
} // method get_fullname (0 arguments)
return fn+space+ln;
} // method get_fullname (1 argument)
I n J av a, we a c c o m p l i sh e n c a p su l a t i o n t h ro u g h t h e a p p r o p r i a t e u se o f v i si bi l i t y
m o di f i e r s ( a m o di f i e r i s a J av a r e se rv e d wo r d t h a t sp e c i f i e s p a r t i c ul a r c h a r a c t e ri st i c s
o f a m e t h o d o r d a t a v al u e ) .
A n a c c e ss sp e c i f i e r (v i si b i l i t y m o d i f i e r s) d ef i n e wh o i s a b l e t o u se t h i s m e t h o d .
A c c e ss sp e c i f i e r s c a n b e :
p u b l i c wh e n a n y o n e c a n c a l l t hi s m e t h o d ( p u b l i c m e t h o d s a r e a l so c a l l e d se rv i c e
m et h o d s; A m e t h o d c r e a t e d si m p l y t o a ssi st a se r v i c e m et h o d i s c a l l e d a su p p o r t
m et h o d ) .
p r i v a te wh e n o n l y m et h o d s i n t h e sam e cl a s s a r e p e r m i t t e d t o u se t hi s m et h o d .
p r o t e ct e d wh e n m e t h o d s i n t h i s c l a s s a n d m e t h o d s i n a n y su b c l a s se s m a y u se t h i s
m et h o d .
( n o th i n g ) wh e n a n y c l a sse s i n t h i s p a r t i cu l a r p a c k a g e o r di r e c t o r y m a y a cc e ss t h i s
m et h o d .
Data Scope :
The scope of data is the area in a program in which that data can be used (referenced).
Data declared at the class level can be used by all methods in that class.
Data declared within a method can only be used in that method.
Data declared within a method is called local data.
R e fe re n ce s :
A n o b j e c t r ef e r e n c e h ol d s t h e m em o r y a d d r e s s o f a n o bj e c t .
C l a ssA a = n e w C l a ssA ( ) ;
C l a ss b ;
F o r o b j e ct r ef er e n c e s, a s si g n m e n t c o p i e s t he m em o r y l o c a t i o n :
b = a;
T wo o r m o r e r ef e r e n c e s t h a t r ef er t o t h e sa m e o b j e c t a r e c al l e d a l i a se s o f e a c h o t h e r.
Before After
a b a b
23 SATEESH N
SATEESH N
c a l l b y v al ue a n d c a ll b y r e fere n ce : W hi l e se n d i n g a r g u m e n t s t o a
f u n ct i o n si m pl e d a t a t y p e s su c h a s i n t , f l oa t e t c . , wi l l b e p a sse d b y v a l u e s. W h e r e as
o b j e c t s a r e p a ss e d b y r ef e r e n c e .
Example : c al v a l c a l r e f . j a v a
class A
{
int x,y;
}
class B
{
public static void f1(int x,int y)
{
// x and y will be received by values
x = x+10;
y = y+20;
class calvalcalref
{
public static void main(String args[])
{
int x=10,y=20;
A a = new A();
a.x=10;
a.y=20;
System.out.println();
24 SATEESH N
SATEESH N
The topic of parameter passing in Java seems to cause much confusion. Is it by value, by reference, or
both ? Search the Internet or read a few Java books and you will probably get even more confused. You will
typically come across a statement that "primitive types are passed by value, but objects are passed by
reference". Many people will read such a statement and end up with completely the wrong understanding of
what happens. Let me state clearly that:
In Java, parameters are always passed by value. Even references to objects are passed by value.
Java is pass-by-value,
To understand what this means, you first need to be clear about the distinction between a reference
variable and an object. In a Java statement such as Button b = new Button( ); the variable b is not an
object, it is simply a reference to an object (hence the term reference variable). Figure 1 illustrates this.
b Object
button
object
So what happens when we call a method and "pass in an object" ? Well, let's be clear about one thing
- we are not passing in an object, rather we are passing in a reference to an object, and it is the reference to
an object that gets passed by value. Consider a method declared as
methodX(b);
then the value of the variable b is passed by value, and the variable y within methodX receives a copy of this
value. Variables b and y now have the same value. However, what does it mean to say that two reference
variables have the same value ? It means that both variables refer to the same object. This is illustrated in
Figure 2.
Object
b
button
object
y
Figure 2. Two different reference variables refer to the one button object.
As figure 2 illustrates, an object can have multiple references to it. In this example, we still have just
the one object, but it is being referenced by two different variables. So what is the consequence of this ? It
means that within methodX you can update the button object via variable y e.g. y.setLabel("new text"); and the
calling routine will see the changes (as variable b refers to the same object), but - and this is the important bit -
if you change the value of the variable y within methodX so that it refers to a different object, then the value of
variable b within the calling method remains unchanged, and variable b will still refer to the same button object
that it always did.
25 SATEESH N
SATEESH N
For example, if in methodX we had y = new Button("another button"); we get the situation shown in Figure 3.
b Object y Object
button button
object object
With the two variables now referencing different objects, if methodX now updates the button which y
now refers to e.g.
y.setLabel("xxx");
then the original button object to which b refers to is unaffected by any such changes.
You may find that drawing diagrams such as Figures 1 to 3 will help your understanding of what is really
happening when you pass parameters into a method in Java. The example code below demonstrates how
Java parameter passing works.
Example : PassByValue.java
import java.awt.*;
26 SATEESH N
SATEESH N
//update the button object that both y and b refer to
y.setLabel("BBB");
System.out.println("The value of y's label is " + y.getLabel());
//make y reference a different object - doesn't affect variable b
y = new Button("CCC");
System.out.println("The value of y's label is " + y.getLabel());
//updating button that y now references has no affect on button referenced by b
y.setLabel("DDD");
System.out.println("The value of y's label is " + y.getLabel());
}
The value of i is 5
In methodZ
The value of j is 5
The value of j is 6
Back in main
The value of i is 5
27 SATEESH N
SATEESH N
U s i n g O b j ec t s a s P a r a m e te r a n d Re tu r n i n g O b je c t s
Example: Use_Obj_as_Param_and_Returning_Obj.java
class Interval
{ // instance variables
double min;
double max;
Interval() { } // empty constructor
Interval(double x,double y)
{
min = x;
max = y;
} // constructor that assigns instance variables
public Interval addint(Interval b)
{
double tempmin = min + b.min;
double tempmax = max + b.max;
return (new Interval(tempmin,tempmax));
} // method addint (add intervals)
public void print(String mesg)
{
System.out.println(mesg+" ["+min+","+max+"]");
} // method print (print interval)
} // class Interval
28 SATEESH N
SATEESH N
I n n e r C l a s se s
If you've done much Java programming, you might have realized that it's possible to declare classes that are
nested within other classes.
Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler
treats the class just like any other top-level class. Any class outside the declaring class accesses the nested
class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes
implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested
top-level variety.
Member classes - Member inner classes are just like other member methods and member variables and
access to the member class is restricted, just like methods and variables. This means a public member class
acts similarly to a nested top-level class. The primary difference between member classes and nested top-
level classes is that member classes have access to the specific instance of the enclosing class.
Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within
the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to
implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected,
private, and static are not usable.
Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous
classes have no name, you cannot provide a constructor.
class Base
{
void method1()
{
}
void method2()
{
}
}
class A // normal class
{
static class B // static nested class
{
}
class C // inner class
{
}
void f()
{
class D // local inner class
{
}
}
void g()
{
// anonymous class
Base bref = new Base()
{
void method1()
{
}
};
}
}
29 SATEESH N
SATEESH N
A nested class that is not declared static is called an inner class. In the example code, B is a nested class,
while C is a nested class and an inner class.
An inner class object is scoped not to the outer class, but to the instantiating object.
Even if the inner class object is removed from the outer class object that instantiated it, it
retains the scoping to its creator.
If an object has a reference to another object's ("parent object"'s) inner class object, the inner
class object is dealt with by that object as a separate, autonomous object, but in fact, it still
has access to the private variables and methods of its parent object.
An inner class instantiation always remembers who it's parent object is and if anything
changes in the parent object (e.g. one of its property's value changes), that change is
reflected in all its inner class instantiations.
Example : InnerClass_Ex1.java
class class1
{
// this value can access in inner classes and sub classes
int outer_var1 = 10;
void outer_method()
{
Inner1 inner1obj1 = new Inner1();
inner1obj1.inner1_method();
Inner2 inner2obj1 = new Inner2();
inner2obj1.inner2_method();
}
class Inner1
{
// variables and methods of this class can access within this class only
int inner1_var = 100;
void inner1_method( )
{
System.out.println("Inner1 class method");
System.out.println("Accessing outer_var1: "+outer_var1);
}
}
class Inner2
{
// variables and methods of this class can access within this class only
int inner2_var = 200;
void inner2_method( )
{
System.out.println("Inner2 class method");
System.out.println("Accessing outer_var1: "+outer_var1);
}
}
}
30 SATEESH N
SATEESH N
class class2 extends class1
{
void class2_method()
{
System.out.println("class2 method ");
System.out.println("Accessing outer_var1 of class1: "+outer_var1);
}
} Output:
class2 method
public class InnerClass_Ex2 Accessing outer_var1 of class1: 10
{ Inner1 class method
public static void main(String[] args) Accessing outer_var1: 10
{ Inner2 class method
class2 obj = new class2(); Accessing outer_var1: 10
obj.class2_method();
// obj.outer_method(); /* that inturn calls inner1_method(),
inner2_method() methods */
Example: actionPerformed events utilize the Observer-Observable pattern -- An instance of the observer is
added to the observable. JBuilder creates an anonymous inner class to give to the button as its
ActionListener.
Anonymous inner classes are scoped inside the private scoping of the outer class. They can access
the internal (private) properties and methods of the outer class.
References to an inner class can be passed to other objects. Note that it still retains its scoping.
Anonymous inner classes must use the no parameter constructor of the superclass.
Since an object made from the inner class has a "life" independent of its outer class object, there is a
problem with accessing local variables, especially method input paramenters.
Initialize a property that the inner class then uses -- properties have the cross-method-call
persistence that local variables lack.
Make the local variable "final" -- compiler will automatically transfer the value to a more
persistent portion of the computer memory. Disadvantage: the value cannot be changed.
Usages:
Very useful for controlled access to the innards of another class.
Very useful when you only want one instance of a special class.
31 SATEESH N
SATEESH N
One key idea is that an anonymous class has no name. An anonymous class is a subclass of an
existing class (Base in this example) or an implementation of an interface.
Because an anonymous class has no name, it cannot have an explicit constructor. Neither can an
anonymous class be referred to outside its declaring expression, except indirectly through a superclass or
interface object reference. Anonymous classes are never static, never abstract, and always final. Also, each
declaration of an anonymous class is unique.
For example, the following code declares two distinct anonymous classes:
Nested Classes
Inner Classes
An inner class is a type of nested class that is not explicitly or implicitly declared static.
33 SATEESH N
SATEESH N
I N H ER I T A N C E
I n h e r i t a n c e i s t h e p r o c e s s o f c r e a t i n g n e w c l a s se s f r om ex i st i n g c l a sse s. T h e
c l a ss wh i c h i s b e i n g i n h e ri t e d i s k n o wn a s ‘ su p e r c l a s s ‘ a n d t h e c l a s s w h i c h i n h e ri t s
t h e o t h e r c l a s s i s k n o wn a s ‘ su b c l a ss ‘ . T o i n h e r i t a c l a ss i n t o a n o t h e r c l a s s, t h e k e y
wo r d ‘ e x t e n d s ‘ sh o u l d b e u se d .
c l a ss A A su p e r c l a s s
{
c l a ss B ex t e n d s A B su b c l a ss
{
J av a su p p o r t s m ul t i l ev e l I n h e ri t a n c e b u t d o e s n o t su p p o r t m u l t i pl e I n h e r i t a n c e .
A A B
M u l t i pl e I n h e ri t a n c e
B M ul t i l ev el I n h e r i t a n c e C n o t su p p o r t e d b y J av a
su p p o r t e d b y J av a
C
E x a m p l e : I n h e r i t en c e . j a v a
class common
{
int no;
String name;
}
class student extends common
{
int tfee;
void accept()
{
no=10;
name="Sateesh";
tfee=5000;
}
void display()
{
System.out.println("\n Student No. : "+no+"\n Student Name: "+name+"\n Total
Fee :"+tfee);
}
}
class customer extends common
{
int qty; float price,totbil; String item;
void accept()
{
no=101;
name="Raj";
item="SAMSUNG key board";
qty=2;
price=150;
totbil=price*qty;
}
34 SATEESH N
SATEESH N
void display()
{
System.out.println("\n Customer No. : "+no+"\n Customer name : "+name+"\n
Item purchased: "+item+"\n Quantity : "+qty+"\n Price : "+price+"\n
Total Bill : "+totbil);
}
}
C o n s t r u c to r s i n th e c a s e o f I n h e r i t a n c e :
W h e n ev e r a su b c l a ss o b j e c t i s c r e a t e d t h e su p e r c l a s s c o n st r u c t o r wi l l b e c a l l e d
f i r st a n d t h e n t h e su b c l a s s c o n st r u c t o r . I f t h e r e a r e m o r e t h a n o n e su p e r c l a s se s
c o n st r u c t o r s wi l l b e c al l e d i n t h e o r d e r of I n h e r i t a n c e .
Ex: c l a ss A
{
c l a ss B ex t e n d s A
{
Ex ec u t i o n t a k e s p l a c e f r om b ot t om t o t o p
}
c l a ss C e x t e n d s B
{
S u p er k e y wo r d : T h e ‘ t h i s ‘ r e f e r e n c e v a ri a b l e al wa y s r e f e r s t o t h e c u r r e n t c l a ss .
A n d t h e ‘ su p e r ‘ r e f e r e n c e v a r i a bl e a l wa y s r e f e r s t o t h e i m m e di a t e su p e r c l a s s. T h e
‘ su p e r ‘ k e y wo r d c a n b e a p p l i e d i n 3 c a t e go r i e s.
i. T o r ef e r t o t h e v a ri a b l e s of t h e su p e r c l a ss.
ii. T o r ef e r t o t h e m e t h o d s of t h e su p e r c l a ss.
iii. T o c al l a su p e r c l a ss c o n st r u c t o r f r om t h e su b c l a ss c o n st r u c t o r s.
35 SATEESH N
SATEESH N
E x a m p l e : C o n s t r c t o r s _ I n h e r i t e n c e. j a v a
/ / Pr o g r am f o r i . T o r ef e r t o t h e v a r i a bl e s o f t h e su p e r cl a ss.
i i . T o r ef e r t o t h e m et h o d s o f t he su p e r c l a ss.
class A
{
int x; // variable
void display() // method
{
System.out.println("’x’ Value of Class A is: "+x);
}
}
class B extends A
{
int x;
B(int a,int b)
{
super.x=a;
this.x=b;
}
void display()
{
super.display(); //calls display() of class A
System.out.println("’x’ Value of Class B is: "+x);
}
}
class C o n st r c t o r s_ I n h e r i t e n c e
{ Out put:
public static void main(String args[])
{ ’x’ Value of Class A is: 10
B b = new B(10,20); ’x’ Value of Class B is: 20
b.display();
}
}
Example : Co n s t r u c t o rT O Co n s t ru c t o r _ I n h e r i t e n c e . j a v a
/ / Pr o g r am f o r i i i . T o c al l a su p e r c l a ss c o n st r u c t o r f r om t h e su b c l a ss c o n st r u c t o r s.
class A
{
int x,y;
A(int x,int y) // constructor of class A
{
this.x=x;
this.y=y;
}
}
class B extends A
{
int z;
B(int a,int b,int c) // constructor of class B
{
super(a,b); // sends the 1st 2 arguments to the super class constructor
this.z=c;
}
36 SATEESH N
SATEESH N
void display()
{
System.out.println("Values are: "+x+" "+y+" "+z);
}
}
NOTE: C a l l i n g a ‘ s u p e r c l a s s ‘ c o n st r u c t o r f r om t h e ‘ su b c l a s s ‘ c o n st r u c t o r u si n g t h e
‘ su p e r ‘ i n a f u n ct i o n st yl e m u st b e t h e f i r st st a t e m e nt i n t h e ‘ su b c l a ss ‘ c o n st r u c t o r .
Ex : B ( )
{
su p e r ( ) ;
t h i s. z= c ;
}
O v e r ri d d e n Me t ho d s
W h e n ev e r a f u n ct i o n of su p e r c l a ss a l so d e f i n e d i n t h e su b c l a s s, t h e n t h e
f u n ct i o n i s k n o wn a s o v e r ri d d e n .
Ex: c l a ss A
{
void f 1( )
{
}
}
c l a ss B ex t e n d s A
{
v oi d f 1 ( ) / / ov e r ri d d e n
{
}
}
I n J av a a r e f e r e n c e v a r i a bl e of ‘ su p e r c l a s s ‘ c a n r e f e r t o a n i n st a n c e o f ‘ su b
c l a ss ‘ a n d i s a b l e t o c al l t h e ‘ ov e r ri d d e n ‘ f u n ct i o n.
Ex: A a = new A( );
B b = new B( );
a . f 1 ( );
b . f 1 ( );
A r; / / r i s r ef e r e n c e v a r i a bl e of su p e r c l as s A
37 SATEESH N
SATEESH N
a
r = a;
r
r . f 1 ( ); / / c al l s a . f 1 ( );
b
r = b;
r
r . f 1 ( ); / / c al l s b. f 1 ( ) ;
D y n a mi c M e th o d D i s p a t ch :
S y s t e m . i n . r e a d ( ) : R e a d s a c h a r a c t e r f ro m t h e k e y b o a r d a n d r e t u r n s t h e “ A S C I I
v al u e “ of t h a t c h a r a c t e r.
Ex: i n t c h = S y st em . i n . r e a d ( );
S y st em . o u t . p ri n t l n ( c h ) ;
E x a m p l e : D y n a mi c M e t h o d Di s p a t c h . j a v a
/ / w. a . p t o a c c e p t a c h oi c e f r om t h e u se r , i f t h e c h o i c e i s ‘ 1 ’ a c c e p t a n d d i sp l a y st u d e n t
d e t a i l s, i f t h e c h o i c e i s ‘ 2 ’ a c c e p t a n d di sp l a y c u st o m e r d e t a i l s.
class common
{
void accept()
{
}
void display()
{
}
}
class student extends common
{
int sno; String sname; int tfee;
void accept() // over ridden function
{
sno=10;
sname="Sateesh";
tfee=1500;
}
void display() // over ridden function
{
System.out.println("Student Details : "+sno+" "+sname);
}
}
class customer extends common
{
int cno; String cname,product; int qty,rate;
void accept() // over ridden function
{
cno=20;
cname="Raj";
product = "Mouse";
qty=2;
rate=150;
}
38 SATEESH N
SATEESH N
void display() // over ridden function
{
System.out.println("Customer Details: "+cno+" "+cname+" "+product+" "+qty+"
"+rate);
}
}
class D y n a m i c M et h o d D i sp a t c h
{
public static void main(String args[]) throws Exception
{
char ch;
common r;
System.out.println("Enter 1: Student 2: Customer\n ");
ch = (char) System.in.read();
Out put:
if(ch=='1')
r = new student(); Enter 1: Student 2: Customer
else 1
r = new customer(); Student Details : 10 Sateesh
Example : Inheritence_Ex1.java
class common
{
void accept( )
{
System.out.println("method accept() in class common");
}
}
class student extends common
{
void display()
{
System.out.println("method display() in class student");
}
}
public class Inheritence_Ex1 Output :
{ Throgh object "r"
public static void main(String[] args) method accept() in class common
{ Throgh object "obj"
common r = new common(); method accept() in class common
System.out.println("Throgh object \"r\""); method display() in class student
r.accept(); Throgh object "r2"
method accept() in abstract class common
student obj = new student();
System.out.println("Throgh object \"obj\"");
obj.accept();
obj.display();
common r2;
System.out.println("Throgh object \"r2\"");
r2 = new student();
r2.accept();
//r2.display(); // Error, the method display() is undefined for type common
}
}
39 SATEESH N
SATEESH N
N o t e : I n t h e a b ov e ex am pl e t h e di sp l a y ( ) m e t h o d m u st b e d e c l a r e d i n su p e r c l a ss
c o m m o n t o a cc e ss t h e d i sp l a y ( ) m et h o d i n t h e su b c l a s s, t h r o u g h r ef e r e n c e v a ri a b l e r 2 .
Example : Inheritence_Ex2.java
class common
{
void accept( )
{
System.out.println("method accept() in class common");
}
void display()
{
System.out.println("method display() in class common");
}
}
common r2;
System.out.println("Throgh object \"r2\"");
r2 = new student();
r2.accept();
r2.display();
}
}
40 SATEESH N
SATEESH N
F in a l k e y wo r d : T h e ‘ f i n al ‘ k e y wo r d c a n b e sp e c i f i e d f or t h e v a ri a bl e s, m et h o d s
a n d c l a sse s.
F o r t h e v ar i a bl e s : W h e n ev e r a v a ri a bl e i s sp e c i f i e d a s f i n a l , su c h v a ri a b l e b e c om e s a
c o n st a n t .
Ex: f i n al i n t M A X = 1 0 0 ;
MA X = 5 0 ; // E rr o r , c a n ’ t m o di f y t h e v al u e
F o r t h e c l a sse s : A f i n a l cl a ss c a n ’ t b e e x t e n d e d .
Ex: f i n al c l a ss A
{
}
c l a ss B e x t e n d s A / / E r r o r , c a n ’ t ov er r i d e ex t e n d f i n a l c l a ss.
{
}
Note: A b st r a c t f i n al i s n o t al l o we d .
41 SATEESH N
SATEESH N
A b s t r a c t me t ho d s a n d A b s t ra c t c la s s e s
W h e n ev e r a f u n ct i o n of su p e r c l a ss i s u se d o n l y f o r t h e p ol ym o r p h i sm a n d i s n o t
c o n t a i n i n g a n y st a t em e n t s t h e n t h a t f u n c t i o n c a n b e sp e c i f i e d a s a b st r a c t b y p r e f i x i ng
t h e f u n c t i o n d e cl a r a t i o n wi t h k e y wo r d ‘ a b s t r a c t ‘ .
W h e n ev e r a cl a ss c o n t a i n s a t l e a st o n e a b st r a c t f u n ct i o n t h e n t h e cl a ss sh o u l d
a l so b e sp e c i f i e d a s a b st r a c t .
Ex: abstract c l a ss c om m o n
{
abstract void a c c e p t ( ) ;
abstract void d i sp l a y ( );
}
W h e n ev e r a c l a ss e x t e n d s a n a b st r a c t c l a ss t h e n t h e c l a ss sh o u l d c o m p u l so r i l y
ov e r ri d e al l t h e a b st r a c t m e t h o d s o f t h e su p e r c l a ss.
T h e r e c a n ’ t b e a n y i n st a n c e s o f a n a b st r a c t c l a ss. H o w ev e r , r ef e r e n c e v a ri a b l e s
o f t h e a b st r a c t c l a sse s a r e a l l o we d i n t h e pr o g r a m .
c o m m o n r; // ok
r = new c om m o n ( ) ; / / E r r o r c a n ’ t i n st a n t i a t e a b st r a c t cl a ss
r = new st u d e n t ( ) ; / / o k , st u d e n t i s n o t ab st r a c t
E x a m p l e : AbstractClass_Ex1.java
abstract class abstractclass
{
abstract void f1();
A n a b st r a c t cl a ss c a n c o n t a i n a b st r a c t as w e l l a s n o n - a b st r a c t m e t h o d s.
Example: Abstract_abstmeth_nonabstmeth.java
43 SATEESH N
SATEESH N
A cl a ss c a n b e sp e c i f i e d a s a b st r a c t ev e n i t i s n o t c o n t a i ni n g a n y a b st r a c t m e t h o d s
we c a n ’ t c r e a t e i n st a n c e s o f i t s su b c l a s se s i f t h e y a r e n o t a b st r a c t .
E x a m p l e : AbstractClass_nonabstmeth.java
How to Use an Abstract Class and Define Its Abstract Methods at Instantiation :
Suppose you have an abstract class MyAbstractClass with an abstract method do( ) :
Of course, some classes inheriting from MyAbstractClass can be redefined with the 'do' method.
However, it may be convenient sometime to simply redefine the abstract method at the instantiation of
its abstract class. This only requires the following lines:
Redefining abstract methods at instantiation is particularly useful if the code in the method is rather short and
creating subclasses would be useless or too heavy.
44 SATEESH N
SATEESH N
E x a m p l e : AbstractClass_Ex2.java
46 SATEESH N
SATEESH N
I n t e r fa ce s
A n i n t e rf a c e i s a c o l l e c t i o n o f si g n a t u r e s o f f u n ct i o n s a n d f i n a l v a ri a b l e s. O n c e
a n i n t e rf a c e i s c r e a t e d a c l a s s c a n i m p l em e n t t h e i n t e rf a c e. W h e n ev e r a c l a ss
i m pl em e n t s t h e i n t e rf a c e, t h e c l a ss sh o u l d ov e r ri d e al l t h e m et h o d s o f i nt e rf a c e .
Example : Interface_Ex1.java
interface common
{
void accept();
void display();
}
class student implements common output :
{
int sno; String sname; int tfee; Enter 1: Student 2: Customer
1
public void accept()//overridden function
Student Details : 10 Sateesh 1500
{
sno=10;
sname="Sateesh"; output :
tfee=1500;
Enter 1: Student 2: Customer
}
public void display()//overridden function 2
{ Customer Details: 20 Raj product2 150
System.out.println("Student Details : "+sno+" "+sname+" "+tfee);
}
}
class customer implements common
{
int cno; String cname,product; int qty,rate;
public void accept() // overridden function
{
cno=20;
cname="Raj";
product="Mouse";
qty=2;
rate=150;
}
public void display() // overridden function
{
System.out.println("Customer Details: "+cno+" "+cname+" "+"product"+qty+"
"+rate);
}
}
class I n t e rf a c e _ Ex 1
{
public static void main(String args[]) throws Exception
{
char ch;
common r;
System.out.println("Enter 1: Student 2: Customer\n ");
ch = (char) System.in.read();
if(ch=='1') r = new student();
else r = new customer();
r.accept();
r.display();
}
}
47 SATEESH N
SATEESH N
M u l ti p l e i m p l e m e n t s : A c l a ss c a n i m pl e m e n t a n y n um b e r of i nt e rf a c e s su c h c l a s s
sh o u l d ov e r ri d e a l l t h e m e t h o d s i n a l l t h e i n t e rf a c e s.
Ex: interface A
{
void f1( );
}
interface B
{
void f2( );
}
class Interface_MultipleInheritence
{
public static void main(String args[])
{
//A a = new A( ); // Error, the type cannot be instantiated
//B b = new B( ); //Error, the type cannot be instantiated
C c = new C( ); // OK
c.f1( );
c.f2( );
Output :
A a;
a=c; Hi
a.f1(); Hello
Hi
B b; Hello
b=c;
b.f2();
}
}
Extended Interfaces : A n i n t e rf a c e c a n e x t e n d e d a n o t h e r i n t e r f a c e u si n g t h e k e y
wo r d “ e x t e n d s “ . W h e n ev e r a cl a ss i m p l e m e n t s t h e l a st i n t e rf a c e t h e cl a ss sh o u l d
ov e r ri d e al l t h e m et h o d s i n t h e i n t e rf a c e c ha i n .
Ex: interface A
{
void f1( );
}
interface B extends A
{
void f2( );
}
48 SATEESH N
SATEESH N
class C implements B
{
public void f1( )
{
System.out.println("Hi");
}
public void f2( )
{
System.out.println("Hello");
}
}
class Interface_extend_Interface
{
public static void main(String args[])
{
//A a = new A( ); // Error, the type cannot be instantiated
//B b = new B( ); //Error, the type cannot be instantiated
C c = new C( ); // OK
c.f1( );
c.f2( );
Output :
A a;
a=c; Hi
a.f1(); Hello
Hi
B b; Hello
b=c;
b.f2();
}
}
P a r t i a l i m p l e m en t s : W h e n ev e r a cl a ss i m p l em e n t s a n i n t e rf a c e , b ut d o e s n o t
ov e r ri d e a l l t h e m e t h o d s o f t h e i n t e rf a c e su c h c l a ss sh o u l d b e s p e c i f i e d a s a b st r a c t .
W e sh o u l d c r e a t e a n o t h e r c l a ss t h a t e x t e n d s t h e a b st r a c t c l a ss a n d sh o u l d o v e r ri d e t he
l ef t ov e r m e t h o d s.
Ex : interface A
{
void f1( );
void f2( );
}
class C extends B
{
public void f2( )
{
System.out.println("Hello");
}
}
49 SATEESH N
SATEESH N
class Interface_Abstract
{
public static void main(String args[])
{
//A a = new A( ); // Error, the type cannot be instantiated
//B b = new B( ); //Error, the type cannot be instantiated
C c = new C( ); // OK
c.f1( );
c.f2( );
Output :
A a;
a=c; Hi
a.f1(); Hello
Hi
B b; Hello
b=c;
b.f2();
}
}
Within the confines of Java syntax, an interface is a type that only defines abstract methods and
constant ( finbal ) members. In a more general sense, an interface is an abstract class that defines no
implementation. Neither an interface nor an abstract class can be directly instantiated. However, an abstract
class may define non-constant members and non-abstract methods. An abstract class is often used to define
the common set of features required of its implementing subclasses, including data structures and method
implementations. An interface is used to define only the methods and constants that are to be shared by its
implementers. You may implement an interface using the implements keyword and extend an abstract class
using the extends keyword. When you implement an interface, you must provide the code for all of the
methods in the interface. When you extend an abstract class, you inherit all of the implemented methods and
only need to implement those that were left undefined (abstract).
1 . A n a b st r a c t c l a ss c a n c o n t a i n a b st r a c t as w e l l a s n o n - a b st r a c t m e t h o d s. H o wev e r an
i n t e rf a c e c o n t a i n s o n l y t h e si g n a t u r e s of t he f u n c t i o n s.
2 . A c l a ss c a n e x t e n d s o n l y o n e c l a ss. H o w ev e r a c l a ss c a n i m p l em e n t a n y n um b e r o f
i n t e rf a c e s.
C L AS S P AT H : T h e cl a ss p a t h i s a n e nv i ro n m e n t v a ri a bl e se t i n t h e o p e r a t i n g sy st e m
wh i c h c o n t a i n s a c o l l e c t i o n of su b d i r e c t o ri e s wh e r e e a c h s u c h d i r e c t o r y c a n c o n t ai n
a n y n u m b e r o f cl a ss f i l e s. O n c e t h e c l a ss p a t h i s se we a r e a b l e t o a c c e s s t h e c l a s se s
i n t h e su b d i r e c t o r i e s f r om a n y l o c a t i o n i n t he sy st e m .
V e r i f y i n g t h e cl a ssp a t h : D: \ > e c h o % cl as sp a t h %
T o a d d i n g a n e w su b d i r e c t o r y t o p r ev i o u s su b d i r e c t o ri e s.
D : / > e c h o % c l a ssp a t h %
T h e cl a ssp a t h i s a n e nv i r o nm e n t v a ri a b l e wh i c h wi l l b e r em ov e d o n c e t h e
c o m m a n d p r om p t i s cl o se d .
50 SATEESH N
SATEESH N
P A C KA G ES A p a c k a g e i s a c ol l e c t i o n of cl a sse s t h a t c a n b e i m p o rt e d i nt o o t h e r
p r o g r a m s. A p a c k a g e wo r k s si m i l a r t o a l i b r a r y wh i c h i s a c o l l e c t i o n of c l a sse s. T h e s e
c l a sse s c a n b e i m p o r t e d a n d u se d i n o t h e r J av a p r o g r am s.
T o c r e a t e a p a c k a g e a s u b d i r e c t o r y i s r e q u i r e d . T h e n a m e o f t h e p a c k a g e wi l l b e
t h e n a m e of t h e su b d i r e c t o r y . T o m a k e a c l a ss b e l o n g i n g t o a p a c k a g e , t h e p a c k a g e
n a m e sh o u l d b e sp e c i f i e d a s t h e f i r st st a t em e n t i n t h e p r o g r am .
Ex: d:\>
sa m p a c k D
p1
A . j av a
B . j av a
f:\>
sa m p a c k F
p2
C . j av a
D . j av a
e:\>
core
p a c k . j av a / / c o n t a i n s m ai n ( ), i m p or t s A , B, C , D
W e sh o u l d se t t h e cl a ssp a t h b e f o r e c om pi l i n g t h e p a c k a g e s. j av a
D : \ > S E T C L A S S PA T H= % cl a ssp a t h % ; d : \ sa m p a c k D ; f : \ sa m p a c k F ;
package p1;
public class A
{
public void display()
{
System.out.println("Display from A");
}
}
package p1;
public class B
{
public void display()
{
System.out.println("Display from B");
}
}
51 SATEESH N
SATEESH N
// filename : C.java
// placed in f:\sampackF\p2\C.java
package p2;
public class C
{
public void display()
{
System.out.println("Display from C");
}
}
// filename : D.java
// placed in f:\sampackF\p2\D.java
package p2;
public class D
{
public void display()
{
System.out.println("Display from D");
}
}
// filename : pack.java
// this class contains the main( ) , this can be placed any where
class pack
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C(); Out put:
D d = new D();
Display from A
Display from B
a.display();
Display from C
b.display(); Display from D
c.display();
d.display();
}
}
52 SATEESH N
SATEESH N
T h e f ol l o wi n g a r e t h e l i st of som e p r e d e f i n e d p a c k a g e s wh i c h wi l l b e i n st a l l ed
wi t h J D K .
j av a . l a n g : T h i s p a c k a g e c o n t ai n s t h e i m p o rt a n t cl a sse s l i k e sy st e m , st r i n g ,
i nt e g e r , o bj e c t et c . , t h i s pa c k a g e wi l l b e i m p o r t e d i n t o ev e ry j av a
p r o g r am b y d ef a ul t .
j av a . i o : C o n t a i n s cl a sse s f o r I / P an d O / P.
j av a . a wt : AW T st a n d s f o r A b st r a c t W i n d o ws T o o l ki t , c o n t ai n s c l a sse s f o r G UI .
j av a . a p p l et : F o r a p p l et m a n a g em e n t .
j av a . n e t : F o r n et wo r k i n g .
j av a . sq l : C o n t ai n s c l a sse s f o r m a n a g i n g d a t a b a se t r a n sa c t i o n s.
j av a . u t i l : C o n t ai n s c l a sse s f o r m a n g e i n g d a t e s, c o l l e ct i o n s e t c . ,
Object Class : I t i s d e f i n e d i n j av a . l a n g p a c k a g e . W h e n ev er we c r e a t e a c l a s s
wh i c h d o e s n o t i n h e r i t a n y o t h e r cl a ss b y d e f a u l t i n h e r i t s t h e o b j e c t cl a ss i . e . , o b j ec t
c l a ss i s t h e su p e r c l a ss f o r a l l t h e cl a sse s. I n J av a o n l y t h e O bj e c t c l a ss wi l l n o t h av e
a su p e r c l a ss. F o r a l l t h e r em a i ni n g cl a sse s t h e O b j e ct cl a ss b e c o m e s t h e su p e r c l a ss.
Ex: class O bj e c t
{
class A
{ O b j e ct
} A
class B extends A B
{
O b j e ct cl a ss i s c o n t a i n i n g t h e f ol l o wi n g m e t h o d s :
p u b l i c i n h a sh C o d e ( ) : R e t u r n s t h e u n i q u e i d e n t i f i c a t i o n f o r e a c h i n st a n c e of t h e c l a ss.
2000 S
Ex: st u d e n t s = new st u d e n t ( );
10 Sateesh 2000
k = s; K
2000
b o o l e a n e q u a l s( o b j e c t o b j ) : C om p a r e s t h e h a sh c o d e s o f b ot h t h e o bj e c t s a n d r e t u r n s
t r u e i f b o t h a r e e q u a l , o t h e r wi se f al se .
3000 t
Ex: st u d e n t t = new st u d e n t ( ) ; 20 Sanju 3000
s ! = t;
53 SATEESH N
SATEESH N
S t ri n g t o S t ri n g ( ) : R e t u r n s t h e h a sh c o d e i n t h e h e x a d e c i m al f o rm a t p r ef i x e d wi t h
n a m e of t h e c l a ss.
E x a m p l e : ObjClas_hashcode_equals . j a v a
class student
{
int sno=10; String sname="Sateesh";
}
class ObjClas_hashcode_equals
{
public static void main(String args[])
{
student s = new student();
student t = new student();
student r = s;
System.out.println();
}
}
T h e t o St r i n g f u n c t i o n c a n b e ov e r ri d d e n i n a n y c l a ss t o r i d d e n a n y u sef u l
i nf o rm at i o n .
54 SATEESH N
SATEESH N
E x a m p l e : Objclass_toString. j a v a
class student
{
int sno; String sname; int tfee;
student(int sno, String sname, int tfee)
{
this.sno = sno;
this.sname = sname;
this.tfee = tfee;
}
public String toString() //overridden
{
String str = sno+" "+sname+" "+tfee;
return str;
}
}
class Objclass_toString
{ Out put:
public static void main(String args[]) 10 Sateesh 1500
{ 20 Sanju 1000
student s = new student(10,"Sateesh",1500); 30 Raj 1200
student t = new student(20,"Sanju",1000);
student r = new student(30,"Raj ",1200);
System.out.println(s); // calls s.toString()
System.out.println(t);
System.out.println(r);
}
}
Cloning :
Sometimes it is necessary to copy objects so that we can manipulate the data within it without
destroying the original object. Thus after editing the object (e.g., file or record) we still be able to cancel and
revert back to a saved version.
In JAVA, copying of objects is called cloning. In fact, the copy( ) method is called clone( ) in JAVA. So,
to clone in JAVA means to make a local copy of an object. JAVA has a clone( ) method which can be used for
copying any object.
There are two basic kinds of copying strategies: shallow copying and deep copying.
Shallow Copying :
In order to use this method, we simply have to implement the Cloneable interface in our class:
Since clone( ) is a general method, it has a return type of Object. So we need to type-cast the result.
55 SATEESH N
SATEESH N
The clone( ) method is declared in Object as protected. So by default, we can only use the clone( )
method in its own class or one of its superclasses. If we want to make a publicly available clone( ) method,
we have to write our own (more later).
Oddly enough, most classes in the standard JAVA library are not Cloneable. If you try to clone a non-
cloneable object (such as an Integer object), then you'll get a compile error.
The basic clone( ) method in Object checks if the class (subclass) is cloneable. If not, it throws a
CloneNotSupportedException.
This form of cloning is called a shallow copy. Here, the object is cloned but the objects within it are
not (i.e. shared with the original). What does that mean ? Well if the copied object contains inner parts,
these inner parts are still shared !!! So we may not really have a completely separated copy. Hence, the
elements of the original are shared with the copy. It is a little bit like two people having different straws but
sharing the same contents of a drink.
Here is what the clone( ) method for Student may look like::
Example : Shallow_clone_Ex1.java
class Marks
{
int datacommunications;
int networks;
int cryptography;
void display()
{
System.out.println("Marks:: ");
System.out.println("DataCommunications: "+datacommunications);
System.out.println("NetWorks : "+networks);
System.out.println("CryptoGraphy : "+cryptography);
}
}
56 SATEESH N
SATEESH N
class Student implements Cloneable
{
int sno=50;
String sname = "SATEESH";
Marks m = new Marks();
{ // worked as consturctor
sno = 100;
sname = "sateesh";
}
57 SATEESH N
SATEESH N
Output :
Deep Copying :
A Deep Copy attempts to make a completely separate copy of an object by copying its internal parts as well.
There are some problems when doing a deep copy of a composite object:
You must assume that the elements of the composite object have clone() methods that also do a
deep copy of their components , and so on ...
Essentially, you must control all of the code in all of the classes, or at least know enough about the
classes to be sure that their deep copies are performed properly.
Example : Deep_clone_Ex1.java
copy constructors and static factory methods provide an alternative to clone, and are much easier to
implement
Copy constructors :
58 SATEESH N
SATEESH N
Ex c e p t io n H an d l in g A n Ex c e p t i o n i s a n e r r o r t h a t o c c u r s i n t h e r u n t i m e of a
p r o g r a m (i . e . , a n ex c e p t i o n i s a R u n t i m e e r r o r ) . I n t h e p r o g r am m i n g l a n g u a g e wh i c h
d o e s n o t s u p p o r t e x c e p t i o n h a n d l i n g , e r r or s a r e t o b e c h e c k e d m a n u a l l y u si n g e r r or
c o d e s a n d e r r o r m e ssa g e s. I n j av a w h e n e v e r a n ex c e p t i o n o c c u r s, a n o b j e c t
r e p r e se n t i n g t h a t e x c e p t i o n wi l l b e c r e a t e d a n d wi l l b e ‘ t h r o wn ‘ . A n e x c e p t i o n m u st b e
h a n d l e d u si n g t h e j av a ex c e p t i o n h a n d l i n g ke y wo r d s.
T h e r e a r e 5 k e y wo r d s :
1. try, 2. catch, 3 . t h ro w , 4. f i n al l y , 5 . th r o w s .
All the statements that are to be executed should be given in a ‘ try block ‘. Whenever an exception
occurs an object representing that exception will created and will be thrown. A thrown exception must be
caught using ‘ catch block ‘. Each catch can handle one type of exception.
E x a m p l e : TryCatch. j a v a
class TryCatch
{
static int arr[]={10,20,30};
public static void main(String args[])
{
display(2); // to display the 3rd element
display(1);
display(5);
display(0);
}
static void display(int n)
{
try
{
System.out.println("Value is : "+arr[n]);
}
catch(ArithmeticException ex)
{
Out put:
System.out.println("Arithmetic Error");
} Value is : 30
catch(ArrayIndexOutOfBoundsException ex) Value is : 20
{ Invalid element no.
System.out.println("Invalid element no."); Value is : 10
}
catch(ArrayStoreException ex)
{
System.out.println("Invalid array");
}
}
}
59 SATEESH N
SATEESH N
Compiler-enforced exceptions, or checked exceptions : Checked exception are those which the Java
compiler forces you to catch. e.g. IOExceptions are checked Exceptions.
Runtime exceptions, or unchecked exceptions : Runtime exceptions are those exceptions that are thrown at
runtime because of either wrong input data or because of wrong business logic etc. These are not checked by
the compiler at compile time.
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM
errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad
input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a
NullPointerException will take place if you try using a null reference. In most of the cases it is possible to
recover from an exception (probably by giving user a feedback for entering proper values etc.).
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those
exceptions.
L i s t o f p r e d e fi n ed E x c e p ti o n s :
I n j av a a l l t h e e x c e p t i o n n am e s o r c l a s se s t h e f o l l o wi n g a r e t h e g e n e r a l
e x c e p t i o n s t h a t a r e av ai l a b l e i n t h e j av a . l a n g p a c k a g e .
1 . A ri t hm et i c Ex c e p t i o n : T hi s e x c e p t i o n o cc u r s w h e n e v e r a d iv i si o n b y 0 ( z e r o )
o c c u r s i n t h e p r og r a m .
2 . A r r a y I n d ex O u t O f B o u n d sE x c e p t i o n : T r yi n g t o a c c e ss a n e l e m e n t f r om a n a r r a y
b e y on d t h e a r r a y si z e .
3 . A rr a y S t o r e Ex c e p t i o n : I nv al i d a ssi g n m e n t t o a n el em e n t i n a a r r a y .
4 . Cl a ssN o t F o u n d E x c e p t i o n : T h e sp e c i f i ed c l a ss i s n o t av ai l a b l e i n t h e r u n t i m e .
5 . Cl a ssC a st E x c e p t i o n : I nv al i d t y p e c a st i n g .
6 . N ul l P o i n t e rEx c e p t i o n : I nv al i d u se o f NU L L r e f e r e n c e v ar i a bl e .
7 . N um b e r F o rm a t Ex c e p t i o n : I nv al i d c o n v e r si o n f r om st ri n g d a t a t o n um e ri c d a t a .
8 . Ex c e p t i o n : Ex c e p t i o n i s t h e su p e r c l a ss f o r al l t h e ex c e p t i o n s. T hi s c l a ss c a n b e
u se d t o h a n d l e a l l t h e u n sp e c i f i e d ex c e p t i o n s i n t h e p r o g r am .
T h r o w i n g a n E x c e p ti o n : W e c a n a l so t h r o w s a n e x c e p t i o n u si n g t h e ‘ t h r o w ‘ k ey
wo r d . W e c a n t h r o w a p r e d e f i n e d ex c e p t i o n o r a n u se r d e f i n e d e x c e pt i o n . W e g e n e r al l y
t h r o w e x c e p t i o n s wh e n e v e r a c o n d i t i o n i s no t sa t i sf i e d et c . ,
60 SATEESH N
SATEESH N
E x a m p l e : TryThrowCatch.java
// T h i s p r o g r a m t h r o ws a p r e d e f i n e d ex c e p t i on a n d su c h e x c e p t i o n wi l l b e h a n d l e d
in the m ain( ) .
class TryThrowCatch
{
static void f1(int n)
{
if(n == 0)
throw new ArithmeticException();
else if( n < 0 )
throw new NegativeArraySizeException();
else
System.out.println("OK");
}
i n s t a n c eo f k e y wo r d : T h i s o p e r a t o r i s u se d f o r i d e n t i f yi n g t h e t y p e of t h e cl a ss f o r
t h e g i v e n o bj e c t .
E x a m p l e : i n s t a n c eo f K W . j a v a
class instanceofKW
{
static void f1(int n)
{
if(n == 0)
throw new ArithmeticException();
else if( n < 0 )
throw new NegativeArraySizeException();
else
System.out.println("OK");
}
public static void main(String args[])
{
try
Out put:
{
f1(2); OK
f1(5); OK
f1(0); Arithmetic Error Occured
}
catch(Exception ex)
{
61 SATEESH N
SATEESH N
if(ex instanceof ArithmeticException)
System.out.println("Arithmetic Error Occured");
else if(ex instanceof NegativeArraySizeException)
System.out.println("Invalid Array size");
}
}
}
f i n a l l y bl o c k : T h e f i n al l y b l o ck c a n b e gi v e n i m m e di a t el y af t e r t h e t r y b l o c k o r af t e r
a l l t h e c a t c h b l o c k s. T h e f i n al l y b l o c k i s a l wa y s e x e c u t e d wh e t h e r o r n o t a n e x c e p t i on
i s t h r o wn i n t h e p r o g r am .
Ex: try( ) try( )
{ {
} }
f i n al l y( ) catch( )
{ {
} }
catch( )
{
}
f i n al l y( )
{
}
t h r o w s k e y wo r d : W h e n ev e r a f u n c t i on i s s u p p o se d t o t h r o w a n e x c e p t i o n t h e
f u n ct i o n sh o u l d b e p l a c e d i n a t r y b l o c k at t h e t i m e of c al l i n g i t a n d we sh o u l d h a n d l e
t h e c o r r e sp o n d i n g E x c e p t i o n . I f d o e sn ’ t r e q u i r e d t o h a n d l e t h e e x c e p t i o n we c a n
sp e c i f y t h a t ex c e p t i o n n am e u si n g t h e t h r ow s k e y w o r d .
Ex: ----
cl a ss d i sp l a y
{
p u b l i c st a t i c v oi d m ai n ( St ri n g a r g s[ ] ) t h r o ws E x c e p t i o n
----
}
The throws “ ArrayIndexOutOfBoundsException “ clause in the method header tells the compiler that
we know this exception may occur and if it does, the exception should be thrown to the caller of this method
instead of crashing the program. The throws clause is placed after the parameter list and before the opening
brace of the method. If more than one type of checked exception needs to be declared, separate the class
names with commas.
If an exception is always handled using the throws clause, then eventually the exception will propagate all the
way back to the main method of the application. If the main method throws the exception and the exception
actually occurs while the program is running, then the program will crash.
T h r o w i n g a n u s e r d e f i n e d e x c e p t i o n : T o c r e a t e a n u se r e x c e p t i o n , c r e a t e a c l a ss
t h a t ex t e n d s t h e ex c e p t i o n cl a ss. T h e ex c ep t i o n cl a ss e x t e n d s t h e t h r o wa b l e c l a ss.
T h r o wa b l e
Exception
U se r D e f i n e d Ex c e p t i o n
A n i n st a n c e of t h e u se r e x c e p t i o n c a n b e t hr o wn u si n g t h e ‘ t h r o w ‘ k e y wo r d .
62 SATEESH N
SATEESH N
Example : UserDefException.java
/ / I n t h e f ol l o wi n g p r o g r a m t h e f u n ct i o n f 1 ( ) t a k e s a n i n t e g e r a r g um e n t a n d t h r o w s
e i t h e r m y ex c e p t i o n 1 o r m y ex c e p t i o n 2 d e p e nd i n g o n v a ri o u s c o n d i t i o n s.
MyException1()
{
msg = "First Exception Occured";
}
public String toString()
{
return msg;
}
}
MyException2()
{
msg = "Second Exception Occured";
}
public String toString()
{
return msg;
}
}
class UserDefException
{
static void f1(int n) throws MyException1,MyException2
{
if(n==0)
throw new MyException1();
else if(n<0)
throw new MyException2();
else
System.out.println("OK");
}
public static void main(String args[])
{
try Out put:
{
f1(3); OK
f1(2); OK
f1(-2); Second Exception Occured
}
catch(MyException1 ex)
{
System.out.println(ex); // calls ex.toString()
}
catch(MyException2 ex)
{
System.out.println(ex); // calls ex.toString()
}
}
}
63 SATEESH N
SATEESH N
S t r in g Ha n d l in g
String Class : T h e S t r i n g c l a ss i s u se d f o r m a n a g i n g st r i n g d a t a . I t i s c o n t a i n i n g
c o n st r u c t o r s a n d m e t h o d s t o d e a l wi t h t h e st r i n g d a t a.
C o n s t r u c to r s :
S t ri n g ( ) : C r e a t e s a st r i n g wi t h o u t a n y d a t a .
S t ri n g ( c h a r a r r [ ] ) : C r e a t e s a st r i n g wi t h ch a r a c t e r s i n t h e gi v e n a r r a y.
Ex: c h a r a rr [ ] = { ‘ a ’ , ’ b ’ , ’ c ’ } ; arr a b c
St r i n g st r = n e w S t r i n g ( a r r ); st r “abc”
S t ri n g ( S t ri n g st r ) : C r e a t e s a st ri n g f r om a n o t h e r st r i n g .
Methods :
i n t l e n g t h ( ) : R e t u r n s t h e l e n g t h of t h e st r i n g .
c h a r c h a r A t ( i nt i n d e x ) : R e t u r n s t h e c h a r ac t e r a t t h e sp e c i f i e d i n d ex .
Ex: S t ri n g st r = “T e st i n g ” ;
S y st e m . o u t . p ri n t l n ( st r . l e n g t h ( ) ); 7
S y st e m . o u t . p ri n t l n ( st r . c h a r A t ( 3 ) ) ; ‘ t ’
B o o l e a n e q u a l s( S t r i n g s2 ) : I f t h e c u r r e n t st r i n g i s s1 , s1 wi l l b e c o m p a r e d wi t h s2 a n d
r e t u r n s t r u e i f b o t h a r e e q u a l , o t h e r wi se f al se .
Ex: S t ri n g s1 = “ a b c ”;
S t ri n g s2 = n e w S t ri n g ( “ a b c ” ) ;
S t ri n g s3 = s1 ;
i f ( s1 = = s2 ) f al se , b e c a u se = = o p e ra t o r c om p a r e s wi t h t h e r ef e r e n c e s i . e ,
h a sh c o d e s
i f ( s1 = = s3 )
true
i f ( s3 = = s1 )
i f ( s1 . e q u a l s( s2 ) t r u e
i f ( s1 . e q u a l s( s3 ) ) t r u e
i f ( s2 . e q u a l s( s3 ) ) t r u e
i n t c om p a r e T o ( S t r i n g s2 ) : I f c u r r e n t st r i n g i s s1 , s 1 wi l l c om p a r e wi t h s2 a n d r e t u r n s
a v al u e f r om t h e f ol l o wi n g t a bl e .
return value if
< 0 s1 < s1
> 0 s1 > s2
= 0 s1 . e q u a l s( s2 ) = = t r u e
c o m p a ri si o n d e p e n d i n g o n A S CI I v al u e s.
S t ri n g t o U p p e r C a se ( ) : R e t u r n s t h e st r i n g t o t h e u p p e r c a se .
64 SATEESH N
SATEESH N
N o t e : I n a n y of t h e st r i n g f u n c t i o n s t h e so u r c e wi l l n o t b e m o d i f i e d. O n l y t h e r e t u rn
v al u e c o t ai n s t h e m o d i f i e d d a t a .
Ex: S t ri n g st 1 = “ H e l l o ” ;
S t ri n g st 2 = st 1 . t o U p p e r C a se ( ) ;
S y st e m . o u t . p ri n t l n ( st 1 ) ; H el l o N o c h a n g e i n so u r c e
S y st e m . o u t . p ri n t l n ( st 2 ) ; HE L L O M o d i f i e d v al u e
S t ri n g t o L o we r C a se ( ) : R e t u r n s t h e st ri n g t o t h e l o we r c a se .
S t ri n g t ri m ( ) : R em ov e s t h e l e a d i n g a n d t r ai l i n g sp a c e s.
b o o l e a n st a r t sW i t h ( St ri n g st ) : C om p a r e s t h e b e g i n n i n g a n d e n d i n g p o r t i o n s of t h e
b o o l e a n e n d sW i t h ( S t ri n g st ) : S t ri n g .
Ex: St ri n g st = “T hi s i s t o t e st ” ;
S t ri n g su b st r i n g ( i n t st a r t I n d e x , i nt e n d I n d e x ) : Ex t r a ct s a p o r t i o n o f t h e st r i n g f r om
st a r t i n d ex t o e n d i n d e x - 1 .
S t ri n g su b st r i n g ( i n t st a r t I n d ex ) : Ex t r a c t s f r om st a r t i n d ex t o e n d i n g of t h e st r i n g .
i n t i n d ex O f ( ) :
Ex :
public class ReverseTester
{
public static String reverse( String data )
{
String rev = new String();
return rev;
}
/* When the input is "Hello" six Strings are constructed (including the first,
empty String) because each time the following statement executes, a new String is
created:
rev += data.charAt(j);
65 SATEESH N
SATEESH N
This is fine for programs that do a moderate amount of character
manipulation. But such abundant construction of objects will slow down a
program that does a great deal of character manipulation. Such programs are
word processors, compilers, assemblers, data base programs, and many others.
*/
S t ri n g B uf f er : A S t ri ng B uf f er o b j e ct h ol ds a S t ri n g of c h ara c t e r s t h a t c a n b e c ha n g e
d by app en di n g c ha r ac t er s at t he end a n d by i nse r t i ng c har a c t er s. Ho wev er , unl i k e
a c h ar a r r ay, a S t ri n gB uf f er c om e s wi t h m a ny m et h od s c o nv eni e nt f or c h a r a c t
e r m a ni pul at i on. A St ri ng Buf f er aut om ati cal l y g r ows i n l eng t h as n e ed ed.
C o n str u c to r s :
p u bl i c St ri n gBuf f er () : c r e at e an em pt y St ri n gB uf f er
U su al l y, i f p r og r am ex ec ut i o n sp e e d i s a c o nc er n, y o u sh o ul d dec l ar e a
S t ri ngB uf f er t o be j ust som ewha t l ar ger t han y ou m i ght need . T hi s d oe sn ' t waste m uc h
sp a c e a nd put s f e w d em a nd s o n t he r u n-t ime sy st em .
A s wi t h a rr ay s, St ri n gB uf f er i nd ex es st art a t 0 an d g o u p t o l en gt h- 1. Som e
S t ri n gBuf f er m et h od s ar e:
M e th o d s :
S t ri n gBuf f er ap pe nd ( c ha r c ) : A p pe nd c t o t h e e nd of t h e St ri n gBuf f er
S t ri n gBuf f er ap pe nd ( St ri n g s ) : A p pe nd t h e c h ar act er s i n s t o t h e e nd of t he
S t ri n g Buf f er.
c h ar c har At ( i nt i nd ex ) : G et t he c ha r act er a t i nd ex .
i nt l e ngt h( ) : R et u rn t h e n um b er of c har ac t er s.
66 SATEESH N
SATEESH N
// In this version of reverse(), only two new objects are created: the
StringBuffer and the String object that is returned to the caller.
return temp.toString();
}
Data Conversions :
// approach 1
int i =Integer.parseInt(str);
System.out.println("String to int (1): "+i);
// approach 2 o u tp u t :
i = Integer.valueOf(str).intValue();
System.out.println("String to int (2): "+i); int to String (1): 3
int to String (2): 3
// Converting string to long String to int (1): 25
long l = Long.valueOf(str).longValue(); String to int (2): 25
System.out.println("String to long : "+l); String to long : 25
String to float : 25.6
// Converting string to float String to double : 25.6
str = "25.6";
float f = Float.valueOf(str).floatValue();
System.out.println("String to float : "+f);
What is a a stream?
A stream is a sequence of data that flow from a source to destination. i.e., producing or consuming the
information.
A stream is linked to a physical device by the java I/O system. The physical device may be keyboard,
memory, disk file, network socket or console.
Input to a java program : A java program can consume input from a key board, memory, a disk file or a
network socket.
To bring in information, a program opens a stream on an information source (a file, memory, a socket) and reads the
information sequentially, as shown here:
Output from a java program : A java program can produce output on a console, memory, a disk file or a
network socket.
Similarly, a program can send information to an external destination by opening a stream to a destination and
writing the information out sequentially, like this:
No matter where the data is coming from or going to and no matter what its type, the algorithms for
sequentially reading and writing data are basically the same :
Reading Writing
--> open a stream --> open a stream
--> while more information --> while more information
read information write information
--> close the stream --> close the stream
All of the streams--readers, writers, input streams, and output streams--are automatically opened when
created. You can close any stream explicitly by calling its close method. Or the garbage collector can implicitly
close it, which occurs when the object is no longer referenced.
68 SATEESH N
SATEESH N
There are two kinds of streams : Byte Streams and Character Streams.
The java.io package contains a collection of stream classes ( InputStream and OutputStream
classes, Reader and Writer classes ) that support these algorithms for reading and writing. To use these
classes, a program needs to import the java.io package.
Prior to JDK 1.1, the input and output classes (mostly found in the java.io package) only supported 8-
bit byte streams. The concept of 16-bit Unicode character streams was introduced in JDK 1.1. While byte
streams were supported via the java.io.InputStream and java.io.OutputStream classes and their subclasses,
character streams are implemented by the java.io.Reader and java.io.Writer classes and their subclasses.
Most of the functionality available for byte streams is also provided for character streams. The
methods for character streams generally accept parameters of data type char parameters, while byte streams,
you guessed it, work with byte data types. The names of the methods in both sets of classes are almost
identical except for the suffix, that is, character-stream classes end with the suffix Reader or Writer and byte-
stream classes end with the suffix InputStream and OutputStream. For example, to read files using character
streams, you would use the java.io.FileReader class; for reading it using byte streams you would use
java.io.FileInputStream.
Unless you are working with binary data, such as image and sound files, you should use readers and
writers (character streams) to read and write information for the following reasons:
They can handle any character in the Unicode character set (while the byte streams are limited to ISO-
Latin-1 8-bit bytes).
They are easier to internationalize because they are not dependent upon a specific character
encoding.
They use buffering techniques internally and are therefore potentially much more efficient than byte
streams.
To bridge the gap between the byte and character stream classes, JDK 1.1 and JDK 1.2 provide the
java.io.InputStreamReader and java.io.OutputStreamWriter classes. The only purpose of these classes is to
convert byte data into character-based data according to a specified (or the platform default) encoding. For
example, the static data member "in" in the "System" class is essentially a handle to the Standard Input (stdin)
device. If you want to wrap this inside the java.io.BufferedReader class that works with character-streams, you
use InputStreamReader class as follows:
character Streams :
Reader and Writer are the abstract parent classes for character-stream based classes in the java.io package.
As discussed above, Reader classes are used to read 16-bit character streams and Writer classes are used to
write to 16-bit character streams.
The following figure shows the class hierarchies for the Reader and Writer classes.
69 SATEESH N
SATEESH N
byte Streams :
To read and write 8-bit bytes, programs should use the byte streams, descendants of InputStream and
OutputStream. InputStream and OutputStream provide the API and partial implementation for input streams
(streams that read 8-bit bytes) and output streams (streams that write 8-bit bytes). These streams are typically
used to read and write binary data such as images and sounds. Two of the byte stream classes,
ObjectInputStream and ObjectOutputStream, are used for object serialization.
The following figure shows the class hierarchies for the InputStream and OutputStream classes.
70 SATEESH N
SATEESH N
Using the Streams
The following table lists java.io's streams and describes what they do. Note that many times,
java.io contains character streams and byte streams that perform the same type of I/O but for different
data types.
I/O Streams
Type of I/O Streams Description
CharArrayReader
Use these streams to read from and write to memory. You create
CharArrayWriter
these streams on an existing array and then use the read and
ByteArrayInputStream write methods to read from or write to the array.
ByteArrayOutputStream
Memory Use StringReader to read characters from a String in memory.
Use StringWriter to write to a String. StringWriter collects the
StringReader
characters written to it in a StringBuffer, which can then be
StringWriter
converted to a String.
StringBufferInputStream
StringBufferInputStream is similar to StringReader, except
that it reads bytes from a StringBuffer.
PipedReader
Implement the input and output components of a pipe. Pipes are
PipedWriter
Pipe used to channel the output from one thread into the input of
PipedInputStream another.
PipedOutputStream
FileReader
FileWriter Collectively called file streams, these streams are used to read
File
FileInputStream from or write to a file on the native file system.
FileOutputStream
N/A
Concatenation Concatenates multiple input streams into one input stream.
SequenceInputStream
N/A
Object
ObjectInputStream Used to serialize objects.
Serialization
ObjectOutputStream
N/A
Data Read or write primitive data types in a machine-independent
Conversion
DataInputStream format.
DataOutputStream
LineNumberReader
Counting Keeps track of line numbers while reading.
LineNumberInputStream
71 SATEESH N
SATEESH N
A reader and writer pair that forms the bridge between byte
streams and character streams.
An InputStreamReader reads bytes from an InputStream and
converts them to characters, using the default character
Converting between Bytes InputStreamReader encoding or a character encoding specified by name.
and Characters OutputStreamWriter An OutputStreamWriter converts characters to bytes, using the
default character encoding or a character encoding specified by
name and then writes those bytes to an OutputStream.
You can get the name of the default character encoding by
calling System.getProperty("file.encoding").
Note that the StreamTokenizer class is NOT a subclass of InputStream. StreamTokenizer is a utility class
used to parse the stream of input.
F i l e : Files and directories are accessed and manipulated through the java.io.File class.
Note: the File class does not provide for I/O. Rather it is often used in the arguments for the file I/O class
methods.
C o n s t ru c t o r :
File(String parent,String child) : Allows separate specification of the path and the file name.
Methods :
l o n g l e n g t h ( ) : R e t u r n s t h e l e n g t h of t h e f i l e. I t r et u r n s 0 i f f i l e i s n o t av ai l a bl e .
b o ol e a n i sD i r e ct o r y ( ) : R eturns true if the File object refers to a directory. It returns false if it refers
to a regular file or if no file with the given name exists..
b o ol e a n i sF i l e ( ) : R e t u r n s t r u e i f t h e g i v en p a t h r e p r e se n t s a f i l e o t h e r wi se f al se .
b o ol e a n d e l e t e ( ) : D el e t e s t h e f i l e o r d i r e ct o r y , i f i t e x i st s.
b o ol e a n e x i st s( ) : R eturns true if the file named by the File object already exists. You could use this
method if you wanted to avoid overwriting the contents of an existing file when
you create a new FileWriter.
b o ol e a n l i st ( ) : If the File object refers to a directory, this function returns an array of type String[]
containing the names of the files in this directory. Otherwise, it returns null.
boolean canRead( ) : Method asks if the file is readable.
boolean setReadOnly( ) : Makes the file property to read only.
Example : f i l el e n . j a v a
/ / t o f i n d t h e l e n g t h of t h e f i l e
import java.io.*;
class FileLength
{
public static void main(String args[])
{
72 SATEESH N
SATEESH N
try
{
String fname = "d://sateesh_inputfile.java";
File f = new File(fname);
System.out.println( fname +" file size: "+f.length());
}
catch(Exception ex)
{
if(ex instanceof FileNotFoundException)
{
System.out.println("File not found, give existing filename");
}
}
} Out put:
}
d://sateesh_inputfile.java file size: 13662
The position of the end of the stream depends on the constructor used.
Consturctors :
ByteArrayInputStream(byte[] buffer) : This constructor is used, the end of the stream is the end of the byte
array.
ByteArrayInputStream(byte[] buffer, int offset, int length): This constructor is used, the end of the
stream is reached at the index given by offset+length.
ByteArrayOutputStream : This class implements an output stream in which the data is written into a byte
array. The buffer automatically grows as data is written to it.
Constructors :
public ByteArrayOutputStream(int size) : Creates a new byte array output stream. The buffer capacity
is initially 32 bytes, though its size increases if necessary.
Example: ByteArrayIOStreams.java
import java.lang.System;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
for(int i=0;i<s.length();++i)
outStream.write(s.charAt(i));
73 SATEESH N
SATEESH N
CharArrayReader : The CharArrayReader class represents a stream whose data comes from a character
array. This class is similar to ByteArrayInputStream, but it deals with a Java character stream rather than a
byte stream. Furthermore, this class supports marking a position in the stream, which ByteArrayInputStream
does not.
The position of the end of the stream depends on the constructor used.
Consutrctors :
public CharArrayReader(char[] buf) : This constructor is used, the end of the stream is the end of the
character array.
public CharArrayReader(char[] buf, int offset, int length) : This constructor is used, the end of the
stream is reached at the index given by offset+length.
CharArrayWriter : The CharArrayWriter class represents a stream whose data is written to an internal
character array. This class is similar to ByteArrayOutputStream, but it operates on an array of Java characters
instead of a byte array.
The data from a CharArrayWriter can be sent to another Writer using the writeTo( ) method. A copy of the
array can be obtained using the toCharArray() method.
Constructors:
public CharArrayWriter( ) : This constructor creates a CharArrayWriter with an internal buffer that has a
default size of 32 characters. The buffer grows automatically as data is written to the stream.
public CharArrayWriter(int initialSize) : This constructor creates a CharArrayWriter with an internal buffer that
has a size of initialSize characters. The buffer grows automatically as data is written to the stream.
Example: CharArrayIOReadWrite.java
import java.lang.System;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
for(int i=0;i<s.length();++i)
out.write(s.charAt(i));
System.out.println("outstream: "+out);
System.out.println("size: "+out.size());
CharArrayReader in;
in = new CharArrayReader(out.toCharArray());
output :
int ch=0;
StringBuffer sb = new StringBuffer(""); outstream: This is a test.
while((ch = in.read()) != -1) size: 15
sb.append((char) ch); 15 characters were read
They are: This is a test.
s = sb.toString();
StringReader : The StringReader class is useful when you want to read data in a String as if it were coming
from a stream, such as a file, pipe, or socket. For example, suppose you create a parser that expects to read
tokens from a stream. But you want to provide a method that also parses a big string. You can easily add one
using StringReader.
Constructors :
public StringReader(String s) : This constructor creates a StringReader that uses the given String as its data
source. The data is not copied, so changes made to the String affect the data that the StringReader returns.
Methods :
read( ) : This method returns the next character from the string. The method cannot block.
ready( ) : If there is any data left to be read from the string, this method returns true.
StringWriter : The StringWriter class is useful if you want to capture the output of something that normally
sends output to a stream, such as a file or the console. A PrintWriter wrapped around a StringWriter competes
with StringBuffer as the easiest way to construct large strings piece by piece. While using a StringBuffer is
more efficient, PrintWriter provides more functionality than the normal append() method used by StringBuffer.
Constructors :
public StringWriter( ) : This constructor creates a StringWriter with an internal buffer that has a default size of
16 characters. The buffer grows automatically as data is written to the stream.
Public StringWriter( int initialSize ) : This constructor creates a StringWriter with an internal buffer that has a
size of initialSize characters. The buffer grows automatically as data is written to the stream.
Methods :
public void write(int c) : This method writes the given value into the internal buffer. If the buffer is full, it is
expanded.
75 SATEESH N
SATEESH N
public void write(String str) : This method copies the characters of str into this object's internal buffer. If the
internal buffer is full, it is expanded.
public StringBuffer getBuffer( ) : This method returns a reference to the StringBuffer object that is used in this
StringWriter.
Example : StringReadWrite.java
import java.lang.System;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.IOException;
for(int i=0;i<s.length();++i)
outStream.write(s.charAt(i));
System.out.println("outstream: "+outStream);
System.out.println("size: "+outStream.toString().length());
int ch=0;
F i l eI n p u tS t r e a m : T hi s c l a ss i s u se d f o r o p e n i n g a f i l e i n t h e i n p u t m o d e a n d a l l o w s
u s t o r e a d t h e c o n t e n t s of t h e f i l e .
C o n s t r u c to r :
Methods :
i n t r e a d ( ) t h r o ws I O Ex c e p t i o n : R e a d s a c h a r a c t e r f r om t h e f i l e a n d r e t u r n s t h e A S C I I
v al u e of t h a t c h a r a c t e r . I t r e t u r n s – 1 o r EO F .
v oi d cl o se ( ) t h r o ws I O Ex c e p t i o n : Cl o se s t h e o p e n e d f i l e.
76 SATEESH N
SATEESH N
F i l eO u t p u t S t r e a m : Opens a f ile i n t h e o u t p u t m o d e , wh i c h a l l o ws u s t o wr i t e t h e
data into the file.
C o n s t r u c to r :
Methods:
void write( int val ) throw IOException : This method writes a byte containing the low-order eight bits of the
given value to the output stream.
write( ) : Takes an ASCII value and writes the given character into the file.
void close( ) throws IOException : This method closes this file output stream and releases any resources used
by it.
E x a m p l e : FileIP_OPStreams.j a v a
/ / T h i s p r o g r a m t a k e s a f i l e n a m e , o p e n s t h a t f i l e a n d d i sp l a y s t h e c o n t e n t s o f f i l e o n
c o n so l e .
import java.io.*;
class FileIP_OPStreams
{
public static void main(String args[])
{
try
{
String in_fname = "d://sateesh_inputfile.txt";
String out_fname = "d://sateesh_outputfile.txt";
FileReader : FileReader stream is used to read character data from text files. It is a subclass of
InputStreamReader that uses a default buffer size (8192 bytes) to read bytes from a file and the default
character encoding scheme to convert the bytes to characters. If you need to specify the character encoding
or the buffer size, wrap an InputStreamReader around a FileInputStream.
Constructors :
public FileReader(String fileName) throws FileNotFoundException This constructor creates a FileReader that
gets its input from the file named by the specified String.
public FileReader(File file) throws FileNotFoundException: This constructor creates a FileReader that gets its
input from the file represented by the specified File.
FileWriter : FileWriter stream is used to write character data into text files. It is a subclass of
OutputStreamWriter that uses a default buffer size (8192 bytes) to write bytes to a file and the default
character encoding scheme to convert characters to bytes. If you need to specify the character encoding or
the buffer size, wrap an OutputStreamWriter around a FileOutputStream.
Constructors :
public FileWriter(String fileName) throws IOException: This constructor creates a FileWriter that sends its
output to the file named by the specified String.
public FileWriter(String fileName, boolean append) throws IOException : This constructor creates a
FileWriter that sends its output to the named file. If append is true, the stream is positioned at the end of the
file, and data is appended to the end of the file. Otherwise, if append is false, the stream is positioned at the
beginning of the file, and any previous data is overwritten.
Example : CopyFile.java
The following CopyFile program uses FileReader and FileWriter to copy the contents of a file named
sateesh_inpufile.txt into a file called sateesh_outputfile.txt :
The read( ) method obtains one character at a time from the File. (For the host system this will
correspond to one byte at a time.)
import java.io.*;
in.close();
out.close();
System.out.println("One file is copied. (D://sateesh_outputfile.txt)");
}
catch(FileNotFoundException ex)
{
System.out.println("File not found");
}
} Output :
}
One file is copied. (D://sateesh_outputfile.txt)
C o n s t r u c to r s :
E x a m p l e : Concatenate_SeqIS_Ex1.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
try
{
SequenceInputStream s = new SequenceInputStream(is1,is2);
int c;
s.close();
}
catch (IOException ex)
{
System.err.println("Concatenate: " + e);
}
}
}
Data Stream Classes : A problem with the FileInputStream and FileOutputStream classes is that they only
work at the byte level. What do you do when you need to read integers, write floating-point values, and read or
write some other non-byte value from/to a file? The answer is to use Java's DataInputStream and
DataOutputStream classes.
As with the buffered stream classes, the data stream classes are designed so that their objects can be
chained to other streams. However, you can only chain data stream objects to byte-oriented streams. For
example, you can chain a data input stream to a FileInputStream object and call the data input stream's
methods to read integer, floating-point, and other data items, but you cannot directly chain a data input stream
object to a FileReader object.
80 SATEESH N
SATEESH N
DataInputStream : DataInputStream allows you to read lines of text and Java primitive data types in a
portable way.
Deprecated: This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way
to read lines of text is via the BufferedReader.readLine( ) method. Programs that use the DataInputStream
class to read lines can be converted to use the BufferedReader class by replacing code of the form:
with:
BufferedReader d = new BufferedReader(new InputStreamReader(in));
C o n s t r u c to r :
public DataInputStream(InputStream in) : This constructor creates a DataInputStream object that reads
from, or wraps, the given input stream.
D a t a O u tp u t St r e a m : DataOutputStream allows you to write lines of text and Java primitive data types in
a portable way.
DataOutputStream provides simple methods to write primitive data-types out to any output stream,
whether it be the user console, a network connection, or a file.
C o n s tu r c t o r s :
public DataOutputStream(OutputStream out) : This constructor creates a DataOutputStream that uses out
as its underlying stream.
boolean wr i t e B o o l e a n ( b o o l e a n v ) ;
byte wr i t e B y t e (i n t v );
wr i t e B y t e s( S t ri n g s) ;
c h a r , st r i n g wr i t e C h a r ( i n t v );
wr i t e C h a r s( S t r i n g s) ;
double wr i t e D o u b l e ( d o u b l e v ) ;
float wr i t e F l o a t (f l o a t v );
int wr i t e I n t (i n t v );
long wr i t e L o n g ( l o n g v );
sh o r t wr i t e S h o r t ( i nt v );
st r i n g wr i t e U T F ( St ri n g st r ) ;
Java also provides a corresponding DataInputStream, which will allow you to read data back. This means you
can write a data structure out to a disk or network connection, and read it back at a later date.
Example: DataIOStreams.java
import java.io.*;
public class DataIOStreams
{
public static void main(String[] args)throws IOException
{
// write the data out
81 SATEESH N
SATEESH N
DataOutputStream out = new DataOutputStream(new FileOutputStream
("D://invoice1.txt"));
double[] sal = { 6000.00, 7700.00, 8600, 8000.00, 12000.00 };
int[] dept = { 12, 8, 13, 29, 50 };
String[] employees = { "Sateesh", "Ravi Kumar", "Srinivas", "Kishore", "Varma" };
System.out.println("Writing...........");
System.out.println("Salary DeptNo EmployeeName");
for (int i = 0; i < employees.length; i ++)
{ Output :
System.out.print(sal[i]); Writing...........
out.writeDouble(sal[i]); Salary DeptNo EmployeeName
System.out.print(" "); 6000.0 12 Sateesh
out.writeChar('\t'); 7700.0 8 Ravi Kumar
System.out.print(dept[i]); 8600.0 13 Srinivas
out.writeInt(dept[i]); 8000.0 29 Kishore
System.out.print(" "); 12000.0 50 Varma
out.writeChar('\t'); Reading...........
System.out.print(employees[i]); Salary DeptNo EmployeeName
out.writeChars(employees[i]); 6000.0 12 Sateesh
System.out.println(); 7700.0 8 Ravi Kumar
out.writeChar('\n'); 8600.0 13 Srinivas
} 8000.0 29 Kishore
out.close(); 12000.0 50 Varma
System.out.println("Reading...........");
System.out.println("Salary DeptNo EmployeeName");
// read it in again
DataInputStream in = new DataInputStream(new FileInputStream
("D://invoice1.txt"));
double salary;
int deptno;
StringBuffer employee;
double total = 0.0;
try
{
while (true)
{
salary = in.readDouble();
System.out.print(salary);
System.out.print(in.readChar());
// throws out the tab
deptno = in.readInt();
System.out.print(deptno);
System.out.print(in.readChar());
// throws out the tab
char chr;
employee = new StringBuffer(20);
while ((chr = in.readChar()) != '\n')
employee.append(chr);
System.out.println(employee.toString());
}
}
catch (EOFException e)
{
}
in.close();
}
}
82 SATEESH N
SATEESH N
1 . I n p u t S t r e am R e a d e r , 2 . B uf f e r e d R e a d e r .
BufferedReader : T h e B uf f er e d R e a d e r , b u f f e r s t h e c h a r a c t e r s a n d c o n v e r t s t h em i n t o
t h e st r i n g f o rm a t .
Constructors :
public BufferedReader(Reader in) : This constructor creates a BufferedReader that buffers input from the
given Reader using a buffer with the default size of 8192 characters.
public BufferedReader(Reader in, int sz) : This constructor creates a BufferedReader that buffers input
from the given Reader, using a buffer of the given size.
Methods :
S t ri n g r e a d L i n e ( ) t h r o ws I O Ex c e p t i o n : R e a d s a l i n e ( S t r i n g ) f r om gi v e n i n p u t
st r e a m or null if the end of the stream has been reached.
I n p u t St r e a m R e a d e r : T h e I n p u r S t r e am R e a d e r , r e a d s t h e d a t a f ro m t h e g i v e n i n p u t
st r e a m i n t h e b y t e f o rm a t a n d c o nv er t s i n t o t h e c h a r a c t e r f o rm a t . i . e . , t he
I n p u t S t r e am R e a d e r c o nv e r t s t h e d a t a f r om t h e b y t e st r e a m s t o c h a r a c t e r st r e a m s.
This class is used to bridge the gap between a Reader, and an InputStream. InputStreamReader is a
reader that can be connected to any InputStream - even filtered input streams such as DataInputStream, or
BufferedInputStream.
C o n s t r u c to r s :
public InputStreamReader(InputStream in) : This constructor creates an InputStreamReader that gets its
data from in and translates bytes to characters using the system's default encoding scheme.
/ / f i l e n a m e : ISR_BR_ReadLineNos.j a v a
/ / t o a c c e p t a f i l e n a m e a s c o m m a n d l i n e a r g u m e n t a n d t o d i sp l a y t h e c o n t e n t s o f f i l e
a l o n g wi t h t h e l i n e n o ’ s.
import java.io.*;
class ISR_BR_ReadLineNos
{
public static void main(String args[])
{
83 SATEESH N
SATEESH N
try
{
String fname = "D://sateesh_inputfile.txt";
You can specify the size of the buffer used by BufferedInputStream when it is created or accept the default of
2048 bytes. It then intercepts your calls to the read methods and attempts to satisfy your request with data in
its buffer. If the data in the buffer is not sufficient, a read to the next input stream in the chain is done to fill the
buffer and return the data requested.
LineNumberReader : A buffered character-input stream that keeps track of line numbers. A line is
considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed
immediately by a linefeed.
Consturctors :
LineNumberReader Reader) : Create a new line-numbering reader, using the default input-buffer size.
LineNumberReader (Reader, int) : Create a new line-numbering reader, reading characters into a buffer
of the given size.
Methods :
setLineNumber( ) : This method enable you to set the internal line number count maintained by
LineNumberInputStream.
getLineNumber( ) : This method enable you to get the internal line number count maintained by
LineNumberInputStream.
Output :
Example : LineNumberReader_Ex1.java
1.
import java.lang.System;
2. This file is created
import java.io.LineNumberReader;
3. for testing io streams.
import java.io.FileReader;
4.
import java.io.BufferedWriter;
5. fileinputstreamreader,
import java.io.IOException;
6. fileoutputstreamreader,
7. bufferedreader etc.,
public class LineNumberReader_Ex1
{
public static void main(String args[]) throws IOException
{
FileReader inFile = new FileReader("D://sateesh_inputfile.txt");
String inputLine;
R e a d i n g l i n e s f r o m t h e k e y b o a r d : T o r e a d l i n e s f r om t h e k e y b o a r d t h e sy st e m . i n
sh o u l d b e a t t a t c h e d t o t h e B uf f e r e d R e a d e r .
Example : ISR_BR_ReadLines. j a v a
// t o a c c e p t 5 l i n e s f r om t h e k e y b o a r d a n d d i sp l a y t h em i n t h e r ev e r se o r d e r .
import java.io.*;
System.out.println("Enter 5 strings:\n");
for(i=0;i<5;i++)
arr[i] = stdin.readLine();
System.out.println();
for(i=4;i>=0;i--)
System.out.println(arr[i]);
}
85 SATEESH N
SATEESH N
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}
PrintWriter : The PrintWriter class provides support for writing string representations of primitive data types
and can be attatched to any output stream for writing line by line into the stream. PrintWriter uses the system's
default encoding scheme to convert characters to bytes. PrintWriter also uses the system's own specific line
separator, rather than the newline character, for separating lines of text. This line separator is equivalent to the
value returned by: System.getProperty("line.separator")
Constructors :
public PrintWriter(OutputStream out) : This constructor creates a PrintWriter object that sends output to the
given OutputStream. The constructor creates the intermediate OutputStreamWriter that converts characters to
bytes using the default character encoding.
public PrintWriter(OutputStream out, boolean autoFlush) : This constructor creates a PrintWriter object
that sends output to the given OutputStream. The constructor creates the intermediate OutputStreamWriter
that converts characters to bytes using the default character encoding. If autoFlush is true, every time a
println( ) method is called, the PrintWriter object calls its flush( ) method. This behavior is different from that of
a PrintStream object, which calls its flush() method each time a line separator or newline character is written.
Methods:
void print(String str) throws IOException : This method writes the given String to the underlying output
stream. If String is null, the method writes "null".
void println(String str) throws IOException : This method writes "true" to the underlying output stream if b
is true, otherwise it writes "false". In either case, the string is followed by a line separator.
void write(String str) throws IOException : This method writes the given String to the underlying output
stream. The method does this by calling write(s, 0, s.length) for the underlying output stream and catching any
exceptions that are thrown. If necessary, the method blocks until the String is written.
Example : PrintWriter_KB.java
/ / t o a c c e p t 5 l i n e s f r om t h e k e y b o a r d a n d sa v e t h em i n t h e f i l e sa t e e sh _ o u t p u t f i l e . t x t
(f i l e n am e ).
import java.io.*;
class PrintWriter_KB
{
public static void main(String args[])
{
try
{
//key board
//output
86 SATEESH N
SATEESH N
for(int i=1;i<=5;i++)
{
System.out.print("Enter: ");
catch(Exception ex)
{
System.out.println("error:"+ex);
}
}
}
Example: Co p y F i l e _ P W . j a v a
/ / t o c o p y d a t a f r om t h e 1 st f i l e t o 2 n d f i l e
import java.io.*;
class CopyFile_PW
{
public static void main(String args[])
{
try
{
// console i.e. system.out
// keyboard
// reading filename
System.out.print ("Enter source file name: ");
String sourcefname = stdin.readLine();
// start reading from source and copy each line to the targer
String str = in.readLine(); // from the source file
while(str!=null) Output :
{
out.println(str); // write into targer Enter source file name:
str = in.readLine(); D://sateesh_inputfile.txt
} Enter target file name: D://sammm.txt
in.close(); Copied
out.close();
87 SATEESH N
SATEESH N
System.out.println("Copied");
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}
PrintStream :
We have actually been using the PrintStream filter in many programs. The System.out and System.err
objects are FileOutputStreams that use a PrintStream filter. This filter adds the capability to force the attached
stream to be flushed every time a newline (\n) character is written. It also provides several overloaded versions
of print() and println() that write each of the primitive data types to the attached stream as strings. In addition,
each of the println() methods also append a newline to each object written.
Threads are often required to communicate. A technique that is often used by threads wishing to
communicate involves piped streams.
The idea behind piped streams is to connect a piped output stream to a piped input stream. Then, one
thread writes data to the piped output stream and another thread reads that data by way of the piped input
stream. Although there are no synchronization problems with piped streams, those streams have limited sizes.
As a result, a writing thread could write more output to a piped output stream than that stream can
accommodate, and the excess output would be lost. To prevent that from happening, the reading thread must
be responsive. To support piped streams, Java supplies the PipedInputStream, PipedReader,
PipedOutputStream, and PipedWriter classes in its standard class library. (Those classes are located in the
java.io package.)
CAUTION
Deadlock might occur if a single thread uses a piped output stream connected to a piped input stream,
and performs both writing and reading operations on that stream.
PipedReader / PipedWriter : The PipedReader / PipedWriter class represents half of a communication pipe;
a PipedReader must be connected to a PipedWriter. When the two halves of a communication pipe are
connected, data written to the PipedWriter can be read from the PipedReader. The communication pipe
formed by a PipedReader and a PipedWriter should be used to communicate between threads. If both ends of
a pipe are used by the same thread, the thread can hang.
PipedReader :
Constructors :
public PipedReader(PipedWriter src) throws IOException : This constructor creates a PipedReader that
receives data from the given PipedWriter.
Methods :
public void connect(PipedWriter src) throws IOException : This method connects the given PipedWriter
to this PipedReader object. If there is already a connected PipedWriter, an exception is thrown.
public int read( ) throws IOException : Reads the next character of data from this piped stream.
88 SATEESH N
SATEESH N
PipedWriter :
Constructors :
public PipedWriter(PipedReader sink) : This constructor creates a PipedWriter that sends data to the
given PipedReader.
Methods :
public void connect(PipedReader sink) throws IOException : This method connects this PipedWriter object
to the given PipedReader. If this PipedWriter or sink is already connected, an exception is thrown.
public void write(int c) throws IOException : Writes the specified char to the piped output stream.
Example: PipedThreads.java
import java.io.*;
this.pr = pr;
this.pw = pw;
}
pw.close ();
}
else
{
int item;
while ((item = pr.read ()) != -1)
System.out.print ((char) item); // dst reads
pr.close ();
}
}
catch (IOException e)
{
}
}
}
class PipedThreads
{
public static void main (String [] args) throws IOException
{
89 SATEESH N
SATEESH N
PipedWriter pw = new PipedWriter ();
PipedReader pr = new PipedReader (pw); Output :
Filter Streams
FilterInputStream is the base class for all the input stream filters. This class does not make any
modifications to the attached stream, but merely provides the chaining functionality that will be exploited by its
subclasses. The FilterInputStream is attached to an input stream by passing the input stream to the filter
stream's constructor.
FilterReader :
FilterWriter :
PushbackReader : The PushbackReader class represents a character stream that allows data to be pushed
back into the stream. In other words, after data has been read from a PushbackReader, it can be pushed back
into the stream so that it can be reread. This functionality is useful for implementing things like parsers that
need to read data and then return it to the input stream. PushbackReader is the character-oriented equivalent
of PushbackInputStream. When you create a PushbackReader object, you can specify the number of
characters that you are allowed to push back; the default is one character.
Constructors :
public PushbackReader(Reader in) : This constructor creates a PushbackReader that reads from the given
Reader, using a pushback buffer with the default size of one byte.
public PushbackReader(Reader in, int size) : This constructor creates a PushbackReader that reads from
the given Reader, using a pushback buffer of the given size.
Methods :
public void unread(int c) throws IOException : This method puts the given character into the pushback
buffer.
ObjectInputStream :
ObjectOutputStream :
90 SATEESH N
SATEESH N
RandomAccessFiles : The RandomAccessFile class reads data from and writes data to a file. The file is
specified using a File object or a String that represents a pathname. Both constructors take a mode parameter
that specifies whether the file is being opened solely for reading, or for reading and writing. Each of the
constructors can throw a SecurityException if the application does not have permission to access the specified
file using the given mode. Unlike FileInputStream and FileOutputStream, RandomAccessFile supports
random access to the data in the file; the seek() method allows you to alter the current position of the file
pointer to any location in the file. RandomAccessFile implements both the DataInput and DataOutput
interfaces, so it supports reading and writing of all the primitive data types.
Constructors :
public RandomAccessFile(File file, String mode) : This constructor creates a RandomAccessFile to access
the specified File in the specified mode.
Methods :
getFilePointer( ) : This method returns the current position in the file. The position is the offset, in bytes, from
the beginning of the file where the next read or write operation occurs.
seek( ) : This method sets the current file position to the specified position. The position is the offset, in bytes,
from the beginning of the file where the next read or write operation occurs.
readBoolean( ) : This method reads a byte as a boolean value from the file. A byte that contains a zero is read
as false. A byte that contains any other value is read as true. The method blocks until the byte is read, the end
of the file is encountered, or an exception is thrown.
public final void writeBoolean(boolean v): If v is true, this method writes a byte that contains the value 1 to the
file. If v is false, the method writes a byte that contains the value 0.
read( ) : This method reads the next byte from the file. The method blocks until the byte is read, the end of the
file is encountered, or an exception is thrown.
write( ) : This method writes the low-order eight bits of b to the file as a byte .
RandomAccessFile implements both the DataInput and DataOutput interfaces, so it supports reading
and writing of all the primitive data types.
Example : RandomAccessFile_Ex1.java
import java.lang.System;
import java.io.RandomAccessFile;
import java.io.IOException;
public class RandomAccessFile_Ex1
{
public static void main(String args[]) throws IOException
{
RandomAccessFile file = new RandomAccessFile("D://sateesh_inputfile.txt","rw");
file.writeBoolean(true);
file.writeInt(123456); Output :
file.writeChar('j');
file.writeDouble(1234.56); 123456
file.seek(1); j
System.out.println(file.readInt()); 1234.56
System.out.println(file.readChar()); true
System.out.println(file.readDouble());
file.seek(0);
System.out.println(file.readBoolean());
file.close();
}
}
91 SATEESH N
SATEESH N
StreamTokenizer : The StreamTokenizer class performs a lexical analysis on an InputStream object and
breaks the stream into tokens. Although StreamTokenizer is not a general-purpose parser, it recognizes
tokens that are similar to those used in the Java language. A StreamTokenizer recognizes identifiers,
numbers, quoted strings, and various comment styles.
Alphabetic characters from 'a' through 'z', 'A' through 'Z', and '\u00A0' and '\u00FF'.
Numeric characters '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.', and '-'
Constructors :
public StreamTokenizer(Reader in) : This constructor creates a StreamTokenizer that reads from the given
Reader.
Methods :
public void commentChar(int ch) : This method tells this StreamTokenizer to treat the given character as
the beginning of a comment that ends at the end of the line. The StreamTokenizer ignores all of the characters
from the comment character to the end of the line. By default, a StreamTokenizer treats the '/' character as a
comment character. This method may be called multiple times if there are multiple characters that begin
comment lines.
public int nextToken() throws IOException : This method reads the next token from the stream. The value
returned is the same as the value of the variable ttype. The nextToken() method parses the following tokens:
TT_EOL The end of a line has been reached. The eolIsSignificant() method controls whether end-
of-line characters are treated as whitespace or returned as TT_EOL tokens.
TT_NUMBER A number has been parsed. The value can be found in the variable nval. The
parseNumbers() method tells the StreamTokenizer to recognize numbers distinct from words.
TT_WORD A word has been parsed. The word can be found in the variable sval.
Quoted string A quoted string has been parsed. The variable ttype is set to the quote character, and sval
contains the string itself. You can tell the StreamTokenizer what characters to use as quote characters using
quoteChar( ).
Character A single character has been parsed. The variable ttype is set to the character value.
public void ordinaryChar(int ch) : This method causes this StreamTokenizer to treat the given character
as an ordinary character. This means that the character has no special significance as a comment, string
quote, alphabetic, numeric, or whitespace character. For example, to tell the StreamTokenizer that the slash
does not start a single-line comment, use ordinaryChar('/').
public void pushBack( ) : This method has the effect of pushing the current token back onto the stream.
In other words, after a call to this method, the next call to the nextToken() method returns the same result as
the previous call to the nextToken()method without reading any input.
92 SATEESH N
SATEESH N
public void slashSlashComments(boolean flag) : By default, a StreamTokenizer does not recognize
double-slash comments. However, if you call slashSlashComments(true), the nextToken() method recognizes
and ignores double-slash comments.
public void slashStarComments(boolean flag) : By default, a StreamTokenizer does not recognize slash-star
comments. However, if you call slashStarComments(true), the nextToken() method recognizes and ignores
slash-star comments.
public void wordChars(int low, int hi) : This method causes this StreamTokenizer to treat characters in the
specified range as characters that are part of a word token, or, in other words, consider the characters to be
alphabetic. A word token consists of a sequence of characters that begins with an alphabetic character and is
followed by zero or more numeric or alphabetic characters.
public void quoteChar(int ch) : This method tells this StreamTokenizer to treat the given character as the
beginning or end of a quoted string. By default, the single-quote character and the double-quote character are
string-quote characters. When the parser encounters a string-quote character, the ttype variable is set to the
quote character, and sval is set to the actual string. The string consists of all the characters after (but not
including) the string-quote character up to (but not including) the next occurrence of the same string-quote
character, a line terminator, or the end of the stream.
Word: DOB
Example: : encountered.
Word: Date
import java.lang.System; - encountered.
import java.io.StreamTokenizer; Number: 3.0
import java.io.InputStreamReader; Word: Month
import java.io.BufferedReader; - encountered.
import java.io.IOException; Number: 10.0
Word: Year
public class StreamTokenizer_Ex1 - encountered.
{ Number: 1979.0
public static void main(String args[]) throws IOException EOF encountered.
{
BufferedReader inData = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer inStream = new StreamTokenizer(inData);
inStream.commentChar('#');
boolean eof = false;
do
{
int token=inStream.nextToken();
// Parse according to input token
switch(token)
{
case StreamTokenizer.TT_EOF: System.out.println("EOF encountered.");
eof = true;
break;
case StreamTokenizer.TT_EOL: System.out.println("EOL encountered.");
break;
case StreamTokenizer.TT_WORD: System.out.println("Word: "+inStream.sval);
break;
case StreamTokenizer.TT_NUMBER:System.out.println("Number:
"+inStream.nval);
break;
default: System.out.println((char) token+" encountered.");
if(token=='!')
eof=true;
}
} while(!eof);
}
}
93 SATEESH N
SATEESH N
Did you know that Java makes it easy to read and write Zip files? Zip support manifests itself in the
standard class library by way of the ZipInputStream and ZipOutputStream filter stream classes, and other
classes that (along with ZipInputStream and ZipOutputStream) are part of the java.util.zip package. By using
those classes, it is possible to create a command-line version of the popular WinZip utility.
In t e g e r c la ss :
p u b l i c st a t i c i n t p a r se I n t ( S t r i n g st r ) t h r o w s N u m b e r F o rm at Ex c e pt i o n
T h e p a r se I n t f u n c t i o n av ai l a b l e i n t h e i nt e g e r c l a ss t a k e s a st r i n g a n d c o n v e rt s
i n t o t h e n um e r i c f o rm a t .
/ / f i l e n am e : i n t e cl a s . j a v a
/ / t o a cc e p t 2 n um b e r s f r om t h e k e y b o a r d a n d d i sp l a y t h e t o t al .
i m p o r t j av a. i o. * ;
i m p o r t j av a. l a n g . *;
c l a ss i n t e c l a s
{
p u b l i c st a t i c v o i d m ai n ( S t ri n g a r g s[ ] )
{
try
{
// key board
B uf f e r e d R e a d e r st d i n = n e w B uf f e r e d Re a d e r ( n e w I n p u t S t r e a m R e a d e r ( S y st em . i n ) );
S t ri n g st r ;
i nt a , b, c ;
S y st em . o u t . p r i nt l n ( "E n t e r a n um b e r : ") ;
st r = st d i n . r e a d L i n e ( st r ); Out put:
E:\Core>javac inteclas.java
a = I nt e g e r . p a r se I n t ( st r ) ; E:\Core>java inteclas
S y st em . o u t . p r i nt l n ( "E n t e r a n o t h e r : " ) ; Enter a number :
10
st r = st d i n . r e a d L i n e ( st r ); Enter another :
20
b = I nt e g e r . p a r se I n t ( st r ) ; Total is : 30
E:\Core>
c = a + b;
S y st em . o u t . p r i nt l n ( "T o t al i s : "+ c );
}
c a t c h ( N um b e rF o rm a t Ex c e p t i o n ex )
{
S y st em . o u t . p r i nt l n ( " C o nv e r si o n f i n al " );
}
c a t c h (I O Ex c e p t i o n ex )
{
S y st em . o u t . p r i nt l n ( "E r r o r : "+ ex );
}
}
}
94 SATEESH N
SATEESH N
M U L T I T H R E AD I N G :
O n e of t h e m ai n a dv a n t a g e i n j av a p r o g ra m m i n g i s, i t su p p o r t s m u l t i t h r e a d e d
p r o g r a m s.
A m u l t i t h r e a d e d p r o g r a m i s p r o g r a m t h a t c o n t a i n s 2 o r m o r e p a rt s t h a t r u n s
c o n c u r r e n t l y. E a c h p a rt of a p r o g r am i s c a l l e d a t h r e a d .
M u l t i t h r e a di n g e n a b l e s u s t o r u n m u l t i p l e pa r t s o f t h e p r o g r am at t h e sa m e t i m e .
Creating a Thread : I n j av a a t h r e a d c a n be c r e a t e d i n 2 wa y s.
i . u si n g t h e T h r e a d cl a ss i i . U si n g R u nn a b l e i nt e rf a c e
i . T h r e a d c l a ss : T h r e a d c l a s s i s t h e m a i n c l a s s t o m a n a g e a l l t h e t h r e a d s i n a j av a
p r o g r a m . i . e . , t h r e a d s t h a t a r e c r e a t e d ei t h e r b y t h e T h r e a d cl a ss o r wi t h h e l p of
R u n n a b l e i n t e rf a c e c a n o n l y b e c o n t r ol l e d by t h e T h r e a d c l a ss.
E a c h T h r e a d c o n t ai n s n a m e , p ri o r i t y , T h r e ad g r o u p e t c . ,
C o n st r u c t o r s:
T h r e a d ( S t ri n g n am e ) : cr e a t e s a t h r e a d wi t h sp e c i f i e d n am e.
T h r e a d ( ) : c r e a t e s a t h r e a d wi t h a d ef a ul t n a m e .
T h r e a d ( R u n n a b l e r , S t ri n g n am e ) :
C r e a t e s a t h r e a d u si n g t h e r u n n a b l e i n t e rf a c e .
Thread(Runnable r) :
M e t h o d s:
v oi d st a r t ( ) : st a r t s t h e T h r e a d . i . e . , t h e t h r e a d wi l l b e a d d e d t o t h e t h r e a d Q u e u e
S t ri n g g e t N am e ( ) : R e t u r n s t h e n am e of t he t h r e a d .
v oi d se t N a m e (S t ri n g n e wN a m e ) : c h a n g e s t h e n a m e of t h e T h r e a d .
v oi d se t P ri o r i t y (i n t p ri o ri t y) : C h a n g e s t h e p r i o r i t y of t h e T h r e a d . Mi n. p ri o r i t y i s: 1
M a x . p ri o r i t y i s: 2
d ef a u l t i s : 5
i n t g et P ri o r i t y ( ) : R e t u r n s t h e c u r r e n t p ri o ri t y of t h e t h r e a d .
b o o l e a n i n l i v e ( ) : R e t u r n s t r u e i f t h e T h r e ad i s st i l l r u n n i n g , o t h e r wi se f al se .
st a t i c T h r e a d c u r r e n t T h r e a d ( ) : R e t u r n s t h e c u r r e n t t h r e a d .
v oi d i n t e r r u p t ( ) : I n t e r r u p t s a sl e e p i n g t h r e a d .
M a i n T h r e a d : W h e n ev er we r u n a j av a p r o g r a m t h e p r o g r a m wi l l b e p l a c e d i n a n
a l r e a d y r u n n i n g t h r e a d wh i c h i s k n o wn a s m ai n T h r e a d . Al l t h r e a d s t h a t a r e c r e a t e d i n
t h e p r o g r a m wi l l b e t h e c h i l d t h r e a d s o f t h e m ai n T h r e a d . W h e n ev e r t h e m ai n T h r e a d
st o p s t h e p r o g r a m wi l l b e t e rm i n a t e d .
I n t h e f ol l o wi n g e x am pl e a r e f e r e n c e of t he m ai n T h r e a d wi l l b e o b t a i n e d u si n g
the current Thread f uncti on.
95 SATEESH N
SATEESH N
Ex: v oi d m ai n ( )
{
T h r e a d r = T h r e a d . c u r r e nt T h r e a d ( );
r. sl e e p ( 2 0 0 0 ) ;
-- --- --
- - - - - --
}
/ / f i l e n am e : thread.java
/ / T h e f ol l o wi n g p r o g r a m p ri n t s t h e v al u es f r om 1 t o 1 0 , f o r e a c h i t e r at i o n t h e m ai n
T h r e a d sl e e p s f o r 1 se c o n d .
c l a ss t h r e a d
{
p u b l i c st a t i c v o i d m ai n ( S t ri n g a r g s[ ] ) Out put:
{
Thread r = Thread.currentThread(); / / m ai n T h r e a d E:\Core>javac thread.java
E:\Core>java thread
f or ( i nt i = 0; i < = 1 0 ; i + + )
Count is : 0
{
Count is : 1
S y st em . o u t . p ri n t l n ( " C o u n t i s: "+ i ) ;
Count is : 2
Count is : 3
try
Count is : 4
{
Count is : 5
r. sl e e p ( 1 0 0 0 ) ;
Count is : 6
} Count is : 7
c a t c h ( I n t e r r u p t e d Ex c e p t i o n ex ) Count is : 8
{ Count is : 9
S y st em . o u t . p ri n t l n ( " M ai n T h r e a d I n t er r u p t e d " ) ; Count is : 10
} Finished . . .
}
S y st em . o u t . p ri n t l n ( " F i ni sh e d . . . " ); E:\Core>
}
}
/ / f i l e n am e : th r e a d 2 . j a v a Out put:
/ / sam e a s a b ov e p r o g r am E:\Core>javac thread2.java
E:\Core>java thread2
c l a ss t h r e a d 2 Count is : 0
{ Count is : 1
p u b l i c st a t i c v o i d m ai n ( S t ri n g a r g s[ ] ) Count is : 2
{ Count is : 3
f or ( i nt i = 0; i < = 1 0 ; i + + ) Count is : 4
{ Count is : 5
S y st em . o u t . p ri n t l n ( " C o u n t i s: "+ i ) ; Count is : 6
try Count is : 7
{ Count is : 8
T h r e a d . sl e e p ( 1 0 0 0 ) ; / / M a i n T h re a d Count is : 9
} Count is : 10
c a t c h ( I n t e r r u p t e d Ex c e p t i o n ex ) Finished . . .
{
S y st em . o u t . p ri n t l n ( " M ai n T h r e a d I n t er r u p t e d " ) ; E:\Core>
}
}
S y st em . o u t . p ri n t l n ( " F i ni sh e d . . . " );
}
}
96 SATEESH N
SATEESH N
c r e a t i ng a T h r ead u s i ng t h r ea d c l a s s : T h e f i r st wa y o f c r e a t i n g a t h r e a d , i s t o
c r e a t i n g a c l a ss t h a t ex t e n d s t h e T h r e a d cl a ss. W h e n ev e r a c l a ss e x t e n d s t h e T h r e a d
c l a ss t h e f ol l o wi n g f u n c t i o n sh o u l d b e ov er ri d d e n .
p u b l i c v oi d r u n ( ) : W h e n ev e r we st a r t t h e t h r e a d u si n g t h e st a r t m e t h o d t h e t h r e a d wi l l
b e a d d e d t o t h e t h r e a d q u e u e a n d t h e t h r e a d c a l l s t h e r u n ( ) f u n c t i o n . i . e, a l l t h e
st a t e m e n t s i n t h e r u n ( ) f u n ct i o n wi l l b e ex ec u t e d i n a se p a r a t e p r o c e s s.
/ / f i l e n am e : mu l th r e a d . j a v a
st
/ / I n t h e f o l l o wi n g e x am pl e 2 t h r e a d s wi l l b e c r e a t e d , t h e 1 t h r e a d p r i n t s t h e v al u e s
nd
f r om 1 t o 1 0 wi t h t i m e of 1 se c . . f o r e a c h i t e r a t i o n , t h e 2 t h r e a d p ri n t s t h e v al u e s
f r om 3 0 t o 2 6 wi t h t h e g a p o f 2 se c . f o r e a c h i t e r a t i o n , b o t h t h e t h r e a d s a r e u si n g
a r o u n d 1 0 se c . b o t h t h e t h r e a d s wi l l b e st a r t a t t h e sa m e t i m e .
c l a ss F i r st T h r e a d ex t e n d s T h r e a d Out put:
{
p u bl i c v oi d r u n ( )
E:\Core>javac multhread.java
{ E:\Core>java multhread
f o r (i n t i = 1 ; i < = 1 0 ; i + + ) Second Thread : 30
{ First Thread : 1
S y st em . o u t . p ri n t l n ( "F i r st T h r e a d : "+ i ); First Thread : 2
try Second Thread : 29
{ First Thread : 3
T h r e a d . sl e e p ( 1 0 0 0 ) ; First Thread : 4
} Second Thread : 28
c a t c h ( I nt e r r u p t e d Ex c e p t i o n ex ) First Thread : 5
{ First Thread : 6
S y st em . o u t . p r i nt l n (" F i r st T h r e a d I n t e r r u p t e d " ) ; Second Thread : 27
} First Thread : 7
} First Thread : 8
} Second Thread : 26
c l a ss S e c o n d T h r e a d e x t e n d s T h r e a d First Thread : 9
{ First Thread : 10
p u bl i c v oi d r u n ( )
{
f o r (i n t i = 3 0 ; i > = 2 6 ; i - - ) E:\Core>
{
S y st em . o u t . p ri n t l n ( " S e c o n d T h r e a d : "+ i ) ;
try
{
T h r e a d . sl e e p ( 2 0 0 0 ) ;
}
c a t c h ( I nt e r r u p t e d Ex c e p t i o n ex )
{
Sy st e m . o u t . p ri n t l n ( " S e c o n d T h r e a d I n t e r r u p t e d " ) ;
}
}
}
}
c l a ss m u l t h r e a d
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
F i r st T h r e a d f = n e w F i r st T h r e a d ( ) ;
SecondThread s = new SecondThread();
s. st a r t ( ) ;
f . st a r t ( );
}
}
97 SATEESH N
SATEESH N
/ / f i l e n am e : m y m u l th r e a d . j a v a
/ / t h e f ol l o wi n g p r o g r a m i s e n h a n c e m e n t f or t h e p r ev i o u s p r o g r a m wh i c h p r ov i d e s o n l y
o n e t h r e a d c l a s s wi t h m u l t i pl e i n st a n c e s. F o r t h i s p u r p o se t h e st a r t v a l u e , e n d i n g v a l ue
e t c . , wi l l b e t a k e n a s p a r a m et e r s.
c l a ss M y T h r e a d e x t e n d s T h r e a d Out put:
{
i n t st a r t , e n d , d e l a y; E:\Core>javac mymulthread.java
E:\Core>java mymulthread
M y T h r e a d ( St r i n g n am e, i nt st a r t , i n t e n d , i n t d e l a y ) Second : 26
{ First : 1
se t N a m e ( n am e ) ; First : 2
t hi s. st a r t = st a r t ; Second : 27
t hi s. e n d = e n d ; First : 3
t hi s. d e l a y = d el a y ; First : 4
} Second : 28
First : 5
p u bl i c v oi d r u n ( ) First : 6
{ Second : 29
/ / p ri n t t h e v a l u e s First : 7
First : 8
f o r (i n t i = st a r t ; i < = e n d ; i + + ) Second : 30
{ First : 9
S y st em . o u t . p ri n t l n ( g e t N am e ( ) + " "+ i ) ; First : 10
t ry Finished . . .
{ E:\Core>
T h r e a d . sl e e p ( d e l a y ) ;
}
c a t c h (I n t e r r u p t e d Ex c e pt i o n ex )
{
Sy st e m . o u t . p ri n t l n ( g e t N am e ( )+ " I nt e r u p t e d " ) ;
}
}
}
}
c l a ss m ym ul t h r e a d
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
M yT h r e a d f = n e w M y T h r e a d ( "F i r st " , 1 , 10 , 1 0 0 0 ) ;
M yT h r e a d s = n e w M y T h r e a d ( " se c o n d " , 2 6 , 3 0 , 2 0 0 0 ) ;
s. st a r t ( ) ;
f . st a r t ( ) ;
}
}
C r e a t i ng a T h re ad u s in g R u nn ab l e i n ter f a c e : T h e se c o n d m e t h o d f o r c r e a t i n g a
T h r e a d i s t o c r e a t e a c l a ss t h a t i m pl em e n t s t h e r u n n a b l e i n t e rf a c e . W h e n ev e r a cl a ss
i m pl em e n t s t h e r u n n a b l e i n t e rf a c e t h e c l a s s sh o u l d o v e rr i d e t h e f ol l o wi n g f u n c t i on
public void run( ).
B e c a u se J av a d o e sn ’ t su p p o r t m u l t i p l e I n he r i t e n c e f o r cl a sse s w e c a n u se t h e
r u n n a b l e i n t e rf a c e f o r cr e a t i n g a t h r e a d i n t h e f ol l o wi n g c o n d i t i o n . W h e n we wa n t a
c l a ss t o e x t e n d a n o t h e r c l a ss a n d we w a n t t h i s c l a ss t o wo r k a s a T h r e a d t h e n
r u n n a b l e i n t e rf a c e sh o u l d b e u se d .
98 SATEESH N
SATEESH N
/ / f i l e n am e : r u n i n t r f a c e . j a v a
i m p o r t j av a. l a n g . *;
c l a ss f i r st i m p l em e nt s R u n n a b l e
{ Out put:
p u bl i c v oi d r u n ( ) E:\Core>javac runintrface.java
{ E:\Core>java runintrface
f o r (i n t i = 1 ; i < = 1 0 ; i + + )
{ Second : 30
S y st em . o u t . p ri n t l n ( " F i r st : "+ i ); First : 1
First : 2
t ry Second : 29
{ First : 3
T h r e a d . sl e e p ( 1 0 0 0 ) ; First : 4
} Second : 28
c a t c h (I n t e r r u p t e d Ex c e pt i o n ex ) First : 5
{ First : 6
S y st em . o u t . p r i nt l n (" F i r st I n t e r r u p t e d" ) ; Second : 27
} First : 7
} First : 8
} Second : 26
} First : 9
c l a ss se c o n d i m p l em e n t s R u n n a b l e First : 10
{
p u bl i c v oi d r u n ( ) E:\Core>
{
f o r (i n t i = 3 0 ; i > = 2 6 ; i - - )
{
S y st em . o u t . p ri n t l n ( " S e co n d : " + i );
try
{
T h r e a d . sl e e p ( 2 0 0 0 ) ;
}
c a t c h ( I nt e r r u p t e d Ex c e p t i o n ex )
{
S y st em . o u t . p r i nt l n (" S e c o n d I n t e rr u p t e d " ) ;
}
}
}
}
c l a ss r u n i n t rf a c e
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
f i r st f = n e w f i r st ( ) ;
se c o n d s = n e w s e c o n d ( ) ;
// T h r e a d t 1 = n e w T h r e a d ( f );
// T h r e a d t 2 = n e w T h r e a d ( s) ;
n e w T h r e a d ( s) . st a r t ( ) ;
n e w T h r e a d ( f ) . st a r t ( );
// t 2 . st a r t ( );
// t 1 . st a r t ( );
}
}
99 SATEESH N
SATEESH N
S y n c h r o n i z a ti o n :
S y n c h r o n i z at i o n i s t h e p r o c e ss o f a p p l yi n g q u e u e m e c h a n i sm o n t h r e a d s.
W h e n t wo o r m o r e t h r e a d s a r e t r y i n g t o ac c e ss t h e s a m e sh a r e d d ev i c e a n d i f
t h e d ev i c e c a n ’ t b e sh a r e d t h e n we sh o u l d a p p l y sy n c h r o n i z a t i o n .
S y n c h r o n i z a t i o n c a n b e a c hi ev e d i n t wo wa y s.
i . S y n c h r o ni z e d f u n ct i o n s i i . S y n c h r o n i z e d st a t em e n t s
i . S y n c h ro n i ze d f u n c t io n s : S y n c h r o n i z a t i o n c a n b e a c h i ev e d b y p r ef i x i n g t h e
f u n ct i o n wi t h t h e k e y wo r d sy n c h r o n i z e d .
/ / f i l e n am e: s y n c h p r i n t e r f u n . j a v a
c l a ss p r i n t e r
{
sy n c h r o n i z e d v oi d p ri n t (i n t st a r t , i n t e n d , i n t d e l a y )
{
S y st em . o u t . p r i nt l n ( "[ " );
f o r (i n t i = st a r t ; i < = e n d ; i + + )
{
S y st em . o u t . p ri n t l n ( " "+ i ) ;
}
100 SATEESH N
SATEESH N
c l a ss sy n c h p r i n t e r f u n
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
p r i nt e r p = n e w p r i n t e r ( );
u se r u 1 = n e w u se r ( p , 1 , 1 0 , 1 0 0 0 ) ;
u se r u 2 = n e w u se r ( p , 2 6 , 3 0 , 2 0 0 0 ) ;
u se r u 3 = n e w u se r ( p , 4 1 , 4 5 , 1 5 0 0 ) ;
u 1 . st a r t ( ) ;
u 2 . st a r t ( ) ;
u 3 . st a r t ( ) ;
}
}
i i . S y n ch r o n i ze d st a te m en t s : S u p p o se i f t h e f u n c t i o n o n wh i c h we wa n t o a c h i ev e
sy n c h r o n i z a t i o n i s a t h i r d p a r t y p r o d u c t a n d i f we c a n n o t m o d i f y t h e so u r c e c o d e t h e n
t o a c h i ev e t h e sy n c h r o n i z a t i o n we sh o u l d a p p l y t h e sy n c h r o n i z e d st a t e m e nt s.
I f t h e p r i n t ( ) f u n c t i o n i s n o t sy n c h r o n i z e d , c a l l t h e p r i n t ( ) f u n c t i o n i s a
sy n c h r o n i z e d b l o c k f or t h e o bj e c t p .
/ / f i l e n am e: s y n c h p r i n t e r s t m . j a v a
c l a ss p r i n t e r
Out put:
{
sy n c h r o n i z e d v oi d p ri n t (i n t st a r t , i n t e n d , i n t d e l a y ) E:\Core>javac synchprinterstm.java
{ E:\Core>java synchprinterstm
S y st em . o u t . p r i nt l n ( "[ " );
[
f o r (i n t i = st a r t ; i < = e n d ; i + + ) 1
{ 2
S y st em . o u t . p ri n t l n ( " "+ i ) ; 3
4
try 5
{ 6
T h r e a d . sl e e p ( d e l a y ) ; 7
} 8
c a t c h ( I nt e r r u p t e d Ex c e p t i o n ex ) 9
{ 10
S y st em . o u t . p r i nt l n (" T h r e a d I nt e r r u p t e d " ) ; ]
} [
} 26
27
S y st em . o u t . p r i nt l n ( "] " ); 28
} 29
} 30
c l a ss u s e r e x t e n d s T h r e a d ]
{ [
p ri n t e r p ; 41
42
i n t st a r t , e n d , d e l a y; 43
44
u se r ( p r i n t e r p , i n t st a r t , i n t e n d , i n t d e l a y ) 45
{ ]
t h i s. p = p ;
E:\Core>
101 SATEESH N
SATEESH N
t h i s. st a r t = st a r t ;
t h i s. e n d = e n d ;
t h i s. d e l a y = d e l a y;
}
p u bl i c v oi d r u n ( )
{
p . p ri n t ( st a r t , e n d , d e l a y );
}
c l a ss sy n c h p r i n t e r st m
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
p r i nt e r p = n e w p r i n t e r ( );
u se r u 1 = n e w u se r ( p , 1 , 1 0 , 1 0 0 0 ) ;
u se r u 2 = n e w u se r ( p , 2 6 , 3 0 , 2 0 0 0 ) ;
u se r u 3 = n e w u se r ( p , 4 1 , 4 5 , 1 5 0 0 ) ;
u 1 . st a r t ( ) ;
u 2 . st a r t ( ) ;
u 3 . st a r t ( ) ;
}
}
In t e r T h r e ad C o m m u n i ca t i on : S om e t i me s t h e o u t p u t o f o n e T h r e a d wi l l b e t h e i n p u t
o f a n o t h e r T h r e a d i . e . , i n so m e c a se s a T h r e a d e n t e r s i n t o wa i t i n g st a t e t i l l i t r e c e iv es
i n p u t f r om a n o t h e r T h r e a d . Si m i l a rl y, a T h re a d sh o u l d n o t i f y t h e wa i t i n g T h r e a d , o n c e
the input is ready.
T h e f ol l o wi n g t h r e e f u n c t i o n s o f t h e o b j e c t c l a ss a r e u se d f o r c om m u n i c at i o n
b e t we e n t h e T h r e a d s.
2 . p u b l i c v oi d n o t i f y( ) t h r o w s I n t e r r u p t e d E x ce p t i o n : N o t i f i e s t h e wa i t i n g t h r e a d ,
so t h a t t h e wa i t i n g t h r e a d r e su m e s.
3 . p u b l i c v oi d n o t i f y Al l ( ) t h r o ws I n t e r r u p t e d E x c e p t i o n : N o t i f i e s a l l t h e wa i t i n g
T h r e a d s, t h e T h r e a d wi t h t h e h i g h e st p ri o r i t y wi l l r e su m ef i r st .
/ / f i l e n am e : i n t e r th r e a d . j a v a
/ / F l a g b e c om e s t r u e , i f t h e su p p l i e r p a ss t h e v al u e . F l a g b e c om e s f al se , i f t h e
/ / c o n su m e r c o n su m e s t h e v al u e , i . e. , t h e qu e u e Q wa s e m p t y .
c l a ss Q
{
i n t n;
b o o l e a n f l a g = f a l se ;
sy n c h r o n i z e d v oi d p u t (i n t n )
{
102 SATEESH N
SATEESH N
try
{
i f (f l a g = = t r u e ) / / n o t at c o n su m ed
wa i t ( );
t hi s. n = n ;
S y st em . o u t . p r i nt l n ( "S u p p l i e d : "+ n ) ;
f l a g = t r u e; / / j u st su p p l i e d
n o t i f y ( ); / / i nf o rm t h e c u st om e r
}
c a t c h (I n t e r r u p t e d Ex c e p t i o n ex )
{
S y st em . o u t . p ri n t l n ( " T h r e a d I n t e r r u p t e d" ) ;
}
}
sy n c h r o n i z e d v oi d g e t ( )
{
try
{
i f (f l a g = = f a l se )
wa i t ( ) ; / / n o t su p p l i e d
S y st em . o u t . p ri n t l n ( " C o n su m e d : " + n );
f l a g = f a l se ; / / Q wa s e m p t y Out put:
E:\Core>javac interthread.java
n o t i f y( ) ; / / n o t i f y t h e su p p l i e r
}
E:\Core>java interthread
c at c h ( I n t e r r u pt e d Ex c e p t i o n ex ) Supplied : 1
{ Consumed: 1
S y st em . o u t . p ri n t l n ( "T h r e a d I n t e rr u p t e d " ) ; Supplied : 2
} Consumed: 2
} Supplied : 3
} Consumed: 3
Supplied : 4
c l a ss p r o d u c e r e x t e n d s T h r e a d Consumed: 4
{ Supplied : 5
Q q; Consumed: 5
Supplied : 6
producer(Q q)
Consumed: 6
{ Supplied : 7
t hi s. q = q ; Consumed: 7
} Supplied : 7
p u b l i c v oi d r u n ( ) Consumed: 7
{ Supplied : 8
f o r (i nt i = 1; i < = 2 0 ; i + + ) Consumed: 8
{ Supplied : 9
q . p u t (i ); / / su p p l y 2 0 v al u e s Consumed: 9
} Supplied : 10
} Consumed: 10
} E:\Core>
c l a ss c o n s u m e r ex t e n d s T h r e a d
{
Q q;
c o n su m e r (Q q )
{
t h i s. q = q ;
}
103 SATEESH N
SATEESH N
p u b l i c v oi d r u n ( )
{
f or ( i nt i = 1; i < = 2 0 ; i + + )
{
q. g e t ( ) ; / / r e c e i v e 2 0 v a l u e s f r om t he q u e
}
}
}
c l a ss i n t e r t h r e a d
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
Q q = new Q();
c o n su m e r c = n e w c o n su m e r ( q ) ;
c. st a r t ( ) ;
p . st a r t ( ) ;
}
}
104 SATEESH N
SATEESH N
j a va . u ti l. p a c ka g e :
StringTokenizer Class :
Often an input String contains several groups of characters, where each group acts as a unit
that has significance. Such a group is called a token. Tokens are separated from each other by delimiter
characters. For example, say that you need to add up the following numbers:
12 8 5 32
You automatically group these characters to form four integers separated by spaces. The tokens in
this case are 12 and 8 and 5 and 32. These tokens are delimited by the space character.
The StringTokenizer class aids in breaking a String into tokens. You can use the default delimiters,
or specify your own. The default delimiters are: space, tab, newline, and carriage return.
StringTokenizer constructors :
public StringTokenizer( String arg ) : Create a StringTokenizer based on String, using the default
delimiters.
public StringTokenizer( String arg, String delimit) : Create a StringTokenizer based on String, using
the individual characters in delimit as delimiters.
public StringTokenizer( String arg, String delimit, boolean ret) : As above, but if ret is true, then
individial delimiters count as tokens also.
The StringTokenizer class is found in java.util, which must be imported for the program to compile.
import java.io.*;
import java.util.*;
System.out.print("Enter a string:");
String data = stdin.readLine();
while ( tok.hasMoreTokens() )
System.out.println( tok.nextToken() );
} output :
}
Enter a string: sateesh kumar
sateesh
kumar
105 SATEESH N
SATEESH N
More than one Delimiter Works :
Tokens can be separated by more than one delimiter. There are several spaces separating the
tokens in the example.
StringTokenizer Methods :
int countTokens( ) : Return the number of tokens remaining. , The countTokens() method starts with the
total number of tokens the String has been broken into. countTokens() will report one less token.
String nextToken( ) : Return the next token. , Each time nextToken() is called, one token (starting with
the first) is consumed, and
User-specified Delimiters
Here is the program again, but this time with the delimiters specified in the constructor. The delimiters are
now space, equals, plus, and minus.
/ / F i l e n am e : S t rT o k 2 . j a v a
import java.io.*;
import java.util.*;
System.out.print("Enter a string:");
String data = stdin.readLine();
StringTokenizer tok =
new StringTokenizer( data, " =+-" ); // note the space before =
while ( tok.hasMoreTokens() )
System.out.println( tok.nextToken() );
}
}
o u tp u t :
Enter a string:c = a + b
c
a
b
106 SATEESH N
SATEESH N
Returning Delimiters
You probably regard the "=" and the "+" symbols as important, so they should be regarded as tokens. But
"+" also needs to work as a delimiter so that "12+8" is broken into the tokens "12", "+" and "8". This is done by
using true as the third parameter in the constructor: Now individual delimiters (as well as tokens) are
returned by nextToken().
/ / F i l e n am e : S t rT o k 3 . j a v a
o u tp u t :
import java.io.*;
Enter a string:
import java.util.*;
c = a + b
public class StrTok3
c
{
public static void main ( String[] args ) throws IOException
=
{
BufferedReader stdin =
a
new BufferedReader(new InputStreamReader(System.in));
+
System.out.print("Enter a string:");
String data = stdin.readLine();
b
StringTokenizer tok =
new StringTokenizer( data, " =+-", true ); // note the space before =
while ( tok.hasMoreTokens() )
System.out.println( tok.nextToken() );
}
}
D a t e , C a l e n d a r a n d GregorianCalendar Classes :
The various responsibilities for handling dates have been distributed among the following classes:
Abstract java.util.Calendar
java.util.GregorianCalendar extends Interpretation and manipulation of Dates.
java.util.Calendar
107 SATEESH N
SATEESH N
The java.util.Date class can be used to construct objects that represent a specific point in time, with
millisecond accuracy. Obviously to interpret a point in time correctly, you also need to know what calendar and
what timezone is appropriate. There are classes in the java.util package that provide this frame of reference.
The default no arguments constructor, builds a Date object that represents 'now'. Date also has a number of
deprecated (obsolete) methods for getting a date at a specific point in time.
The java compiler will warn you if you use methods marked with the javadoc @deprecated statement
in your own classes, as a rule the javadoc should refer you to the newer or better alternative method to use.
A Calendar provides 3 methods set() add() and roll() that you can use to change a 'field' in the
Calendar, and a get() method you can use to retrieve the value of a field. If you look at the java.util.Calendar
class, you'll notice it defines a bunch of integer class constants, with names like DAY_OF_MONTH and
MONTH. You use these to identify to the methods, which field you are changing, for example
You'll want to read the javadoc for the Calendar class, which explains the difference between the add()
and roll() methods, and the various rules and side effects to manipulating a Calendar.
108 SATEESH N
SATEESH N
Again, you'll want to see the javadoc for the SimpleDateFormat class for more details. Here is an
example of how to parse a String into a java.util.Date.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
class SimpleDateForm
{
public static void main(String args[])throws Exception
{
// Getting the Date in simple date format
Date td = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String today = sdf.format(td);
System.out.println("Todays Date is: "+today);
/* Getting the year as int from Date object you need to add 1900 to it to
get the 4 digit year.
The getYear() method returns the number of years elapsed after the year
1900.
So if it's the year 2000 now, mydate.getYear() will return 100. So
100 +
1900 = 2000. */
output :
import java.util.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
class GetDayName
{
public static void main(String[] args)
{
Date date1 =(new GregorianCalendar(1989, Calendar.OCTOBER, 17)).getTime();
Date date2 = new Date();
System.out.println("1989-10-17 was a " + sayDayName(date1));
System.out.println("Today is a " + sayDayName(date2));
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
today_date = df.parse(today_str);
System.out.println(today_date.toString());
System.out.println(cur_date.toString());
if(today_date.before(cur_date))
{
System.out.println("Before");
}
else if(today_date.after(cur_date)) output :
{
System.out.println("After"); Tue Jan 04 00:01:00 IST 2005
} Sat Feb 19 02:15:09 IST 2005
else -1
{ Before
System.out.println("Equal");
}
}
}
// Validate a date
import java.util.*;
import java.text.*;
public class ValidateDate
{
public static void main(String[] args)
{
// Using DateFormat
String dt = "1990/10/88"; // throws a ParseException
// String dt = "1990-10/10"; // throws a ParseException
// String dt = "1990-10-35"; // throws a IllegalArgumentException
try
{
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
df.setLenient(false); // this is important!
111 SATEESH N
SATEESH N
Date dt2 = df.parse(dt);
System.out.println("Date is ok = " + dt2);
}
catch (ParseException e)
{
System.out.println(e.getMessage());
}
catch (IllegalArgumentException e)
{
System.out.println("Invalid date");
}
// Using SimpleDateFormat
String sdt = "050219";
String fdt = "yyMMdd";
try
{
SimpleDateFormat sdf = new SimpleDateFormat(fdt);
sdf.setLenient(false);
Date dt2 = sdf.parse(sdt);
System.out.println("Date is ok = " + dt2 + "(" + sdt + ")");
}
catch (ParseException e)
{
System.out.println(e.getMessage());
}
catch (IllegalArgumentException e)
{
System.out.println("Invalid date");
}
112 SATEESH N
SATEESH N
Collections :
Collections are a vital part of any programming language. They allow many objects to be collected
together and stored as one. Although arrays collect objects together, they are not considered collections in
JAVA. We'll look here at the most commonly used collection
add(Object obj) - adds the given object as an element to the collection (its location is not specified)
addAll(Collection c) - same as above but adds ALL elements specified in the given collection
parameter.
remove(Object obj) - removes the given object from the collection (uses .equals() method for
comparison)
removeAll(Collection c) - same as above but removes ALL elements specified in the given collection
parameter.
retainAll(Collection c) - same as above but removes all elements EXCEPT THOSE specified in the
given collection parameter.
clear( ) - empties out the collection by removing all elements.
Until now, we've just looked at the interfaces ... so what about the actual collection classes ? Well, there are
many collection classes and they are arranged in a hierarchy which contains both abstract and concrete
classes. Here are just a few:
Notice that there are 4 abstract classes and 6 concrete classes shown.
All classes inherit from AbstractCollection, which contains common behaviour for all collections.
All classes (or their parents) implement one of the Collection interfaces.
The classes seem to be split as either having a List behaviour or a Set behaviour, but not both.
113 SATEESH N
SATEESH N
The List Classes
Lets now examine the classes that implement the List interface (i.e., Vector, ArrayList, Stack and
LinkedList):
are ordered
may contain duplicates
have indexable elements (using zero-based indexing).
So we can add many mixed kinds of objects and they are kept ordered sequence (which often depends on the
order that we added them). We can later on, access or modify particular elements according to their index
(i.e., location in the collection). As we will see, Stacks and LinkedLists have further restrictions.
Vector
a general kind of list with many useful accessing/modifying/searching
methods
a synchronized class
ArrayList
also general like Vectors
an unsynchronized class (faster than Vectors)
LinkedList
Stack
114 SATEESH N
SATEESH N
Vectors and ArrayLists
Arrays have a fixed size ... they cannot grow or shrink in response to an application's changing storage
requirements. JAVA has a class called Vector for just this purpose. In more recent versions of JAVA (i.e.,
Java2) there is another class called ArrayList that has the same functionality as the Vector class.
Once created, you can then apply any of the standard collection methods (plus others):
Notice that the Vector and ArrayList are used the same way once created !!! If you do not care about
synchronization, use ArrayList instead of Vector.
When extracting elements from a Vector or an ArrayList (or in fact ANY collection at all), the element is
returned as type Object.
To get the Customers back out later, we must type-cast the result of the get(int index) method:
115 SATEESH N
SATEESH N
System.out.println(c.getName());
}
Vector Consturctors :
Vector( ) : Constructs an empty vector so that its internal data array has size 10 and its standard capacity
increment is zero.
Vector(Collection c) : Constructs a vector containing the elements of the specified collection, in the
order they are returned by the collection's iterator.
Vector(int initialCapacity) : Constructs an empty vector with the specified initial capacity and with its
capacity increment equal to zero.
Vector(int initialCapacity, int capacityIncrement) : Constructs an empty vector with the specified
initial capacity and capacity increment
ArrayList Constructors:
ArrayList(Collection c) : Constructs a list containing the elements of the specified collection, in the order
they are returned by the collection's iterator.
ArrayList(int initialCapacity) : Constructs an empty list with the specified initial capacity.
Example :
import java.awt.*;
import java.util.*;
mv.addElement("Hello");
mv.addElement(Color.red);
mv.addElement(new Integer(99));
}//End of amethod
}
116 SATEESH N
SATEESH N
out put :
Hello
java.awt.Color[r=255,g=0,b=0]
99
Many methods in Java return Enumerations instead of Collections or Vectors (e.g., elements())
Enumerations are not supported by ArrayLists, instead, ArrayLists use Iterators, which are also supported
by Vectors. Enumerations are widely used in JAVA. Many, many methods that need to return collections of
objects, often do so by returning the elements as an Enumeration. Even though Enumerations are "old
news", we still discuss them here because there are still many JAVA enterprise methods that return
Enumerations ... and we want to know how to use them.
Users make successive calls to nextElement( ) to obtain the elements from the collection. Normally we use a
while loop with hasMoreElements( ) as the sole condition:
Enumeration e = v.elements( );
while (e.hasMoreElements( ))
{
Customer c = (Customer)v.nextElement();
System.out.println(c.getName());
}
Example :
import java.util.Vector;
import java.util.Enumeration;
public class Enumeration_Ex1
{
public static void main(String args[])
{
Enumeration names;
Vector VNames = new Vector();
VNames.add("Sateesh");
VNames.add("Tharni");
VNames.add("Srinu");
VNames.add("Ravi");
names = VNames.elements();
while (names.hasMoreElements())
System.out.println(names.nextElement());
}
}
117 SATEESH N
SATEESH N
out put:
Sateesh
Tharni
Srinu
Ravi
Another common mistake is to remove from the collection that is being enumerated through. If for
example we want to enumerate through some items in a vector and remove items as well from the vector, then
this does not work properly. For some reason, JAVA does not allow you to remove from a collection that you
are enumerating through !! Consider this (logically correct) example, and then look at the output to follow:
Example :
import java.util.Vector;
import java.util.Enumeration;
public class Enumeration_Ex2
{
public static void main(String args[])
{
String[] num = {"one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten"};
int elementno = 1;
while(nums.hasMoreElements())
{
String aString = (String)nums.nextElement();
System.out.println(elementno+" "+aString);
if(aString.length() > 4)
aVector.remove(aString); // during this statement element
no and element will be changed
elementno++;
}
System.out.println("After Vector: " + aVector);
}
}
out put:
Before Vector: [one, two, three, four, five, six, seven, eight, nine, ten]
Element NO. Element
1 one
2 two
3 three
4 five
5 six
6 seven
7 nine
8 ten
After Vector: [one, two, four, five, six, eight, nine, ten]
118 SATEESH N
SATEESH N
Notice that the Enumeration did NOT produce all the items. Also, the Vector, after removing, is not correct
since the "eight" string was NOT removed as it should have been. This is a problem with Enumerations.
The moral is ... don't use Enunerations if you are gonna be removing from the collection that you are
enumerating through!
To solve this problem, we can use an Iterator. An iterator is a tool like Enumerations for iterating (i.e.,
traversing) through the elements of a collection. To get an iterator, send the iterator() message to a
collection (such as a Vector):
aVector.iterator();
Iterators are very much like Enumerations, but they have additional capability to remove from the collection
which is being iterated through.
The only item that can be removed is the last one that was returned from a call to next( ).
The item is removed from the underlying collection, not from the iterator.
Here is how to use the iterator in a similar example to that above:
Example :
import java.util.Vector;
import java.util.Iterator;
Before Vector: [one, two, three, four, five, six, seven, eight, nine, ten]
Element NO. Element
1 one
2 two
3 three
4 four
5 five
6 six
7 seven
8 eight
9 nine
10 ten
After Vector: [one, two, four, five, six, nine, ten]
HashTable :
Hashtables are an extremely useful mechanism for storing data. Hashtables work by mapping a key to
a value, which is stored in an in-memory data structure. Rather than searching through all elements of the
hashtable for a matching key, a hashing function analyses a key, and returns an index number. This index
matches a stored value, and the data is then accessed.
You can use a String, for example, as a key, or perhaps a number such as an Integer. However, you can't use
a primitive data type, so you'll need to instead use Char, Integer, Long, etc.
Data is placed into a hashtable through the put method, and can be accessed using the get method. It's
important to know the key that maps to a value, otherwise its difficult to get the data back. If you want to
process all the elements in a hashtable, you can always ask for an Enumeration of the hashtable's keys. The
get method returns an object, which can then be cast back to the original object type.
Example :
package util.Collections;
import java.util.*;
/* To demonstrate hashtables, I've written a little demo that adds one hundred strings to a hashtable. Each
string is indexed by an Integer, which wraps the int primitive data type. Individual elements can be returned, or
the entire list can be displayed. Note that hashtables don't store keys sequentially, so there is no ordering to
the list. */
for (; e.hasMoreElements(); )
{
hashkey = Integer.parseInt(e.nextElement().toString());
System.out.println (hash.get(new Integer(hashkey)));
}
}
}
out put :
Number : 5
Number : 21
Displaying all values of Hashtable.. (Hashtable is unordered )
Number : 20
Number : 41
Number : 62
Number : 83
Number : 40
etc...
You cannot have elements with duplicate keys. If you add a new element that duplicates the key of an
existing element, it will replace it.
Hashtables don't permit duplicates. What do you do if some of your objects have duplicate keys?
When you have duplicates, what do you want to find when you do a lookup? Just the first, just the last? both?
If you are clever, you ca get all those behaviours with a Hashtable.
To get the first duplicate, before you put, do a check to see if the element is already in the Hashtable,
if so, do nothing.
To get the last duplicate, just put. It will replace what was there before. To get both, store an ArrayList as the
value. Store each of the duplicates in one of the slots of the ArrayList. This is a bit inefficient for non-
duplicates. For them, you could store just the plain Object. Any you might handle the special case of just one
duplicate with an array. Your logic might look a bit like this:
Example :
121 SATEESH N
SATEESH N
Dictionaries
The abstract Dictionary class describes the interface for working with key-value maps. The way a
dictionary works is if you provide an object as a key, it will return at most one object as its value from the
collection. If the key isn't in the map, you get nothing back, or null in Java terms. The same object can be the
value for multiple keys. However, the key can only be the handle for one value term. How the actual key-value
pairs are stored is dependent on the specific implementation.
Example :
import java.util.*;
public class AssocArray_Dictionary extends Dictionary
{
private Vector keys = new Vector();
private Vector values = new Vector();
// Test it:
public static void main(String[] args)
{
AssocArray_Dictionary aa = new AssocArray_Dictionary();
out put:
Uppercase: S
Uppercase: A
Uppercase: T
Uppercase: I
Uppercase: S
Uppercase: H
BitSet
A BitSet is really a Vector of bits, and it is used if you want to efficiently store a lot of on-off
information. It’s efficient only from the standpoint of size; if you’re looking for efficient access, it is slightly
slower than using an array of some native type.
In addition, the minimum size of the BitSet is that of a long: 64 bits. This implies that if you’re storing anything
smaller, like 8 bits, a BitSet will be wasteful, so you’re better off creating your own class to hold your flags.
In a normal Vector, the collection will expand as you add more elements. The BitSet does this as well – sort
of. That is, sometimes it works and sometimes it doesn’t, which makes it appear that the Java version 1.0
implementation of BitSet is just badly done. (It is fixed in Java 1.1.) The following example shows how the
BitSet works and demonstrates the version 1.0 bug:
Example :
// Demonstration of BitSet
short st = (short)rand.nextInt();
BitSet bs = new BitSet();
for(int i = 15; i >=0; i--)
if(((1 << i) & st) != 0)
bs.set(i);
else
bs.clear(i);
System.out.println("short value: " + st);
printBitSet(bs);
int it = rand.nextInt();
BitSet bi = new BitSet();
for(int i = 31; i >=0; i--)
if(((1 << i) & it) != 0)
bi.set(i);
else
bi.clear(i);
System.out.println("int value: " + it);
printBitSet(bi);
out put:
Stack
A Stack is sometimes referred to as a “last-in, first-out” (LIFO) collection. That is, whatever you “push”
on the Stack last is the first item you can “pop” out. Like all of the other collections in Java, what you push and
pop are Objects, so you must cast what you pop.
What’s rather odd is that instead of using a Vector as a building block to create a Stack, Stack is
inherited from Vector. So it has all of the characteristics and behaviors of a Vector plus some extra Stack
behaviors. It’s difficult to know whether the designers explicitly decided that this was an especially useful way
to do things, or whether it was just a naïve design.
We all know that a stack is a collection of items that are placed or "stacked" on top of one another.
The very definition of a stack implies a last-in-first-out protocol when accessing the items. That is, when
placing items in the stack, we put them at the top and when removing them, we always take the top one off.
Although Stack inherits many other methods from its superclasses, here are the standard Stack methods:
push(Object obj) - place the given object on the top of the stack and return a reference to it.
pop() - remove and return the top element of the stack. If there are no elements in the stack, an error
occurs.
peek() - return the top element of the stack without removing it. If there are no elements in the stack,
an error occurs.
empty() - return whether or not there are any elements in the stack.
search(Object obj) - return the distance of the given object from the top of the stack. The topmost
element has position 1. If the object is not found in the stack, -1 is returned. If duplicates exist, the
position of the topmost one is returned.
Here’s a simple demonstration of Stack that reads each line from an array and pushes it as a String:
Example :
import java.util.*;
System.out.println("popping elements:");
while(!stk.empty())
System.out.println(stk.pop());
}
}
output :
Lang Package
126 SATEESH N
SATEESH N
A p p l e t s & A W T ( A b s t ra c t Wi n dow To ol k i t ) :
Ap p l e t : A n A p p l e t i s a p r o g r a m d e si g n e d i n j av a a n d wi l l b e pl a c e d o n t h e se rv e r.
T h e a p p l e t wi l l b e d o wn l o a d e d f r om t h e se r v e r t o t h e cl i e nt a l o n g wi t h “ H T M L ”
d o c u m e n t s a n d r u n s i n t h e c l i e n t s we b b r o w se r ( i . e . , a n A p p l e t wi l l r u n a s a p a r t of t he
we b d o c u m e n t ) . A n a p p l e t c a n c o n t ai n c o m p o n e n t s l i k e b u t t o n s, c h e c k b o x e s e t c . , An
a p p l e t c a n o p e n c o n n e c t i o n wi t h t h e n e t wo r k se rv e r s, d a t a b a se se r v e r s e t c. ,
AW T : AW T i s a c o l l e c t i o n of c l a sse s wh i c h p r ov i d e s g r a p h i c a l c om p o n e n t s su c h a s
b u t t o n s, t ex t b ox e s e t c . , wh i c h wi l l b e u se d i n t h e g r a p h i c al i n t e rf ac e p r o g r am m i n g .
C r e a t i n g a n A p pl e t : T o c r e a t e a n A p p l e t cr e a t e a cl a ss t h a t e x t e n d s t h e A p p l e t c l a ss.
/ / f i l e n am e : a p p l e t 1. j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ;
p u b l i c c l a ss a p p l e t 1 ex t e n d s A p p l e t Out put :
{
p u bl i c v oi d i n i t ( ) E:\Core> javac applet1.java
{
E:\Core>appletviewer applet1.html
se t B a c k g r o u n d ( C o l o r . o r a n g e ) ;
}
p u bl i c v oi d p a i nt ( G r a p hi c s g )
{
g . se t F o n t ( n e w F o n t ( "G a r am o u n d " , F o n t . B O L D , 2 0 ) ) ;
g . se t C o l o r ( C o l o r. b l u e ) ;
g . d r a wS t r i n g ( " S AT E ES H " , 1 0 0 , 5 0 ) ;
g . se t C o l o r ( C o l o r. r e d ) ;
g . d r a wS t r i n g ( "T e st i n g t h e A p p l e t i n J av a " , 1 0 0 , 1 5 0 ) ;
}
}
W h e n ev e r a n A p p l e t i s b e i n g l o a d e d i n a W EB b r o ws e r , t h e W E B b r o wse r c a l l s
t h e f ol l o wi n g m e t h o d s of t h e A p p l et . W e c an ov e r ri d e t h e f ol l o wi n g m et h o d s d e p e n d i n g
o n t h e r e q u i r em e n t .
1 . p u b l i c v o i d i ni t ( ) : T hi s m e t h o d wi l l b e c a l l e d wh e n ev e r t h e a p pl e t i s b e i n g l o a d e d
i n t o t h e W EB b r o wse r f o r t h e f i r st t i m e .
2 . p u b l i c v oi d st a r t ( ) : C a l l e d af t e r i ni t , t hi s m e t h o d wi l l a l so b e c a l l e d ev e r y t i m e
wh e n e v e r t h e d o c um e n t c o n t ai n i n g t h e a p p l e t i s r e di sp l a y e d o n t h e W EB b r o wse r .
3 . p u b l i c v oi d st o p ( ) : W h e n ev e r t h e u se g o e s t o t h e n e x t d o c um e n t .
4 . p u b l i c v oi d d e st r o y ( ) : W h e n ev e r t h e A pp l e t i s b e i n g r em ov e d f r om t h e W E B b r o w se r
F o r ex , t h e u se r c l o se s t h e W E B b r o wse r .
127 SATEESH N
SATEESH N
T h e A p p l e t c l a ss m u st b e p u b l i c, b e c a u se t h e a p p l e t i s b e i n g e x e c u t e d i n a n o t h e r
p r o g r a m i . e. , t h e A p pl e t i s b e i n g ex e c ut e d i n a W EB b r o wse r .
5 . p u b l i c v oi d p a i n t ( G r a p h i c s g ) : T h i s m e t h o d wi l l b e c a l l e d wh e n e v e r t h e o u t p ut
m u st b e r e d r a wn . T h i s m e t h o d al so r e c e i v e s a p a r a m e t e r of t h e g r a p h i c s cl a ss wh i c h
c o n t a i n s t h e g r a p h i c s c o n t ex t d e t ai l s. T h e gr a p h i c s c l a ss av a i l a b l e i n t h e j av a . a wt . * .
Ap p l e t c l a s s m e t h o d s :
A p p l e t i s t h e su p e r c l a ss f o r a l l t h e a p p l e t s.
T h e a b ov e 5 m e t h o d s c a n b e o v e r ri d d e n a n d wi l l b e c a l l e d b y t h e W E B b r o wse r
d e p e n d i n g o n t h e u s e r n av i g a t i o n o n t h e HT M L d o c um e n t s. T h e f ol l o wi n g m et h o d s a r e
a l so av a i l a b l e i n t h e A p p l e t cl a ss wh i c h c a n b e c a l l e d i n t h e p r o g r am d e p e n d i n g o n t he
r e q u i r em e n t .
v oi d sh o wS t a t u s( S t r i n g m sg ) : D i sp l a ys t h e m e ssa g e i n t h e st a t u s b a r o f t h e W EB
b r o w se r .
U R L g e t D o c u m e n t B a se ( ) : R e t u r n s t h e UR L o f t h e HT M L d o c um e n t .
U R L g e t C o d e B a se ( ) : R e t u r n s t h e U R L of t h e A p p l e t .
v oi d r e p a i nt ( ) : R e d r a ws t h e A p p l e t .
v oi d se t B a c k g r o u n d ( c o l o r n e wc o l o r ) :
v oi d se t F o r e g r o u n d ( c o l o r n e wc o l o r ) :
c o l o r ( i n t r e dv al u e , i nt g r e e nv a l u e , i n t bl u ev al u e ) :
1 . v oi d d r a wst r i n g ( S t ri n g st r , i nt x , i n t y ) : Dr a w s t h e st r i n g a t (x , y ) l o c at i o n s.
2 . v oi d d r a wL i n e ( i n t x 1, i n t y 1, i nt x 2 , i nt y 2 ) : D r a ws a l i n e f r om (x 1 , y 1 ) t o
( x 2, y 2 )
3 . v oi d d r a wR e c t ( i nt x , i nt y, i n t wi d t h , i n t h e i g h t ) : D r a ws a r e c t a n g l e a t x , y
l o c a t i o n s wi t h t h e g iv e n wi d t h a n d h e i g h t .
4 . v oi d d r a wO v al ( i n t x , i n t y, i n t wi d t h , i nt h e i g h t ) : D r a ws a o v al a t (x , y) l o c a t i o n s
wi t h t h e g iv e n wi d t h a n d h e i g h t .
5 . v oi d d r a wR o u n d R e c t ( i n t x , i nt y , i n t wi d t h , i n t h e i g h t , i nt n 1 , i n t n 2 ) : D r a w s a
r o u n d e d r e c t a n g l e . H e r e n 1 , n 2 sp e c i f i e s t h e c u rv e d e t ai l s.
128 SATEESH N
SATEESH N
Ex:
n1
n2
6 . v oi d f i l l R e c t ( i nt x , i n t y , i n t wi d t h , i nt h e i g ht ) : F i l l s t h e sp e c i f i e d l o c at i o n .
7 . v oi d f i l l O v al ( i nt x , i n t y , i n t wi d t h , i nt h e i g ht ) : F i l l s t h e sp e c i f i e s l o c a t i o n .
8 . v oi d f i l l R o u n d R e c t ( i n t x , i n t y , i nt wi d t h , i n t h e i g h t , i n t n 1 , i nt n 2 ) : F i l l s t h e
sp e c i f i e d l o c a t i o n .
9 . v oi d S e t C ol o r ( C ol o r n e w c o l o r ) : S e t s t h e d r a wi n g c o l o r .
1 0 . v oi d d r a wP o l y g o n ( P o l y g o n p o l y ) : D r a w s a p o l y g o n . P o l y g o n i s a c l a ss wh i c h
c o n t a i n s (x 1 , y 1 ) , (x 2 , y 2 ) , . . . , (x n , y n ).
1 1 . v oi d f i l l P ol y g o n ( P ol y g o n p o l y ) : F i l l s t h e p o l y g o n .
C o m p o n e n t C l a ss : C o m p o n e n t i s t h e s u p e r c l a ss f o r a l l t h e c l a sse s, wh i c h i s
c o n t a i n i n g t h e f ol l o wi n g m e t h o d s.
D i m e n si o n g e t Si z e ( ) : R e t u r n s t h e si z e of t h e c om p o n e n t .
Ex: P u b l i c Cl a ss D i m e n si o n
{
p u b l i c i nt wi d t h ;
p u b l i c i nt h ei g h t ;
}
/ / F i l e n am e : ap p sh a p e s . j a v a
Out Put :
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ; E:\Core> javac appshapes.java
/ / se t t i n g a p o l y g o n
i nt x [ ] = { 0 , w/ 2 , w, 0 , w} ;
i nt y[ ] = { h , 0 , h, h / 2 , h / 2 };
P o l y g o n p o l y = n e w P o l y g o n ( x , y , 5 );
/ / 5 c o - o r di n a t t e s
129 SATEESH N
SATEESH N
g . se t C o l o r ( C o l o r. l i g h t G r a y );
g.fill Polygon(pol y);
g . se t C o l o r ( C o l o r. c y a n ) ;
g . d r a wL i n e ( 0 , 0 , w, h ) ;
g . se t C o l o r ( C o l o r. y el l o w) ;
g . d r a wR e c t ( 4 , 4 , w- 8 , h - 8 ) ;
g . d r a wO v al ( 8 , 8, w- 1 6 , h - 1 6 ) ;
g . se t C o l o r ( C o l o r. g r e e n ) ;
g.fill RoundRect(25,125,150,75,15,15);
g . se t F o n t ( n e w F o n t ( "T i m e s n e w R o m a n " , F o n t . BO L D , 1 4 ) ) ;
g . se t C o l o r ( C o l o r. b l a ck ) ;
g . d r a wS t r i n g ( " S am pl e S h a p e s" , 3 0 , 1 5 0 ) ;
}
}
Sending Parameters : W e c a n se n d p a r a m et e r s t o a n A p p l et u si n g t h e p a r am t a g i n
t h e H T M L d o c um e n t . E a c h p a r am e t e r c o n t a i n s a n a m e a n d a v a l u e. A j av a a p p l e t c an
r e t r i ev e t h e v al u e s o f t h e p a r am e t e r s u si n g t h e f ol l o wi n g f u n ct i o n .
S t ri n g g e t P a r am e t e r ( S t ri n g p a r am N am e ) : R e t u r n s t h e v al u e wh i c h i s a ssi g n e d t o
p a r a m N am e i n h t m l c o d e .
/ / HT ML Co d e
< ! – a p p se n d p a r a . h t m l - - >
<html>
<body>
< a p p l e t c o d e = " a p p se n d p a r a . c l a s s" wi d t h = 3 0 0 h e i g h t = 4 0 0 >
< p a r am n am e = " em p n o " v al u e = " 1 0 1 " >
< p a r am n am e = " e n am e " v al u e = " S a t ee sh r a j " >
Out Put :
< p a r am n am e = "j o b " v al u e = "M G R ">
</appl et>
E:\Core> javac appshapes.java
</body>
</html>
E:\Core> appletviewer appshapes.html
/ / F i l e n am e : a p p s e n d p a r a . j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ;
p u b l i c c l a ss a p p se n d p a r a e x t e n d s A p p l e t
{
S t r i n g p 1, p 2 , p 3 ;
p u b l i c v oi d i ni t ( )
{
se t B a c k g r o u n d ( C o l o r . cy a n ) ;
/ / R et r i ev e t h e v al u e s of t h e p a r am et e r s
p 1 = g e t P a r am e t e r ( " em p n o " );
p 2 = g e t P a r am e t e r ( " e n am e " );
p 3 = g e t P a r am e t e r ( "j o b " ) ;
}
130 SATEESH N
SATEESH N
p u b l i c v oi d p ai n t (G r a p h i c s g )
{
g . se t C o l o r ( C ol o r . r e d );
g . se t F o n t ( n e w F o n t ( " C om i c S a n s" , F o n t . B O L D , 1 4 ) ) ;
/ / di sp l a y s t h e p a r am e t e r v al u e s
g . d r a wS t ri n g ( p 1 , 5 0 , 5 0 ) ;
g . d r a wS t ri n g ( p 2 , 5 0 , 1 0 0 ) ;
g . d r a wS t ri n g ( p 3 , 5 0 , 1 5 0 ) ;
}
}
D r a win g I ma g e s o n t h e Ap p le t : T o p r e se n t a n i m a g e o n t h e a p p l e t , t h e i m a ge
sh o u l d b e l o a d e d i n t o m em o r y u si n g o n e of t h e f ol l o wi n g f u n ct i o n s.
I m a g e g e t I m a g e ( U R L c o d e b a se , S t ri n g i m a g e ) :
I m a g e g e t I m a g e ( U R L u r l _ of _i m a g e ) :
T o d r a w t h e i m a g e t h e g r a p h i c s cl a ss p r o v i d i n g t h e f ol l o wi n g f u n c t i o n s.
v oi d d r a wI m a g e ( I m a g e i m g , i n t x , i n t y , i n t wi d t h , i nt h e i g ht , I m a g e O b se rv e r o b ) :
/ / HT ML Co d e
/ / F i l e n am e : a p p i mg . j a v a
Out Put :
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ; E:\Core> javac appimg.java
p u bl i c v oi d i n i t ( )
{
// loading the im age
i m g= g e t I m a g e ( g e t C o d e B a se ( ) , " k & h . j p g " );
}
p u bl i c v oi d p a i nt ( G r a p hi c s g )
{
g . d r a wI m a g e (i m g , 0 , 0, t hi s) ;
/ / g. d r a wI m a g e ( i m g , 0 , 0, 2 0 0 , 2 0 0 , t h i s) ;
}
}
131 SATEESH N
SATEESH N
Ab s t ra c t Wi nd o wT o o l Kit
P la c in g c o mp o n e n t s o n t h e Ap p le t : “ j av a. a wt “ p a c k a g e i s p r o v i di n g t h e
f ol l o wi n g c o m p o n e n t c l a sse s, wh i c h a l l ow s u s t o p l a c e c o m p o n e n t s l i k e b u t t o n s,
c h e c k b o x e s, d o o n t h e a p p l e t .
( a ) c o m p o n e n t cl a ss : C o m p o n e n t i s a su p e r c l a s s f o r a l l t h e c om p o n e n t s. I t i s
p r ov i d i n g a se t of m et h o d s wh i c h a r e av ai l ab l e i n a l l t h e su b c l a sse s.
C o m p on en t :
i. Button
ii. T ex t c om p o n e n t
T ex t f i el d
T ex t a r e a
iii. Label
iv. Check box
v. Scrollbar
vi. Choice
vii. L i st
v i i i . C a nv a s
ix. Container
Panel wi n d o w
F r am e Di a l o g
C o m p o n e n t i s a n a b st r a c t c l a ss, b u t i t i s n o t c o n t a i ni n g a n y a b st r a c t m et h o d s i . e . ,
we c a n n o t c r e a t e a n y i n st a n c e s o f t h e c o m p o n e n t c l a ss, b u t t h e m e t h o d s o f t he
c o m p o n e n t cl a ss c a n b e u se d i n t h e su b c l as se s.
C o m p on en t c la s s Me t ho d s :
v oi d se t E n a b l e d ( B o ol e a n e n a b l e s ) : E n a bl e s o r d i sa b l e s t h e c om p o n e n t .
v o i d se t V i si bl e ( B o ol e a n v i si bl e ) : S h ow s t h e c o m p o n e n t t o t h e sp e c i f i e d
l o c at i o n.
v oi d se t L o c a t i o n ( i n t x , i n t y ) : M ov e s t h e c o m p o n e n t t o t h e sp e c i f i e d
l o c a t i o n.
p o i n t g e t L o c a t i o n ( ) : R e t u r n s t h e l o c a t i o n o f t h e c om p o n e n t .
Ex: p u b l i c cl a ss p o i n t
{
public int x;
p u b l i c i n t y;
}
v oi d se t S i z e ( i n t wi d t h, i n t h ei g h t ) : S et s wi d t h a n d h e i g h t of t h e c om p o n e n t .
132 SATEESH N
SATEESH N
v oi d g e t Si z e ( ) :
Ex: p u b l i c cl a ss D i m e n si o n
{
p u b l i c i n t wi d t h ;
publi c i nt hei ght;
}
v oi d se t B o u n d s( i n t x , i n t y , i nt wi d t h , i nt h ei g h t ) :
R e c t a n g l e g e t B o u n d s( ) :
Ex: p u b l i c cl a ss R e c t a n g l e
{
p u b l i c i nt x ;
p u b l i c i nt y;
p u b l i c i nt wi d t h ;
p u b l i c i nt h ei g h t ;
}
Button : F o r c r e a t i n g a p u sh b u t t o n .
S y n t ax : B u t t o n ( ) : c r e a t e s b l a n k b u t t on , i . e n o l a b e l
B u t t o n ( St r i n g L a b e l ) : c r e a t e s B u t t o n wi t h sp e c i f i e d l a b el . SUBMIT
Ex: B ut t t o n ( “S U B M I T ” );
v oi d se t L a b e l ( St ri n g n e wl a b e l ) : C h a n g e s t h e l a b e l of t h e b u t t o n .
v oi d g e t L a b e l ( ) : R e t u r n s t h e l a b e l of t h e b u t t o n .
/ / F i l e n am e : b u t to n t e s t . j a v a
i m p o r t j av a. a p p l e t . * ; Out Put :
i m p o r t j av a. a wt . * ;
E:\Core> javac buttontest.java
p u b l i c c l a ss b u t t o n t e st ex t e n d s A p p l e t
{ E:\Core> appletviewer buttontest.html
Button b1,b2;
p u b l i c v oi d i ni t ( )
{
b 1 = n e w B u t t o n ( "F i r st B u t t o n " ) ;
b 2 = n e w B u t t o n ( " S e c o n d B u t t o n " );
/ / sh o w s t h e c o m p o n e n t s o n t h e a p p l e t
add(b1);
add(b2);
}
}
133 SATEESH N
SATEESH N
Ha n d l in g C o mp o n e n t s : T o h a n d l e a n y c o m p o n e n t a l i st e n e r i s r e q u i r e d . A l i st e n e r
wa i t s f o r a n e v e n t t o o c c u r . O n c e t h e c o rr e sp o n d i n g ev e n t o c c u r s t h e l i st e n e r s c a l l s
t h e sp e c i f i e s m e t h o d .
j av a . a wt . ev e nt p a c k a g e i s p r o v i d i n g t h e l i st e n e r i n t e rf a c e s f o r h a n d l i n g v a ri o u s
t y p e s o f c om p o n e n t s.
I n t e rf a c e s :
A c t i o n L i st e n e r : F o r h a n d l i n g b u t t o n s, l i st b o x e s, m e n u i t em s e t c. ,
I t em Li st e n e r : F o r h a n d l i n g c h e c k b ox e s e t c . ,
A d j u st m e n t L i st e n e r : F o r h a n d l i n g sc r o l l b a rs.
W i n d o wL i st e n e r : F o r h a n d l i n g f oc u s ev e n t s.
K e y L i st e n e r : F o r h a n d l i n g k e y ev e nt s.
M o u se L i st e n e r : F o r h a n d l i n g m o u se ev e n t s.
A c t i o n L i st e n e r : Ac t i o n L i st e n e r i s c o n t ai n i n g t h e f ol l o wi n g m e t h o d .
A l i s t e n e r i s a p r o g r a m t h a t wi l l b e a t t a c h e d t o a c o m p o n e n t . T h e l i st e n e r
c o n t i n u o u sl y m o ni t o r s t h e c o m p o n e n t s f o r sp e c i f i c ev e n t s su c h a s k e y p r e s s,
m o u se c l i c k e t c. , wh e n e v e r t h e ev e n t oc c u r s t h e l i st e n e r c a l l t h e c o r r e sp o n d i n g
f u n ct i o n.
p u b l i c v oi d a c t i o n P e rf o rm e d ( A c t i o n Ev e n t e ) : T o h a n d l e a b u t t o n c r e a t e a c l a s s t h a t
i m pl em e n t s t h e A c t i o n L i st e n e r i n t e rf ac e a n d ov e r ri d e t h e a c t i o n P e rf o rm e d m e t h o d . A d d
t h e l i st e n e r t o t h e r e q u i r e d b u t t o n . W h e n ev e r t h e u se r c l i c k s o n t h e b u t t o n t h e l i st e n e r
r e c e i v e s t h e ev e n t a n d ex e c ut e s t h e a c t i o n P e rf o rm e d m et h o d .
/ / F i l e n am e : b u t to n t e s t 2 . j a v a
i m p o r t j av a. a p p l e t . * ;
i m p o r t j av a. a wt . * ; Out Put :
i m p o r t j av a. a wt . ev e n t . * ;
E:\Core> javac buttontest2.java
p u b l i c c l a ss b u t t o n t e st 2 e x t e n d s A p p l e t
{ E:\Core> appletviewer buttontest2.html
Button b1,b2;
p u b l i c v oi d i ni t ( )
{
b 1 = n e w B u t t o n ( "F i r st B u t t o n " ) ;
b 2 = n e w B u t t o n ( " S e c o n d B u t t o n " );
/ / sh o w s t h e c o m p o n e n t s o n t h e a p p l e t
add(b1);
add(b2);
b 1 . a d d A ct i o n Li st e n e r ( n e w F i r st H a n d l e r () ) ;
b 2 . a d d A ct i o n Li st e n e r ( n e w S e c o n d H a n d l e r ( ) ) ;
}
// Handl ers
First Button Clicked
134 SATEESH N
SATEESH N
cl a ss F i r st H a n d l e r i m pl em e n t s A c t i o n L i st en e r
{
p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e n t e )
{
sh o wS t a t u s( " F i r st B u t t o n Cl i c k e d " ) ;
}
}
cl a ss S e c o n d H a n d l e r i m pl em e n t s A ct i o n L i st e n e r
{
p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e n t e )
{
sh o wS t a t u s( " C l i c k e d o n S e c o n d B u t t o n " ) ;
}
}
}
/ / F i l e n am e : b u t to n t e s t 3 . j a v a
i m p o r t j av a. a p p l e t . * ;
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ;
p u b l i c c l a ss b u t t o n t e st 3 e x t e n d s A p p l e t
{
Button b1,b2;
p u b l i c v oi d i ni t ( )
{
b1 = new B u t t o n ( "F i r st B u t t o n " ) ;
b2 = new B u t t o n ( " S e c o n d B u t t o n " ); cont…
/ / sh o w s the com ponents on the applet Out Put :
/ / C om m o n H a n d l e r
cl a ss C o m m o n H a n d l e r i m pl em e n t s A c t i o n L i st e n e r
{
p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e n t e )
{
if ( e.getSource() == b1 )
sh o wS t a t u s( " F i r st B u t t o n C l i c k ed " ) ;
e l se i f ( e . g e t S o u r c e ( ) = = b 2 )
sh o wS t a t u s( " C l i c k e d o n S e c o n d B u t t o n " ) ;
}
}
} C lic k ed on S ec on d B ut t on
135 SATEESH N
SATEESH N
/ / F i l e n am e : b u t to n t e s t 4 . j a v a
i m p o r t j av a. a p p l e t . * ;
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ;
p u b l i c c l a ss b u t t o n t e st 4 e x t e n d s A p p l e t i m pl em e n t s A c t i o n L i st e n e r
{
Button b1,b2;
Out Put :
p u b l i c v oi d i ni t ( )
{ E:\Core> javac buttontest4.java
b 1 = n e w B u t t o n ( "F i r st B u t t o n " ) ;
b 2 = n e w B u t t o n ( " S e c o n d B u t t o n " ); E:\Core> appletviewer buttontest4.html
/ / sh o w s t h e c o m p o n e n t s o n t h e a p p l e t
add(b1);
add(b2);
b 1 . a d d A ct i o n Li st e n e r ( t h i s) ;
b 2 . a d d A ct i o n Li st e n e r ( t h i s) ;
}
p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e nt e)
{
if ( e.getSource() == b1 )
sh o wS t a t u s( " F i r st B u t t o n C l i ck e d " ) ;
e l se i f ( e . g e t S o u r c e ( ) = = b 2 )
sh o wS t a t u s( " C l i c k e d o n S e c o n d B u t t o n " ) ;
}
First Button Clicked
T e x tF i el d ( ) : A t e x t f i el d i s u se d f o r t e x t f r om t h e u se r . T h e r e a r e 4 i m p o r t a n t
c o n st r u c t o r s a r e t h e r e f o r T ex t F i el d .
T ex t F i el d ( ) T ex t F i el d ( i n t l e n g t h )
T ex t F i el d ( S t ri n g st r ) T ex t F i el d ( St r i n g st r, i n t l e n g t h )
S t ri n g g e t T ex t ( ) : R et u r n s t h e t ex t i n t h e t e x t b ox .
v oi d se t T ex t ( St r i n g t ex t ) : Pl a c e s t h e g i v en t ex t i nt o t h e t ex t b o x .
v oi d se t E d i t a b l e ( B o o l e a n e d i t a b l e ) : M a ke s t h e t e x t r e a d o nl y o r r e a d a n d wr i t e .
T e x t Ar e a ( ) : F o r a c c e p t i n g m ul t i p l e l i n e s o f t ex t .
C o n st r u c t o r s :
T ex t A r e a ( ) , T ex t Ar e a ( i n t r o ws, i n t c o l s ) , T ex t A r e a ( St ri n g st r , i n t r o ws, i n t c ol s )
Methods :
S t ri n g g e t T ex t ( ) v oi d se t T ex t ( St r i n g t ex t )
v oi d se t E d i t a b l e ( b o ol e a n e d i t a bl e ) v oi d a p p e n d ( S t ri n g t ex t )
136 SATEESH N
SATEESH N
/ / F i l e n am e : t e x t t e s t . j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ;
i m p o r t j av a. a wt . ev e n t . * ;
p u b l i c c l a ss t ex t t e st ex t e n d s A p p l e t i m pl em e n t s A c t i o n L i st e n e r
{
T ex t F i el d t 1, t 2 ;
Button b1,b2; Out Put :
b 1 = n e w B u t t o n ( " C o p y D o wn " ) ;
b 2 = n e w B u t t o n ( " C o p y U p " );
a d d ( t 1 );
a d d ( t 2 );
add(b1);
add(b2);
b 1 . a d d A ct i o n Li st e n e r ( t h i s) ;
b 2 . a d d A ct i o n Li st e n e r ( t h i s) ;
}
p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e nt e)
{
if ( e.getSource() == b1 )
{
t 2 . se t T ex t ( t 1 . g e t T ex t ( ) ) ;
t 1 . se t T ex t ( " " );
}
el se i f ( e. g e t S o u r c e ( ) = = b 2 )
{
t 1. se t T ex t (t 2 . g e t T ex t ( ) );
t 2. se t T ex t ( "" ) ;
}
}
Checkbox : T h e c h e c k b o x i s u se d f o r a c ce p t i n g B o ol e a n t y p e s of v al u e s.
C o n st r u c t o r s :
Checkbox( ) C h e c k b o x ( S t ri n g L a b e l )
Methods :
S t ri n g g e t L a b e l ( ) v oi d se t L a b e l ( St ri n g n e wl a b e l )
v oi d se t L a b e l ( S t ri n g n e wl a b e l ) : C h a n g e s t h e L a b e l .
b o o l e a n g e t S t a t e ( ) : R et u r n s t r u e i f t h e c he c k b o x i s c h e c k e d o n o t h e r wi se
f a l se .
137 SATEESH N
SATEESH N
v oi d se t S t a t e ( B o o l e a n st a t e ) : C h a n g e s t h e st a t e o f t h e c h e c k b ox .
A c h e c k b o x sh o u l d b e h a n d l e d u si n g I t e m Li st e n e r i n t e rf a c e, wh i c h i s c o n t a i n i n g t h e
f ol l o wi n g m e t h o d s.
P u b l i c v oi d i t em St a t e C h a n g e d ( I t em Ev e n t e ) :
/ / F i l e n am e : c h kb o x t e s t. j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ;
i m p o r t j av a. a wt . ev e n t . * ;
p u b l i c c l a ss c h k b o x t e st e x t e n d s A p p l e t i m pl e m e n t s A ct i o n Li st e n e r , I t em Li st e n e r
{
C h e c k b ox c b 1 , c b 2;
Button b1;
p u b l i c v oi d i ni t ( ) Out Put :
{
se t F o n t ( n e w F o n t ( " c om i c S a n s" , F o n t . BO LD , 1 8 ) ) ;
E:\Core> javac chkboxtest.java
c b 1 = n e w C h e c k b o x ( "F i r st C h e c k B ox ") ;
E:\Core> appletviewer chkboxtest.html
c b 2 = n e w C h e c k b o x ( " S e c o n d C h e c k B ox " ) ;
b 1 = n e w B u t t o n ( " S h o w B o t h D e t ai l s" ) ;
add(cb1);
add(cb2);
add(b1);
c b 1 . a d d I t em Li st e n e r ( t h i s) ;
c b 2 . a d d I t em Li st e n e r ( t h i s) ;
b 1 . a d d A c t i o n L i st e n e r ( t h i s) ;
}
p u b l i c v oi d i t em S t at e C h a n g e d ( I t e m Ev e n t e)
{
S t ri n g m sg = "" ;
F ir s t c h ec k b ox O N S ec on d c h ec k b ox O F F
i f ( e. g e t S o u r c e ( ) = = c b 1 )
{
m sg = "F i r st C h e c k B ox : ";
138 SATEESH N
SATEESH N
p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e nt e)
{
if ( e.getSource() == b1 )
{
S t r i n g m sg = " ";
m sg = " F i r st C h e c k B ox ";
m sg = m sg + " S e c o n d C h e c k B ox " ;
sh o wS t a t u s( m sg ) ;
}
}
c h e c k b o x g r o u p s : I f c h e c k b ox e s a r e a d d e d t o c h e c k b o x g r o u p s, J av a c o nv e r t s
them to “ Radi o Button “.
C h e c k b o x g e t S e l e ct e d c h e c k b ox ( ) : R e t u rn s t h e r e f e r e n c e o f t h e se l e c t e d c h e c k b o x
f r om t h e sp e c i f i e d g r o u p .
/ / F i l e n am e : r a d i o t e s t . j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ;
i m p o r t j av a. a wt . ev e n t . * ;
p u b l i c c l a ss r a d i o t e st ex t e n d s A p p l e t i m pl em e n t s I t em Li st e n e r
{
C h e c k b ox G r o u p l a n g = n e w C h e c k b o x G r o u p ( ) ;
C h e c k b ox G r o u p p a c k = n e w C h e c k b o x G r ou p ( ) ;
C h e c k b ox o p t 1 = n e w C h e c k b o x (" C L a n g u a g " , l a n g , t r u e ) ;
C h e c k b ox o p t 2 = n e w C h e c k b o x (" C + + L a ng u a g " , l a n g , t r u e ) ;
C h e c k b ox o p t 3 = n e w C h e c k b o x (" J av a " , l an g , t r u e ) ;
C h e c k b ox o p t 4 = n e w C h e c k b o x (" Vi su a l Ba si c " , p a c k , t r u e ) ;
C h e c k b ox o p t 5 = n e w C h e c k b o x (" P o we r B u i l d e r ", p a c k , t r u e ) ;
p u b l i c v oi d i ni t ( )
Out Put :
{
se t F o n t ( n e w F o n t ( " A ri al Bl a c k " , F o n t . B O LD , 1 4 ) ) ; E:\Core> javac radiotest.java
o p t 1 . a d d I t em Li st e n e r ( t h i s) ;
o p t 2 . a d d I t em Li st e n e r ( t h i s) ;
o p t 3 . a d d I t em Li st e n e r ( t h i s) ;
o p t 4 . a d d I t em Li st e n e r ( t h i s) ;
o p t 5 . a d d I t em Li st e n e r ( t h i s) ;
}
139 C++ Language Powe r B u i l d eN
SATEESH r
SATEESH N
p u b l i c v oi d i t em S t at e C h a n g e d ( I t e m Ev e n t e)
{
C h e c k b ox c 1 = l a n g . g e t S e l e ct e d C h e c k b o x ( );
C h e c k b ox c 2 = p a c k . g e t S e l e ct e d C h e c k b o x ( );
St ri n g m sg = c 1 . g e t L a b e l ( ) + " " + c 2. g e t L a b e l ( ) ;
sh o wS t a t u s( m sg ) ;
}
S c r o l l b a r : A sc r ol l b a r i s u se d f o r se l e c t i n g a v a l u e wi t hi n a g i v e n r a n g e .
sc r o l l b a r ( ) : C r e a t e s v e r t i c al sc r o l l b a r .
sc r o l l b a r ( i n t st y l e ) : T h e st yl e m a y b e sc r o l l b a r. V E RT I C A L o r sc r o l l b a r . H O RI Z O N T A L
sc r o l l b a r ( i nt st yl e , i n t i n i t i al v al u e , i nt t h um b si z e , i nt m i n , i n t m ax ) :
c o n s t ru c to r s :
v oi d se t V a l u e s( i n t i ni t i al v a l u e, i n t t h um b si z e , i nt m i n , i nt m ax ) : C h a n g e s t h e r a n g e
f o r t h e sc r o l l b a r .
i n t g et V a l u e ( ) : R et u r n s t h e se l e c t e d v a l ue .
v oi d se t V a l u e ( i n t v al ) : M ov e s t h e t h um b t o t h e sp e c i f i e d v al u e .
A sc r o l l b a r sh o u l d b e h a n d l e d u si n g the A d j u st m e n t L i st e n e r i n t e rf ac e . T hi s
c o n t a i n i n g t h e f ol l o wi n g m e t h o d .
p u b l i c v o i d a d j u st m e n t V al u e C h a n g e d ( A d j u st m e n t Ev e n t e ) :
/ / F i l e n am e : scrolbarrgb.java
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ;
i m p o r t j av a. a wt . ev e n t . * ;
p u b l i c c l a ss sc r o l b a r r g b e x t e n d s A p p l e t i m pl em e n t s A d j u st m e n t Li st e n e r
{
S c r ol l b a r r e d = n e w S c r o l l b a r ( S c r ol l b a r . HO R I Z O NT A L , 0 , 1 0 0 , 0 , 3 5 5 );
S c r ol l b a r g r e e n = n e w S c r o l l b a r ( S c r ol l b a r. H O R I Z O N T A L , 0 , 1 0 0 , 0 , 3 5 5 ) ;
S c r ol l b a r b l u e = n e w S c r o l l b a r ( S c r ol l b a r . HO R I Z O NT A L , 0 , 1 0 0 , 0 , 3 5 5 );
p u b l i c v oi d i ni t ( )
{
se t L a y o u t ( n e w G r i d L a y o u t ( 4 , 1 ) ) ;
add(l1);
add(red);
add(green);
add(blue);
140 SATEESH N
SATEESH N
r e d . a d d A d j u st m e n t Li st e n e r ( t h i s) ; Out Put :
g r e e n . a d d A d j u st m e n t L i st e n e r ( t hi s) ;
b l u e . a d d A dj u st m e n t Li st e n e r ( t h i s) ; E:\Core> javac scrollbarrgb.java
}
E:\Core> appletviewer scrollbarrgb.html
p u b l i c v oi d a dj u st m e n t V a l u e C h a n g e d
( A d j u st m e n t Ev e nt e )
{
i nt r = r e d . g e t V al u e ( ) ;
i nt g = g r e e n . g e t V a l u e ( );
i nt b = bl u e . g e t V al u e ( ) ;
C o l o r n c = n e w C o l o r ( r , g, b ) ;
l 1. se t B a c k g r o u n d ( n c ) ;
Choice : F o r c r e a t i n g a c om b o b ox o r d r op d o wn l i st b ox .
C o n st r u c t o r s :
C h o i c e ( ) : C r e a t e s a c h o i c e c om p o n e n t .
Methods :
v oi d a d d ( St ri n g i t em ) : A d d a n i t em t o t h e c h o i c e b ox .
S t ri n g g e t S e l e ct e d I t em ( ) : R e t u r n s t h e t ex t of t h e se l e c t e d i t em .
i n t g e t S el e c t e d I n d ex ( ) : R e t u r n s t h e I n d e x of t h e se l e c t e d i t em st a r t i n g f r om z e r o . I t
r e t u r n s m i n u s o n e ( - 1 ) o n n o se l e c t i o n .
S t ri n g g e t I t em ( i n t i n d ex ) : R e t u r n s t h e t ex t of t h e sp e c i f i e d i t em .
i n t g et I t em C o u n t ( ) : R e t u r n s t h e n um b e r of i t em s i n t h e c h oi c e c om p o n e n t .
v oi d se l e c t ( i nt i n d ex ) : S el e c t s t h e sp e c i f i e d i t em .
v oi d r em ov e ( i nt i n d e x ) : R em ov e s t h e sp e c i f i e d i t em .
v oi d r em ov e ( S t ri n g i t em ) : R em ov e s t h e sp e c i f i e d i t em .
v oi d r e m ov eA l l ( ) : R e m ov e s a l l i t em s. A c h o i c e c o m p o n e n t c a n b e h a n d l e d u si n g
I t em Li st e n e r i n t e rf ac e .
L i s t : F o r cr e a t i n g a l i st b ox .
L i st ( ) : d ef a u l t si z e .
L i st ( i nt r o ws, b o o l e a n m u l t i se l e c t ) :
A l l t h e f u n c t i o n s of t h e c h o i c e b o x su p p o r t e d i n t h e l i st b ox .
141 SATEESH N
SATEESH N
S t ri n g [ ] g e t S e l e ct e d I t em s( ) : R e t u r n s a l l t h e se l e c t e d i t em s.
i n t [ ] g e t S el e c t e dI n d e x s( ) : R e t u r n s a l l t h e se l e c t e d i t em s.
A l i st b ox sh o u l d b e h a n d l e u si n g A c t i o n L i st e n e r i n t e rf a c e.
L a yo u t Ma n a g e me n t :
A l a y o u t sp e c i f i e s h o w t h e c o m p o n e n t s a r e a l i g n e d , si z e d a n d p o si t i o n e d
i n t h e r u n t i m e of a n a p p l et .
J av a . a wt p a c k a g e su p p o r t s t h e f o l l o wi n g f i v e l a y o u t cl a sse s f o r v a ri o u s a l i g nm e n t
o f t h e c om p o n e n t s.
F l o w L a y o u t : I n t h e F l o wL a y o u t w h e n e v e r a c om p o n e n t i s a d d i t wi l l b e a d d e d i n t h e
c u r r e n t r o w. I f t h e r e i s n o sp a c e i n t h e c u r re n t r o w, t h e c o m p o n e n t wi l l b e pl a c e d i n t he
n e x t r o w.
T h i s i s t h e d ef a u l t l a y o u t f or a p p l et a n d p a n e l s.
F l o wL a y o u t ( ) :
F l o wL a y o u t ( i nt al i g n ) :
F l o wL a y o u t ( i nt al i g n , i n t v sp a c e , i n t h sp a c e ) :
align : F l o wL a y o u t . C E N T E R ( d ef a u l t )
F l o wL a y o u t . L E F T
F l o wL a y o u t . R I G HT
v sp a c e a n d h sp a c e a r e t h e sp a c e d b e t we e n c om p o n e n t s v e r t i c al l y a n d h o ri z o n t al l y .
142 SATEESH N
SATEESH N
B o r d e r L a y o u t : I n t h e B o r d e r L a y o u t wh e n ev e r we a d d a c o m p o n e n t we sh o u l d a l s o
sp e c i f y t h e di r e c t i o n of t h a t c om p o n e n t .
T h e f ol l o wi n g di r e c t i o n s a r e su p p o r t e d :
B o r d e r L a y o u t . E A ST
B o r d e r L a y o u t . W E ST
BorderLayout.NORTH
B o r d e r L a y o u t . S O UT H
BorderLayout.CENTER ( d ef a ul t )
Z e r o a r g um e n t c o n st r u c t o r , BorderLayout( ) :
T h i s i s t h e d ef a u l t l a y o u t f or f r am e s a n d d i a l o g s
/ / F i l e n am e : b o r d e r l a y . j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ; Out Put :
C h o i c e c o u r se = n e w C h o i c e ( ) ;
L i st l 1 = n e w L i st ( ) ;
B u t t o n b 1 = n e w B u t t o n ( " S am pl e B ut t o n " ) ;
p u b l i c v oi d i ni t ( )
{
se t F o n t ( n e w F o n t ( " A ri al N a r r o w" , F o n t . BO L D , 1 4 ) ) ;
se t L a y o u t ( n e w B o r d e r L a y o u t ( ) ) ;
a d d ( s1 , B o r d e r L a y o u t . E A S T );
a d d ( s2 , B o r d e r L a y o u t . W E ST ) ;
a d d ( l 1 , B o r d e r L a y o u t . C E N T E R) ;
c o u r se . a d d ( " C L a n g u a g e " ) ;
c o u r se . a d d ( " C + + " ) ;
c o u r se . a d d ( " J av a " );
c o u r se . se l e c t ( 1 ) ; / / 2 n d i t em
l 1. a d d ( " Vi su a l B a si c " ) ;
l 1. a d d ( " P o we r B u i l d e r ") ;
l 1. a d d ( " D e l p h i " ) ;
}
143 SATEESH N
SATEESH N
GridLayout : I n t h e G r i d L a y o u t t h e t o t a l a r e a i s d i v i d e d i n t o r o ws a n d c o l u m n s.
W h e n ev e r we a d d a c o m p o n e n t e a c h c om p on e n t wi l l b e a d d e d i n e a c h c e l l .
G r i dl a y o u t (i n t r o ws, i n t c o l s) :
Out Put :
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ;
p u b l i c c l a ss g r i d l a y ex t e n d s A p p l e t
{
p u b l i c v oi d i ni t ( )
{
se t B a c k g r o u n d ( C o l o r . p i n k) ;
se t L a y o u t ( n e w G r i d L a y o u t ( 6 , 3 , 1 0 , 1 0 ) ) ;
/ / a d d 1 8 c om p o n e n t s
f o r (i n t i = 1 ; i < = 1 8; i + + )
{
a d d ( n e w B u t t o n ( " B u t t o n "+ i ) ) ;
}
}
}
P a n e l L a y o u t : A p a n e l i s a c o n t a i n e r o f c om p o n e n t s t h a t i s we a r e a b l e t o p l a c e
c o m p o n e n t s l i k e B u t t o n s, c h e c k b o x e s e t c . , o n t h e p a n e l . A p a n e l c a n h av e a se p a r a t e
background color, foreground color, layout etc.,
Out Put :
A p a n e l c a n c o n t a i n a n o t h e r p a n e l al so .
p u b l i c c l a ss p a n e l l a y ex t e n d s A p p l e t
{
Panel p1 = new Panel();
Panel p2 = new Panel();
p u b l i c v oi d i ni t ( )
{
se t L a y o u t ( n e w B o r d e r L a y o u t ( ) ) ; / / f o r t he a p p l e t
add(p1,BorderLayout.CENTER);
a d d ( p 2 , B o r d e r L a y o u t . SO U T H ) ;
p 1 . se t B a c k g r o u n d ( C o l o r . o r a n g e ) ;
p 2 . se t B a c k g r o u n d ( C o l o r . p i n k) ;
p 1 . se t L a y o u t ( n e w G r i d L a y o u t ( 2 , 2 , 5 , 5 ) );
p 1 . a d d ( n e w T ex t A r e a ( ) );
p 1 . a d d ( n e w T ex t A r e a ( ) );
144 SATEESH N
SATEESH N
p1.add(new Tex tArea());
p1.add(new Tex tArea());
p 2 . se t L a y o u t ( n e w F l o wL a y o u t ( ) ) ;
p 2 . a d d ( n e w B u t t o n ( " F i r st " ) ) ;
p2.add(new Button("Second"));
p2.add(new Button("Third"));
}
Card Layout : I n t h e c a r d l a y o u t a se t o f c a r d s wi l l b e a d d e d t o t h e l a y o u t . E a c h
c a r d c a n c o n t a i n a n y n u m b e r of c om p o n en t s. T o c r e a t e a c a r d a p a n e l wi l l b e u se d .
W h e n ev e r a c a r d i s se l e c t e d b y t h e u se r , t h e c o m p o n e n t s o f t h a t c a r d wi l l b e sh o wn o n
the applet.
W hi l e a d d i n g a c a r d , t o t h e c a r d l a y o u t we sh o u l d p r o v i d e a n am e f o r e a c h c a r d .
T h i s n am e sh o u l d b e u se d t o b r i n g t h a t c a rd t o t h e f r o n t .
/ / F i l e n am e : cardlay.java
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ; Out Put :
i m p o r t j av a. a wt . ev e n t . * ;
E:\Core> javac cardlay.java
/ / D e si g n i n g c a r d s
E:\Core> appletviewer cardlay.html
c l a ss f i r st c a r d ex t e n d s P a n e l
{
f i r st c a r d ( )
{
se t B a c k g r o u n d ( C o l o r . p i n k) ;
se t L a y o u t ( n e w F l o wL a y o u t ( ) ) ;
c l a ss se c o n d c a r d e x t e n d s P a n e l
{
se c o n d c a r d ( )
{
se t B a c k g r o u n d ( C o l o r . o r a n g e ) ;
se t L a y o u t ( n e w G r i d L a y o u t ( 2 , 2 , 1 0, 1 0 ) ) ;
add(new T e x t A r e a ( ) );
add(new T e x t A r e a ( ) );
add(new T e x t A r e a ( ) );
add(new T e x t A r e a ( ) );
}
}
c l a ss t h i r d c a r d ex t e n d s P a n e l
{
thirdcard()
{
145 SATEESH N
SATEESH N
se t B a c k g r o u n d ( C o l o r . r e d ) ;
se t L a y o u t ( n e w B o r d e r L a y o u t ( ) ) ;
S c r ol l b a r s1 = n e w S c r o l l b a r ( S c r ol l b a r . H O R I Z O N T A L ) ;
S c r ol l b a r s2 = n e w S c r o l l b a r ( S c r ol l b a r . V E R T I C A L );
a d d ( s1 , B o r d e r L a y o u t . S O U T H );
a d d ( s2 , B o r d e r L a y o u t . E A S T );
}
}
p u b l i c c l a ss c a r d l a y ex t e n d s A p p l e t i m pl em e n t s A c t i o n L i st e n e r
{
P a n el p 1 = n e w P a n e l ( ) ;
P a n el p 2 = n e w P a n e l ( ) ;
f i r st c a r d f c = n e w f i r st c a r d ( ) ;
se c o n d c a r d sc = n e w se c o n d c a r d ( ) ;
thirdcard tc = new thirdcard();
B ut t o n b 1 = n e w B u t t o n ( "S h o w f i r st " ) ;
B ut t o n b 2 = n e w B u t t o n ( "S h o w se c o n d " ) ;
B ut t o n b 3 = n e w B u t t o n ( "S h o w t h i r d " ) ;
p u bl i c v oi d i n i t ( )
{
se t L a y o u t ( n e w B o r d e r L a y o u t ( ) ) ;
se t F o n t ( n e w F o n t ( "S a n ss e r i f " , F o n t . B O LD , 1 4 ) ) ;
a d d ( p 2 , B o r d e r L a y o u t . C E NT E R ) ;
a d d ( p 1 , B o r d e r L a y o u t . SO U T H );
p 1 . se t L a y o u t ( n e w G r i d L a y o u t ( 1 , 3 ) );
p1.add(b1);
p1.add(b2);
p1.add(b3);
b 1 . a d d A ct i o n Li st e n e r ( t h i s) ;
b 2 . a d d A ct i o n Li st e n e r ( t h i s) ;
b 3 . a d d A ct i o n Li st e n e r ( t h i s) ;
p 2 . se t L a y o u t (m y L a y o u t );
p 2 . a d d (f c, " c a r d o n e " ); / / n am e f o r t h e ca r d
p 2 . a d d ( sc , " c a r d t wo " ) ;
p 2 . a d d ( t c, " c a r d t h r e e " ) ;
}
p u bl i c v oi d a c t i o n P e rf o rm e d (A c t i o n Ev e n t e )
{
if ( e.getSource() == b1 )
{
m y L a y o u t . sh o w( p 2 , " c a r d o n e " ) ;
}
el se i f ( e. g e t S o u r c e ( ) = = b 2 )
{
m y L a y o u t . sh o w( p 2 , " c a r d t wo " ) ;
}
146 SATEESH N
SATEESH N
e l se i f ( e. g e t S o u r c e ( ) = = b 3 )
{
m y L a y o u t . sh o w( p 2 , " c a r d t h r e e" ) ;
}
}
G r i d B ag L a y o u t : G r i d B a g L a y o u t i s t h e m o st p o we r f u l l a y o u t t o pl a c e t he
c o m p o n e n t s a t t h e r e q u i r e d l o c a t i o n s. T h e l a y o u t u se s a h e l p e r c l a ss ( t h a t i s G r i d B ag
c o n st r a i n t s ) f o r pl a ci n g t h e c om p o n e n t s.
G r i dB a g c o n st r a i n t i s c o n t ai n i n g som e v a ri ab l e s.
I n t h e G r i d B a g L a y o u t t h e t o t a l a r e a i s d i v i d e d i n t o r o ws a n d c o l u m n s. W h e n ev e r
we wa n t t o a d d a c o m p o n e n t , t h e l o c a t i o n a n d t h e d i m e n si o n s o f t h a t c om p o n e n t
sh o u l d b e sp e c i f i e d u si n g t h e g r i d b a g c o nst r a i n t s a n d t h e n t h e c o m p o n e n t sh o u l d b e
a d d e d . E a c h c om p o n e n t c a n o c c u p y m o r e t h a n o n e c e l l .
Sno Sname
Address
Tfee fpaid
Course save
save
0 1 2 3 4 5
0 Sno Sname
1 Address
2 Tfee fpaid
3 Course save
save
/ / F i l e n am e : g r i d b ag . j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ;
i m p o r t j av a. a wt . ev e n t . * ;
p u b l i c c l a ss g r i d b a g ex t e n d s A p p l e t
{
L a b e l l sn o = n e w L a b e l ( " S n o " );
L a b e l l sn a m e = n e w L a b e l ( " S n a m e " );
L a b e l l a d d r e ss = n e w L a b e l ( " A d d r e s s" ) ;
147 SATEESH N
SATEESH N
L a b e l l t f e e = n e w L a b e l ( " T o t F e e " );
L a b e l l f p ai d = n e w L a b e l ( " F e e p ai d " ) ;
L a b e l l c o u r se = n e w L a b e l ( " C o u r se " ) ;
T ex t F i el d sn o = n e w T ex t F i e l d ( 1 0 ) ;
T ex t F i el d sn a m e = n e w T ex t F i e l d ( 3 0 ) ;
T ex t F i el d a d d r e ss = n e w T e x t F i e l d ( 5 0 ) ;
T ex t F i el d t f e e = n e w T ex t F i el d ( 2 0 ) ;
T ex t F i el d f p ai d = n e w T ex t F i el d ( 2 0 ) ;
C h o i c e c o u r se = n e w C h o i c e ( ) ;
B u t t o n b 1 = n e w B u t t o n ( " S av e " );
G r i d B a g C o n st r a i n t s g c = n e w G ri d B a g C o n st r a i n t s( ) ;
p u b l i c v oi d i ni t ( )
{
Out Put :
se t L a y o u t ( g b ) ;
E:\Core> javac gridbag.java
g c . f i l l = G ri d B a g C o n st r a i n t s. B O T H ;
E:\Core> appletviewer gridbag.html
/ / a d d i n g l sn o
g c . g ri dx = 0;
g c . g ri d y = 0;
g c . g ri d wi d t h = 1 ;
g c . g ri d h e i g h t = 1 ;
g b . se t C o n st r a i n t s( l sn o , g c ) ;
a d d ( l sn o ) ;
/ / a d d i n g sn o
g c . g ri dx = 1;
g b . se t C o n st r a i n t s( sn o , g c ) ;
a d d ( sn o ) ;
/ / a d d i n g l sn a m e
g c . g ri dx = 2;
g b . se t C o n st r a i n t s( l sn a m e , g c ) ;
a d d ( l sn a m e );
/ / f o r sn a m e
g c . g ri dx = 3;
g c . g ri d wi d t h = 3 ;
g b . se t C o n st r a i n t s( sn a m e , g c );
a d d ( sn a m e ) ;
/ / a d d i n g l a d d r e ss
g c . g ri dx = 0;
g c . g ri d y = 1;
g c . g ri d wi d t h = 1 ;
g b . se t C o n st r a i n t s( l a d d r e s s, g c ) ;
a d d ( l a d d r e ss) ;
148 SATEESH N
SATEESH N
/ / f o r a d d r e ss
g c . g ri dx = 1;
g c . g ri d wi d t h = 5 ;
g b . se t C o n st r a i n t s( a d d r e s s, g c ) ;
a d d ( a d d r e s s) ;
// addi ng l tfee
g c . g ri dx = 0;
g c . g ri d y = 2;
g c . g ri d wi d t h = 1 ;
g b . se t C o n st r a i n t s( l t f e e , g c );
add(ltf ee);
// f or tf ee
g c . g ri dx = 1;
g c . g ri d wi d t h = 2 ;
g b . se t C o n st r a i n t s( t f e e , g c ) ;
add(tf ee);
/ / a d d i n g l f p ai d
g c . g ri dx = 3;
g c . g ri d wi d t h = 1 ;
g b . se t C o n st r a i n t s( l f p a i d, g c ) ;
a d d ( l f p ai d ) ;
/ / f o r f p ai d
g c . g ri dx = 4;
g c . g ri d wi d t h = 2 ;
g b . se t C o n st r a i n t s( f p a i d, g c ) ;
a d d (f p a i d );
/ / a d d i n g l c o u r se
g c . g ri dx = 0;
g c . g ri d y = 3;
g c . g ri d wi d t h = 1 ;
g b . se t C o n st r a i n t s( l c o u r se , g c ) ;
a d d ( l c o u r se ) ;
/ / f o r c o u r se
g c . g ri dx = 1;
g c . g ri d wi d t h = 3 ;
g b . se t C o n st r a i n t s( c o u r se , g c ) ;
a d d ( c o u r se ) ;
// f or b1
g c . g ri dx = 4;
g c . g ri d wi d t h = 2 ;
g b . se t C o n st r a i n t s( b 1 , g c ) ;
add(b1);
c o u r se . a d d ( " V i su a l B a si c " );
c o u r se . a d d ( " J av a " );
c o u r se . a d d ( " P o we r B u i l d e r " ) ;
}
}
149 SATEESH N
SATEESH N
N U L L L a yo u t : I f t h e l a y o u t i s sa i d t o n u l l we sh o u l d sp e c i f y t h e l o c a t i o n a n d t h e
d i m e n si o n of t h e c om p o n e n t s wh i l e a d d i n g .
/ / F i l e n am e : n u l l t e s t . j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ;
p u b l i c c l a ss n u l l t e st ex t e n d s A p p l e t Out Put :
{
B ut t o n b 1 , b 2 ; E:\Core> javac nulltest.java
se t L a y o u t ( n u l l ) ; / / R em ov e t h e c u r r e n t L a y o u t
b 1 . se t L o c a t i o n ( 5 0 , 5 0 ); //x,y
b 1 . se t Si z e ( 1 5 0 , 4 0 ) ; / / wi d t h , h e i g h t
add(b1);
b 2 . se t B o u n d s( 2 1 0 , 7 5 , 1 5 0 , 4 0 ) ; / / x , y , wi d t h , h e i g h t
add(b2);
}
}
F r a me s : A f r am e i s a c o n t ai n e r wh i c h i s u se d f o r d i sp l a yi n g t h e c om p o n e n t s i n a
se p a r a t e wi n d o w.
A f r am e c o n t a i ni n g t h e f ol l o wi n g f e a t u r e s :
i. T h e f r am e c o n t a i n s t i t l e b a r, m i ni m i z e , m ax i m um , b u t t o n s.
ii. C o n t a i n s r e si z a b l e b o r d e r s.
iii. Contains a m enu bar.
T o c r e a t e a f r am e, c r e a t e a cl a ss t h a t e x t e nd s t h e f r am e cl a ss.
C o n st r u c t o r s :
f r am e ( ) : C r e a t e s a f r am e .
f r am e ( S t ri n g t i t l e ) :
Methods :
v oi d se t T i t l e ( S t ri n g n e wT i t l e ) :
S t ri n g g e t T i t l e ( ) :
150 SATEESH N
SATEESH N
/ / F i l e n am e : frametest1.java
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a p p l e t . * ;
i m p o r t j av a. a wt . ev e n t . * ;
c l a ss M y F r am e ex t e n d s F r am e
{
M yF r am e ( )
{
se t T i t l e ( " S am pl e F r am e " );
se t Si z e ( 2 0 0 , 1 5 0 ) ;
se t B a c k g r o u n d ( C o l o r . pi n k ) ;
}
}
p u b l i c c l a ss f r am e t e st 1 ex t e n d s A p p l e t i m pl e m e n t s A ct i o n Li st e n e r
{
B ut t o n b 1 , b 2 ;
Out Put :
M y F r am e f ;
E:\Core> javac frametest1.java
p u bl i c v oi d i n i t ( )
E:\Core> appletviewer frametest1.html
{
se t B a c k g r o u n d ( C o l o r . cy a n ) ;
b 1 = n e w B u t t o n ( " S h o w F r am e " );
b 2 = n e w B u t t o n ( " Hi d e F r am e " ) ;
add(b1);
add(b2);
f = n e w M y F r am e () ;
b 1 . a d d A ct i o n Li st e n e r ( t h i s) ;
b 2 . a d d A ct i o n Li st e n e r ( t h i s) ;
}
p u bl i c v oi d a c t i o n P e rf o rm e d (A c t i o n Ev e n t e )
{
if ( e.getSource() == b1 )
f . se t V i si bl e ( t r u e ) ;
el se i f ( e. g e t S o u r c e ( ) = = b 2 )
f . se t Vi si b l e (f al se ) ;
}
}
/ / F i l e n am e : frametest2.java
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ;
i m p o r t j av a. a p p l e t . * ;
c l a ss M y F r am e ex t e n d s F r am e i m p l em e n t s A c t i o n L i st e n e r
{
B ut t o n b 1 = n e w B u t t o n ( "Ex i t P r o g r am " ) ;
M y F r am e( )
{
se t T i t l e ( " S am pl e F r am e 2 ") ;
se t Si z e ( 3 0 0 , 2 0 0 ) ;
151 SATEESH N
SATEESH N
se t B a c k g r o u n d ( C o l o r . pi n k ) ;
se t L a y o u t ( n e w F l o wL a y o u t ( ) ) ; Out Put :
add(b1);
b 1 . a d d A ct i o n Li st e n e r ( t h i s) ; E:\Core> javac frametest2.java
}
E:\Core> java frametest2
p u bl i c v oi d a c t i o n P e rf o rm e d (A c t i o n Ev e n t e )
{
i f ( e. g e t S o u r c e ( ) = = b 1 )
{
se t Vi si b l e (f a l se ) ;
S y st em . ex i t ( 0 );
}
}
}
p u b l i c c l a ss f r am e t e st 2 ex t e n d s A p p l e t
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
M yF r am e f = n e w M yF r am e ( ) ;
f . se t V i si bl e ( t r u e ) ; / / sh o w t h e f r am e
}
}
Handling a Frame : T o h a n d l e a f r am e t h e W i n d o wL i st e n e r wi l l b e u se d . W h i c h i s
c o n t a i n i n g t h e f ol l o wi n g 7 m e t h o d s.
1. p u b l i c v o i d wi n d o wC l o si n g ( W i n d o wEv e n t e ) : T h i s e v e nt wi l l b e c a l l e d w h e n
ev e r t h e u se r c l i c k s o n t h e c l o se B u t t o n of t h e wi n d o w.
2. p u b l i c v o i d wi n d o wC l o se d ( W i n d o wEv e n t e ) : Af t e r t h e wi n d o w w a s c l o se d .
3. p u b l i c v o i d wi n d o wO p e n e d ( W i n d o wEv e n t e ) : Af t e r t h e wi n d o w wa s o p e n e d .
4. p u b l i c v o i d wi n d o wA c t i v at e d ( W i n d o wEv e n t e ) :
5. p u b l i c v o i d wi n d o wD e a c t i v a t e d ( W i n d o wEv en t e ) :
6. p u b l i c v o i d wi n d o wI c o n i f i e d (W i n d o wEv e n t e) : W h e n ev e r t h e wi n d o w i s m i n i m i z e d .
7. p u b l i c v o i d wi n d o wD e i c o n i f i e d (W i n d o wEv e nt e ) : Af t e r t h e wi n d o w wa s r e st o r e d .
/ / F i l e n am e : f r a m e t e s t 3 . j a v a
/ / ov e r ri d e al l t h e m e t h o d s o f W i n d o wL i st e n e r
i m p o r t j av a. i o. * ;
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ;
c l a ss M y F r am e ex t e n d s F r am e i m p l em e n t s W i n d o wL i st e n e r
{
M y F r am e( )
{
se t T i t l e (" S am pl e F r am e 3 ") ;
se t S i z e ( 3 0 0 , 2 0 0 ) ;
se t B a c k g r o u n d ( C o l o r . p i n k );
152 SATEESH N
SATEESH N
a d dW i n d o wL i st e n e r ( t h i s) ;
}
/ / ov e r ri d i n g al l t h e 7 m e t h o d s of W i n d o wL i st e n e r
p u b l i c v o i d wi n d o wC l o se d (W i n d o wE v e n t e )
Out Put :
{
E:\Core> javac frametest3.java
}
E:\Core> java frametest3
p u b l i c v o i d wi n d o wC l o si n g (W i n d o wEv e n t e )
{
se t V i si bl e (f al se ) ;
S y st em . ex i t ( 0 ) ;
}
p u b l i c v o i d wi n d o wO p e n e d (W i n d o wEv e n t e )
{
p u b l i c v o i d wi n d o wA c t i v at e d (W i n d o wEv e n t e )
{
p u b l i c v o i d wi n d o wD e a c t i v a t e d (W i n d o wEv en t e )
{
p u b l i c v o i d wi n d o wI c o n i f i e d (W i n d o wEv e n t e)
{
p u b l i c v o i d wi n d o wD e i c o n i f i e d (W i n d o wEv e nt e )
{
c l a ss f r am e t e st 3
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
My F r am e f = n e w M y F r am e ( ) ;
f . se t B o u n d s( 1 0 0 , 1 0 0 , 3 0 0 , 2 0 0 ) ;
f . se t V i si bl e ( t r u e );
}
}
w i n d o w Ad a p t e r : wi n d o wA d a p t e r i s a c l a s s a v ai l a b l e i n t h e j av a. a wt p a c k a g e wh i c h
i m pl em e n t s t h e wi n d o wL i st e n e r i n t e r f a c e a n d o v e r ri d e s a l l i t s m e t h o d s wi t h o u t a n y
st a t e m e n t s. W h e n we c r e a t e a c l a s s t h a t e x t e n d s t h e wi n d o w a d a p t e r c l a ss we c a n
ov e r ri d e o n l y t h e r e q u i r e d m et h o d s.
T h i s f e a t u r e i s i m p l em e nt s f r om j d k 1 . 2 o n w a r d s.
153 SATEESH N
SATEESH N
/ / F i l e n am e : frametest4.java
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ;
i m p o r t j av a. a p p l e t . * ;
c l a ss M y F r am e ex t e n d s F r am e
{
M y F r am e( )
{
se t T i t l e ( " S am pl e F r am e 4 ") ;
se t Si z e ( 3 0 0 , 2 0 0 ) ;
se t B a c k g r o u n d ( C o l o r . pi n k ) ;
a d dW i n d o wL i st e n e r ( n e w M yW i n d o wA d a p t e r ( ) ) ;
}
cl a ss M yW i n d o wA d a p t e r e x t e n d s W i n d o wA d a p t e r Out Put :
// inner
{ E:\Core> javac frametest4.java
p u b l i c v o i d wi n d o wC l o si n g (W i n d o wEv e n t e )
{ E:\Core> java frametest4
se t Vi si b l e (f a l se ) ;
S y st em . ex i t ( 0 );
}
}
}
c l a ss f r am e t e st 4
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
M yF r am e f = n e w M yF r am e ( ) ;
f . se t V i si bl e ( t r u e ) ; / / sh o w t h e f r am e
}
}
S i m i l a r l y t h e i nt e rf a c e s l i k e F o c u sL i st e n e r , M o u se L i st e n e r , K e y L i st e n e r e t c . , wh i c h
a r e c o n t a i n i n g m o r e t h a n o n e m et h o d s t h e c o r r e sp o n d i n g a d a p t e r c l a ss e s a l s o
av ai l a bl e .
A n on y m ou s c l a s se s : A n a n o n y m o u s c l a s s i s a c l a s s wh i c h a l l o ws u s t o o v e r ri d e a
m et h o d of a c l a ss a t t h e t i m e of c r e a t i n g a n i n st a n c e of t h e cl a ss.
Ac t i o n L i s t en e r : T hi s i s a cl a ss wh i c h a l l o w s u s t o ov e r ri d e t h e m et h o d s o f t h e cl a ss ,
a t t h e t i m e of c r e a t i n g t h e i n t e rf a c e of t h e cl a ss.
/ / F i l e n am e : frametest5.java
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ;
c l a ss M y F r am e ex t e n d s F r am e
{
M y F r am e( )
{
154 SATEESH N
SATEESH N
se t B o u n d s( 5 0 , 5 0 , 3 0 0 , 2 0 0 ) ;
se t T i t l e (" S am pl e F r am e 5 " ) ;
se t B a c k g r o u n d ( C o l o r . p i n k );
a d dW i n d o wL i st e n e r ( n e w W i n d o wA d a p t e r ( )
{
p u b l i c v o i d wi n d o wC l o si n g (W i n d o wEv e n t e )
{
se t Vi si b l e (f al se ) ;
Sy st e m . ex i t ( 0 ) ;
Out Put :
}
} E:\Core> javac frametest5.java
);
} E:\Core> java frametest5
}
c l a ss f r am e t e st 5
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
M yF r am e f = n e w M y F r am e ( );
f . se t Vi si b l e (t r u e ) ;
}
}
/ / F i l e n am e : b u t t o n c h kb o x. j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ; Out Put :
i m p o r t j av a. a p p l e t . * ;
E:\Core> javac buttonchkbox.java
p u b l i c c l a ss b u t t o n c h k b o x ex t e n d s A p p l e t
{ E:\Core> appletviewer buttonchkbox.html
B u t t o n b 1 = n e w B u t t o n ( " F i r st B u t t o n " );
C h e c k b ox c b 1 = n e w C h e c k b o x ( "S am p l e Ch e c k b o x " );
p u b l i c v oi d i ni t ( )
{
se t F o n t ( n e w F o n t ( "S a n ss e r i f " , F o n t . B O LD , 1 4 ) ) ;
add(b1);
add(cb1);
C h ec k b ox state changed
b 1 . a d d A ct i o n Li st e n e r ( n e w A c t i o n Li st e n e r ( )
{
p u b l i c v oi d a ct i o n P e rf o r m e d ( A ct i o n Ev e nt e )
{
sh o wS t a t u s( " F i r st B ut t o n Cl i c k e d " ) ;
}
}
);
c b 1 . a d d I t em Li st e n e r ( n e w I t em Li st e n e r ( )
{
p u bl i c v oi d i t em St a t e Ch a n g e d ( I t e m Ev e nt e )
{
sh o wS t a t u s( " C h e c k b o x S t a t e C h a n g e d " ) ;
}
}
);
}
}
155 SATEESH N
SATEESH N
/ / F i l e n am e : g e t f o n t l i s t . j a v a
/ / t o v i e w t h e av ai l a b l e f o n t s i n j av a
i m p o r t j av a. i o. * ; Out Put :
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ; E:\Core> javac getfontlist.java
S t ri n g a r r[ ] = t k. g e t F o n t Li st ( ) ;
f o r (i n t i = 0 ; i < a r r. l e n g t h ; i + + )
{
S y st em . o u t . p ri n t l n ( a r r [ i ] );
}
}
}
class getfontlist
{
public static void main(String args[ ] )
{
MyFrame f = new MyFrame( ) ;
f . setVisible(true) ;
}
}
M e n u s : A f r am e c o n t ai n s m e n u b a r .
T h e f ol l o wi n g cl a sse s wi l l b e u se d b y d e si g n i n g m e n u s.
Menu Bar
Menu
M e n u I t em
C h e c k b o x M e n u I t em
PopupMenu
MenuShortcut
A m e n u c a n c o n t ai n t h e f ol l o wi n g i t em s.
M e n u I t em s
C h e c b o x M e n ui t em s
Separators
M e n u s ( su b m e n u s )
A M e n u I t em sh o u l d b e h a n d l e d u si n g t h e A c t i o n L i st e n e r i n t e rf ac e a n d a C h e c k b o x
M e n u I t em sh o u l d b e u si n g t h e I t em Li st e n e r i n t e rf a c e.
156 SATEESH N
SATEESH N
/ / f i l e n am e : m en u t e s t. j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ;
i m p o r t j av a. a p p l e t . * ;
p u b l i c c l a ss m e n u t e st ex t e n d s A p p l e t
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
M yF r am e f = n e w M y F r am e ( );
f . se t B o u n d s( 1 0 0 , 1 0 0 , 3 0 0 , 2 0 0 ) ;
f . se t Vi si b l e (t r u e ) ;
}
}
c l a ss M y F r am e ex t e n d s F r am e i m p l em e n t s A c t i o n L i st e n e r , I t em Li st e n e r
{
T ex t Ar e a t 1 = n e w T ex t A r e a ( ) ;
M e n u f i l e = n e w M e n u ( " F i l e " );
M e n u wi n d o w = n e w M e n u ( "W i n d o w" ) ;
M e n u t i l e = n e w M e n u ( " T i l e " );
M e n u I t em o pt n e w, o p t o p e n , o p t sa v e , o p t ex i t , o p t c a sc a d e , o p t h o r z , o p t v e rt ;
M y F r am e( )
{
se t F o n t ( n e w F o n t ( " S a n se r i f " , F o n t . BO LD , 1 4 ) ) ;
add(t1);
o p t n e w = n e w M e n u I t em ( " n e w" , n e w M e n u S h o r t c u t ( ' N ' , f al se ) ) ;
/ / f al se : ct rl + N
/ / t r u e : c t rl + sh i f t + O Out Put :
o p t sav e = n e w M e n u I t em ( " sav e" ) ; E:\Core> javac menutest.java
o p t ex i t = n e w M e n u I t em ( " ex i t " ) ;
o p t c a sc a d e = n e w M e n u I t em ( " c a sc a d e " ) ; E:\Core> java menutest
o p t h o r z = n e w M e n u I t em ( " H o ri z o n t al " ) ;
o p t v e r t = n e w M e n u I t em ( " V e r t i c al " );
se t M e n u B a r ( m b a r );
m b a r . a d d (f i l e ) ;
m b a r . a d d ( wi n d o w) ;
f i l e. a d d ( o p t n e w) ;
f i l e. a d d ( o p t o p e n ) ;
f i l e. a d d ( o p t sav e ) ;
f i l e. a d d ( o p t a u t o sav e ) ;
f i l e. a d d S e p a r a t o r ( ) ;
f i l e. a d d ( o p t e x i t ) ;
wi n d o w. a d d ( o p t c a sc a d e ) ;
wi n d o w. a d d ( t i l e ) ;
157 SATEESH N
SATEESH N
t i l e. a d d ( o p t h o r z ) ;
t i l e. a d d ( o p t v er t );
o p t n e w. a d d A c t i o n L i st e n e r ( t h i s) ;
o p t sav e . a d d A c t i o n L i st e n e r ( t hi s) ;
o p t o p e n . a d d A c t i o n Li st e n e r ( t h i s) ;
o p t ex i t . a d d A ct i o n Li st e n e r ( t h i s) ;
o p t c a sc a d e . a d d A c t i o n L i st e n e r ( t hi s) ;
o p t h o r z . a d d A c t i o n L i st e n e r ( t hi s) ;
o p t v e r t . a d d A c t i o n L i st e n e r ( t h i s) ;
o p t a u t o sav e . a d d I t em Li st e n e r ( t h i s) ;
}
p u bl i c v oi d a c t i o n P e rf o rm e d (A c t i o n Ev e n t e )
{
if ( e.getSource() == optnew )
t 1. se t T ex t ( " N e w I t em S el e c t e d " ) ;
el se i f ( e. g e t S o u r c e ( ) = = o p t o p e n )
t 1 . se t T ex t ( " O p e n o p t i o n se l e c t e d" ) ;
e l se i f ( e. g e t S o u r c e ( ) = = o p t ex i t )
{
se t V i si b l e (f a l se ) ;
S y st em . ex i t ( 0 );
}
e l se
{
t 1 . se t T ex t ( e . g e t A ct i o n C o m m an d ( ) + " se l e c t e d " );
}
}
p u bl i c v oi d i t em St a t e C h a n g e d ( I t em Ev e n t e )
{
i f ( o pt a u t o sav e . g e t St a t e ( ) = = t r u e )
t 1 . se t T ex t ( " A u t o S av e : C HE C K E D O N ") ;
el se
t 1 . se t T ex t ( " A u t o S av e : C HE C K E D O F F " ) ;
}
}
KeyListener : K e y L i st e n e r i s u se d f o r h a nd l i n g k e y ev e nt s.
p u b l i c v o i d K e y P r e sse d ( K e y Ev e nt e ) : W h e n e v e r t h e k e y i s d o wn .
p u b l i c v o i d K e y R e l e a se d ( K e y Ev e n t e ) : W h e n e v e r t h e k e y i s d o wn .
p u b l i c v o i d K e y T y p e d ( K e y Ev e nt e ) : B o t h d o w n a n d u p .
K e y Ev e nt :
C h a r g e t K e y C h a r ( ) : R e t u r n s t h e c h a r a ct e r t y p e d b y t h e u se r .
M o u s eL i s t e n e r : I t i s u se d f o r h a n d l i n g M ou se e v e n t s.
p u b l i c v o i d M o u se P r e s se d ( M o u se Ev e n t e ) : wh e n ev e r t h e m o u se b u t t o n i s d o wn .
p u b l i c v o i d M o u se R e l e a se d ( M o u se E v e nt e ) : wh e n e v e r t h e m o u se b u t t o n i s u p .
158 SATEESH N
SATEESH N
p u b l i c v o i d M o u se C l i c k e d ( M o u se Ev e n t e ) : wh e n e v e r t h e m o u se b u t t o n i s d o wn + u p .
p u b l i c v o i d M o u se E n t e r e d ( M o u se Ev e n t e ) : M o u se i s e n t e r e d o n a c om p o n e n t
i . e . , M o u se i s ov e r a c om p o n e n t .
p u b l i c v o i d M o u se E x i t e d ( M o u se Ev e n t e ) : M o u se i s o u t of a c om p o n e n t .
M o u se E v e n t :
i n t g et x ( ) :
R e t u r n s t h e c o - o r d i n a t e s of t h e m o u se p o i n t e r .
i n t g et y ( ) :
i n t g et M o d i f i e r s : R e t u r n s t h e b i t p a t t e r n of t h e m o u se k e y s a n d sh i f t k e y s.
Ex: sh i f t al t c t rl e n t er . . . o n m l . . .
I f ct rl k e y i s p r e s se d v al u e 1 wi l l b e st o r e d o t h e r wi se 0 wi l l b e st o r e d .
B U T T O N 1 : l ef t B UT T O N 2 : m i d dl e B UT T O N 3 : ri g h t
PopupMenu : A n o r m a l m e n u sh o u l d a l wa y s b e a t t a c h e d t o t h e m e n u b a r wh i l e a
p o p u p m e n u c a n b e di sp l a y e d a n y wh e r e o n t h e c om p o n e n t .
/ / F i l e n am e : popuptest.java
Out Put :
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ; E:\Core> javac popuptest.java
i m p o r t j av a. a p p l e t . * ;
E:\Core> java popuptest
c l a ss M y F r am e ex t e n d s F r am e
{
T ex t Ar e a t 1 = n e w T ex t A r e a ( ) ;
M y F r am e( )
{
a d d ( t 1 );
add(popup);
p o p u p . a d d ( n e w M e n u I t e m ( "F i r st o p t i o n " )) ;
p o p u p . a d d ( n e w M e n u I t e m ( "S e c o n d o p t i on " ) ) ;
p o p u p . a d d ( n e w M e n u I t e m ( "T hi r d o p t i o n ") ) ;
p o p u p . a d d ( n e w M e n u I t e m ( "F o u r t h o pt i on " ) ) ; to close the applet goto command prompt
popup.addSeparator(); and click ctrl+c
p o p u p . a d d ( n e w M e n u I t e m ( "F i f t h o p t i o n " )) ;
t 1 . a d d M o u se L i st e n e r ( n e w M y M o u se A d a p t e r ( ) ) ;
}
cl a ss M y M o u se A d a p t e r e x t e n d s M o u se A d a p t e r
{
p u b l i c v oi d m o u se P r e ss e d ( M o u s e Ev e n t e )
{
i n t x = e . g e t X( ) ;
i nt y = e.getY();
159 SATEESH N
SATEESH N
if( ( e.getModifiers( ) & InputEvent.BUTTON3_MASK ) == InputEvent.BUTTON3_MASK )
// in the above statement & is bit-wise operator to verify the bit is ON or OFF
{
p o p u p . sh o w( t 1 , x , y ) ;
}
}
}
} / / e n d of M y F r am e
p u b l i c c l a ss p o p u p t e st e x t e n d s A p p l e t
{
p u b l i c st a t i c v o i d m ai n ( S t ri n g a r g s[ ] )
{
M yF r am e f = n e w M y F r am e () ;
f . se t B o u n d s( 1 0 0 , 1 0 0 , 3 0 0 , 2 0 0 ) ;
f . se t V i si b l e (t r u e ) ;
}
}
Dialog : A d i a l o g i s si m i l a r t o a f r am e use d f o r d i sp l a y i n g i nf o rm at i o n i n a se p a r a t e
wi n d o w. A d i al o g wh e n c o m p a r e d wi t h t h e f ra m e i s c o n t ai n i n g t h e f ol l o wi n g di f f e r e n c e.
1 . A d i al o g c a n n o t c o n t ai n a m e n u b a r .
2 . A d i al o g sh o u l d a l wa y s b e c r e a t e d f r om a f ra m e o r a f r am e a n o t h e r di a l o g .
3 . A d i al o g c a n b e m o d ul a r o r m o d e l e ss.
C o n s t r u c to r : Di a l o g ( F r am e p a r e n t )
D i al o g ( F r am e P a r e n t , S t ri n g t i t l e )
D i al o g ( F r am e p a r e n t , St r i n g t i t l e , B o o l ea n m o d al )
F i l e Di a l o g : I t d i sp l a y s t h e o p e n o r sav e d i a l o g b ox e s.
C o n s t r u c to r : F i l e D i al o g ( F r am e p a r e n t , S t ri n g t i t l e , i nt t y p e )
Type:
Out Put :
F i l e Di a l o g . LO A D : f o r o p e n D i al o g .
F i l e Di a l o g . SA V E : F o r sav e d i al o g . E:\Core> javac filetest.java
S t ri n g g e t F i l e ( ) :
S t ri n g g e t D i r e ct o r y ( ) :
/ / F i l e n am e : F i l e t e s t . j a v a
i m p o r t j av a. a wt . * ;
i m p o r t j av a. a wt . ev e n t . * ;
i m p o r t j av a. i o. * ;
c l a ss f i l et e st
{
p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] )
{
M yF r am e f = n e w M y F r am e ( );
160 SATEESH N
SATEESH N
f . se t B o u n d s( 1 0 0 , 1 0 0 , 4 0 0 , 3 0 0 ) ;
f . se t Vi si b l e (t r u e ) ;
}
}
c l a ss M y F r am e ex t e n d s F r am e i m p l em e n t s A c t i o n L i st e n e r
{
T ex t A r e a t 1 = n e w T ex t A r e a ( );
B u t t o n b 1 = n e w B u t t o n ( "O p e n F i l e" ) ;
B u t t o n b 2 = n e w B u t t o n ( " Ex i t P r o g r am ") ;
F i l e D i al o g f d = n e w F i l e D i al o g ( t hi s, " S e l e ct F i l e" , F i l e D i al o g . LO A D );
M yF r am e ( )
{
se t F o n t ( n e w F o n t ( " A ri al N a r r o w" , F o n t . BO L D , 1 4 ) ) ;
a d d ( t 1 , B o r d e r L a y o u t . C E NT E R );
a d d ( p 1 , B o r d e r L a y o u t . SO U T H ) ;
p 1 . se t L a y o u t ( n e w G r i d L a y o u t ( 1 , 2 ) ) ;
p1.add(b1);
p1.add(b2);
b 1 . a d d A c t i o n L i st e n e r ( t h i s) ;
b 2 . a d d A c t i o n L i st e n e r ( t h i s) ;
}
p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e nt e)
{
i f ( e. g e t S o u r c e ( ) = = b 1 )
o p e nf i l e ( ) ;
e l se i f ( e . g e t S o u r c e ( ) = = b 2 )
{
se t V i si b l e (f a l se ) ;
S y st em . ex i t ( 0 );
}
}
v oi d o p e nf i l e ( )
{
try
{
f d. se t V i si bl e ( t r u e ) ; / / di pl a y t h e f i l e d i a l o g
St r i n g d i r N am e = f d . g e t Di r e ct o r y ( ) ;
i f ( d i r N am e ! = n u l l )
{
S t r i n g f i l e n am e = d i r N am e + f d . g e t F i l e ( ) ;
F i l e f = n e w F i l e (f i l e n am e ) ;
i n t f i l e si z e = ( i nt ) f . l e n g t h ( ) ; / / n o . of c h a r a c t e r s
i n t st a r t = 0 ; / / st a r t i n g p o st i o n
161 SATEESH N
SATEESH N
// open the fil e
F i l e I n p u t St r e am f i n = n e w F i l e I n p u t St r e a m (f i l e n am e ) ;
/ / R e a d al l t h e c h a r a ct e r i n t o t h e b uf f e r
b y t e a r r [ ] = n e w b y t e [ f i l e si z e ] ;
f i n . r e a d ( a r r, st a r t , f i l e si z e ) ; / / r e a d al l t h e
/ / p u t t h e r e a d d a t a, t 1
t 1. se t T ex t ( n e w S t ri n g ( a r r ) ) ;
se t T i t l e (f i l e n a m e );
f i n . cl o se ( ) ;
} / / e n d of i f
}
c at c h ( Ex c e p t i o n ex )
{
t 1. se t T ex t ( "E r r o r : "+ ex ) ;
se t T i t l e ( " " );
}
}
} / / e n d of M yF r am e c l a ss
162 SATEESH N
SATEESH N
This feature of Java allows a java program to connect with the backend database such as oracle, SQL
server etc., to perform Database transactions.
In order to connect from a java program to the backend database a special program is required which
is known as a driver.
Data Base
Java Program Driver
The drivers are divided into 4 categories named as type1, type2, type3, type4.
DriverName : JdbcOdbcBridge, which is of the type1 driver. The above driver uses Microsoft ODBC to
connect with the data bases.
java.sql package : This containing the following interfaces and classes for managing database transactions.
Class : DriverManager
Interfaces : Connection
Statement
PreparedStatement
CallableStatement
ResultSet
ResultSetMetaData
DatabaseMetaData
Loading the driver : The driver should be loaded into the memory before getting a connection. The
forName( ) method will be used to load the driver.
class Class :
Getting a Connection with the Database : The following methods of DriverManager class can be used for
opening connections with the database.
163 SATEESH N
SATEESH N
“ tiger “ is the password , “ scott “ is user name , “ javaoracle “ is the data source name created in the
control panel.
Creating a Data Source Name (DSN) : In the control panel ODBC in the userDSN , click on the ADD
button, which displays a list of the installed drivers select the required driver, for ex. MicrosoftODBC for
oracle, click on Finish button and specify a name for the data source, for ex. Javaoracle
import java.sql.*;
class testcon
{
public static void main(String args[ ])
{
try
{
System.out.print("Loading Driver ..... ");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println(" OK ");
System.out.print("Getting Connection ..... ");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
System.out.println(" OK ");
DatabaseMetaData dbmd = con.getMetaData( );
System.out.println("Driver Name : "+dbmd.getDriverName( ));
System.out.println("Database Name: "+dbmd.getDatabaseProductName( ));
System.out.print("Closing Connection....");
con.close( );
System.out.println(" OK");
}
catch(ClassNotFoundException ex)
{
System.out.println("Driver Not Loaded");
}
catch(SQLException ex)
{
System.out.println("SQL Error: "+ex);
}
}
}
Methods :
Statement createStatement( ) throws SQLException : Creates a statement. A statement is used for executing
SQL statements against the database.
164 SATEESH N
SATEESH N
CallableStatement prepareCall ( String sql statement ) : Prepares a callable statement, which is used for
executing stored procedures of the database.
Methods :
ResultSet executeQuery( String select-statement ) : Executes the given select statement and returns the
result set which contains the selected records.
int executeUpdate( String dml-statement ) : Executes the given dml statement and returns the no. of records
that are effected from the execution.
boolean execute( String sql-statement ) : Executes any SQL statement, returns true if a select statement is
executed, it returns false for a non-select statement.
int getUpdateCount( ) : Returns the number of records that are effected in the last execution.
ResultSet : Contains the selected records from the database. The ResultSet contains the pointer which by
default position at the first record.
int getInt( int fieldno ) : Returns the value of the specified field. Field number starts from 1 .
Similarly the other get methods are available for the remaining data types.
ResultSetMetaData getMetaData( ) : Returns the ResultSetMetaData, which contains the details of the
resultset.
String getColumnLabel( int field no ) : Returns the label of the specified column.
165 SATEESH N
SATEESH N
// File name : getrecords.java
import java.io.*;
import java.sql.*;
class getrecords
{
public static void main(String args[])
{
try
{
System.out.println("Loadig Driver ....");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Getting Connection...");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
System.out.println("Connection Established...");
System.out.println();
System.out.println("EMPNO NAME JOB SAL DEPTNO\n");
while(rs.next())
{
int empno = rs.getInt(1);
String ename = rs.getString(2);
String job = rs.getString("JOB");
double sal = rs.getDouble(4);
int deptno = rs.getInt("DEPTNO");
System.out.println(empno+"\t"+ename+"\t"+job+"\t"+sal+"\t"+deptno);
}
rs.close();
stmt.close();
con.close();
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}
166 SATEESH N
SATEESH N
// File name : getrecords2.java
// to execute the given select statement and display the records
import java.io.*;
import java.sql.*;
class getrecords2
{
public static void main(String args[])
{
try
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Loadig Driver ....");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Getting Connection...");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
System.out.println("Connection Established...");
System.out.println();
// create the statement
Statement stmt = con.createStatement();
int i,n;
n = rm.getColumnCount();
System.out.println();
// display the resultset
while(rs.next())
{
// for each row
for(i=1;i<=n;i++)
{
System.out.print("\t"+rs.getString(i));
}
System.out.println();
}
rs.close();
stmt.close();
con.close();
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}
167 SATEESH N
SATEESH N
// File name : getrecords3.java
// to accept a query & display the fetched records of the query along with the column headings
import java.io.*;
import java.sql.*;
class getrecords3
{
public static void main(String args[])
{
try
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Getting Connection ....");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
Statement stmt = con.createStatement();
String str;
while(true)
{
try
{
System.out.println();
System.out.print("Query>");
str = stdin.readLine();
if(str.trim().toUpperCase().equals("QUIT"))
break;
ResultSet rs = stmt.executeQuery(str);
displayRecords(rs);
rs.close();
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
stmt.close();
con.close();
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
System.out.println();
// displaying headings
168 SATEESH N
SATEESH N
for(i=1;i<=n;i++)
{
System.out.print("\t"+rsmd.getColumnLabel(i));
}
System.out.println();
System.out.println("\t-----------------------------------------");
while(rs.next())
{
for(i=1;i<=n;i++)
{
System.out.print("\t"+rs.getString(i));
}
System.out.println();
}
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
Whenever we open the resultset using the executingQuery( ) function the result set will be opened in a
forward only mode. i.e., the record pointer can be moved only in the forward direction but not in the backward
direction.
In order to open in a scrollable mode the statement should be created with the following parameters.
ResultSetType :
1. ResultSet.TYPE_FORWARD_ONLY : The record pointer can be moved only in the forward direction.
( default )
2. ResultSet.TYPE_SCROLL_INSENSITIVE : The record pointer is scrollable, but the ResultSet doesn’t
effects for the new changes made by the other applications.
3. ResultSet.TYPE_SCROLL_SENSITIVE : The record pointer is scrollable, and also effects the ResultSet
also effects the client applications.
concurrencyType :
Moving the Cursor to a Designated Row : You can move the cursor to a particular row in a ResultSet
object. The methods first, last, beforeFirst, and afterLast move the cursor to the position their names indicate.
The method absolute will move the cursor to the row number indicated in the argument passed to it. If the
number is positive, the cursor moves the given number from the beginning, so calling absolute(1) puts the
cursor on the first row. If the number is negative, the cursor moves the given number from the end, so calling
absolute(-1) puts the cursor on the last row.
169 SATEESH N
SATEESH N
boolean next( ) : Moves the record pointer to the next record returns true on success and false on failure.
boolean previous( ) : Moves the record pointer to the prev record returns true on success and false on failure.
boolean first( ) : Moves the record pointer to the first record returns true on success and false on failure.
boolean last( ) : Moves the record pointer to the last record returns true on success and false on failure.
boolean absolute( ) : Moves the cursor to the given row number in this ResultSet object.
Ex: rs.absolute(4) ; // moves the cursor to the fourth row
boolean relative( ) : Moves the cursor a relative number of rows, either positive or negative.
Ex: rs.relative(-3);
Getting the Cursor Position : The method getRow lets you check the number of the row where the cursor
is currently positioned.
Note: Calling the method relative(1) is identical to calling the method next( ) and calling the method relative(-1)
is identical to calling the method previous( ).
Ex: int rowNum = rs.getRow( ); // rowNum should be 1
rs.relative(2);
int rowNum = rs.getRow( ); // rowNum should be 3
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class navigaterecords
{
public static void main(String args[])
{
MyFrame f = new MyFrame();
f.setBounds(100,100,400,300);
f.setTitle("Employee Details");
f.setVisible(true);
}
}
class MyFrame extends Frame implements ActionListener
{
TextField arr[] = new TextField[5];
int i,n;
Button b1,b2,b3,b4,b5;
Connection con;
Statement stmt;
ResultSet rs;
MyFrame()
{
170 SATEESH N
SATEESH N
setFont(new Font("Sanserif",Font.BOLD,14));
setLayout(new BorderLayout());
add(p1,BorderLayout.CENTER);
add(p2,BorderLayout.SOUTH);
b1 = new Button("First");
b2 = new Button("Previous");
b3 = new Button("Next");
b4 = new Button("Last");
b5 = new Button("Exit");
p2.setLayout(new GridLayout(1,5));
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p1.setLayout(new GridLayout(5,2));
for(i=0;i<5;i++)
{
p1.add(new Label(fieldNames[i]));
arr[i] = new TextField();
p1.add(arr[i]);
}
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
openConnection();
displayRecord(3); // display 1st record
}
171 SATEESH N
SATEESH N
void openConnection()
{
try
{
System.out.println("Getting Connection...");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("select empno,ename,job,sal,deptno from emp");
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
void closeConnection()
{
try
{
rs.close();
stmt.close();
con.close();
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
boolean b = false;
try
{
switch(opt)
{
case 1: b = rs.first(); break;
case 2: b = rs.previous(); break;
case 3: b = rs.next(); break;
case 4: b = rs.last(); break;
}
if(b == true)
{
for( i=0;i<5;i++)
{
arr[i].setText(rs.getString(i+1));
}
}
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}
172 SATEESH N
SATEESH N
The ResultSet.updateXXX methods generally take two parameters: the column to update and the new
value to put in that column. As with the ResultSet.getXXX methods, the parameter designating the column
may be either the column name or the column number. There is a different updateXXX method for updating
each data type (updateString, updateFloat, updateInt, and so on).
To make the update take effect in the database, we must call the ResultSet method
updateRow.Suppose that you realize that the update you made is incorrect. You can restore the previous
value by calling the cancelRowUpdates method if you call it before you have called the method updateRow.
Once you have called updateRow, the method cancelRowUpdates will no longer work.
rs.last( );
rs.updateFloat("SAL", 6000);
rs.cancelRowUpdates( );
rs.updateFloat("SAL", 6000);
rs.updateRow( );
Inserting a Row :
we can do the same thing without using any SQL commands by using ResultSet methods. After we
have a ResultSet object with results from the table “emp” , we can build the new row and then insert it into
both the result set and the table “emp” in one step. We build a new row in what is called the insert row, a
special row associated with every ResultSet object. This row is not actually part of the result set; think of it as a
separate buffer in which to compose a new row.
First step will be to move the cursor to the insert row, which you do by invoking the method
moveToInsertRow . The next step is to set a value for each column in the row. By calling the appropriate
updateXXX method for each value. Finally, we call the method insertRow to insert the row you have just
populated with values into the result set.
173 SATEESH N
SATEESH N
Ex:
rs = stmt.executeQuery("select empno,ename,job,sal,deptno from emp");
rs.moveToInsertRow( ); rs.moveToInsertRow( );
rs.updateInt("EMPNO", 111); rs.updateInt(1,111);
rs.updateString("ENAME", “Sateesh”); [ OR ] rs.updateString(2, “Sateesh”);
rs.updateString("JOB", “Analyst”); rs.updateString(3, “Analyst”);
rs.updateFloat("SAL",7500); rs.updateFloat(4,7500);
rs.updateInt("DEPTNO", 20); rs.updateInt(5, 20);
rs.insertRow( ); rs.insertRow( );
boolean moveToCurrentRow( ) : When you call the method moveToInsertRow, the result set keeps track of
which row the cursor is sitting on, which is, by definition, the current row. As a consequence,The method
moveToCurrentRow, which you can invoke only when the cursor is on the insert row, moves the cursor from the
insert row back to the row that was previously the current row.
Deleting a Row :
Deleting a row is the third way to modify a ResultSet object, and it is the simplest. All we do is
move the cursor to the row we want to delete and then call the method deleteRow . For example, if we
want to delete the fourth row in the ResultSet rs , our code will look like this:
The fourth row has been removed from uprs and also from the database.
Seeing Changes in Result Sets : Result sets vary greatly in their ability to reflect changes made in
their underlying data. If you modify data in a ResultSet object, the change will always be visible if you close it
and then reopen it during a transaction. In other words, if you re-execute the same query after changes have
been made, you will produce a new result set based on the new data in the target table. This new result set
will naturally reflect changes you made earlier. You will also see changes made by others when you reopen a
result set if your transaction isolation level makes them visible.
With a ResultSet object that is TYPE_SCROLL_SENSITIVE, you can always see visible updates
made to existing column values. You may see inserted and deleted rows, but the only way to be sure is to use
DatabaseMetaData methods that return this information.
You can, to some extent, regulate what changes are visible by raising or lowering the transaction
isolation level for your connection with the database. For example, the following line of code, where con is an
active Connection object, sets the connection's isolation level to TRANSACTION_READ_COMMITTED:
Ex: con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
With this isolation level, a TYPE_SCROLL_SENSITIVE result set will not show any changes before
they are committed, but it can show changes that may have other consistency problems. To allow fewer data
inconsistencies, you could raise the transaction isolation level to TRANSACTION_REPEATABLE_READ. The
problem is that, in most cases, the higher the isolation level, the poorer the performance is likely to be. And, as
is always true of JDBC drivers, you are limited to the levels your driver actually provides. Many programmers
find that the best choice is generally to use their database's default transaction isolation level. You can get the
default with the following line of code, where con is a newly-created connection:
Getting the Most Recent Data : Another new feature in the JDBC 2.0 API is the ability to get the most
recent data. You can do this using the method refreshRow, which gets the latest values for a row straight from
the database. Note that the result set should be sensitive; if you use the method refreshRow with a resultSet
object that is TYPE_SCROLL_INSENSITIVE, refreshRow does nothing.
Ex: rs.refreshRow();
// to accept emp details and insert them into the emp table
import java.io.*;
import java.sql.*;
class insertrecord
{
public static void main(String args[])
{
try
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Getting Connection....");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
Statement stmt = con.createStatement();
double sal;
try
{
// Read data from keyboard
System.out.println("Emp No: ");
int empno = Integer.parseInt(stdin.readLine());
System.out.println("Emp Name: ");
String ename = stdin.readLine();
System.out.println("Job: ");
String job = stdin.readLine();
System.out.println("Basic Sal: ");
sal = Double.parseDouble(stdin.readLine());
System.out.println("Dept No: ");
int deptno = Integer.parseInt(stdin.readLine());
if(n==1)
System.out.println("Record Saved");
else
System.out.println("Record not Saved");
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
stmt.close();
con.close();
}
175 SATEESH N
SATEESH N
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}
PreparedStatement : The PreparedStatement takes a query and compiles the query without executing it
we can set the values in the query by specifying the parameters and we can execute it any number of times.
import java.io.*;
import java.sql.*;
class prepstmt
{
public static void main(String args[])
{
try
{
System.out.println();
ps.setInt(1,empno);
ps.setString(2,ename);
ps.setString(3,job);
ps.setDouble(4,sal);
ps.setInt(5,deptno);
int n = ps.executeUpdate();
176 SATEESH N
SATEESH N
if(n==1)
System.out.println("Record saved");
else
System.out.println("Record not saved");
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
if(str.startsWith("N"))
break;
}
ps.close();
con.close();
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}
You can often make coding easier by using a for loop or a while loop to set values for input
parameters.
The code fragment that follows demonstrates using a for loop to set values for parameters in
the PreparedStatement object ps . The arrays, empnos holds the employee numbers, enames holds
the employees names , jobs holds the designations of employees, sals holds the employees salaries
and deptnos holds the departments numbers.
PreparedStatement ps;
String query = "update emp set sal = ? where empno = ?";
ps = con.prepareStatement(query);
int [ ] empnos = {7839, 7844,7876,7900,7902};
Double [ ] sals = {new Double(500), new Double(1000), new Double(1500),
new Double(2000), new Double(2500)};
int len = empnos.length;
for(int i = 0; i < len; i++)
{
ps.setDouble(1, sals[i].doubleValue( ));
ps.setInt(2, empnos[i]);
ps.executeUpdate();
}
177 SATEESH N
SATEESH N
CallableStatement : The CallableStatement is used for calling stored procedures of the database, such as
procedures and functions.
1. w.a function in oracle which takes quantity and rate and returns the amount.
2. w.a.p which accepts quantity and rate from the key board and sends them to oracle and receives the net
amount and displays it on the console.
return tnet;
end;
// to call the function of oracle and get net amount returned by oracle function
import java.io.*;
import java.sql.*;
class calstmt
{
public static void main(String args[])
{
try
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Getting Connection...");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
double rate,net;
while(true)
{
try
{
System.out.println( );
178 SATEESH N
SATEESH N
CallableStatement cs = con.prepareCall("{? = call getnetamt(?,?)}");
cs.registerOutParameter(1,Types.DOUBLE);
cs.setInt(2,qty);
cs.setDouble(3,rate);
ex.printStackTrace();
}
if(str.startsWith("N"))
break;
}
con.close();
System.out.println("Connection closed....");
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}
ExecuteBatch( ) :
A batch update is a set of multiple update statements that is submitted to the database for processing
as a batch. Sending batch updates can, in some situations, be much more efficient than sending update
statements separately.
The list, which is associated with a Statement object at its creation, is initially empty. You can add SQL
commands to this list with the method addBatch and empty it with the method clearBatch. When you have
finished adding statements to the list, you call the method executeBatch to send them all to the database to be
executed as a unit, or batch.
179 SATEESH N
SATEESH N
// File name: batchupdate.java
import java.sql.*;
class batchupdate
{
public static void main(String args[])throws Exception
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
try
{
int[] updCnt = stmt.executeBatch( );
}
catch(Exception ex)
{
ex.printStackTrace();
}
dbCon.commit( );
stmt.close();
dbCon.close();
}
catch (BatchUpdateException be)
{
//handle batch update exception
}
}
Commit :
RollBack :
SavePoint :
Blob
Clob
ConnectionPooling:
RowSets:
180 SATEESH N
SATEESH N
Swing : When we design a Java program we are able to run the program on different platforms without
recompilation. If the program is based on graphical interface then the components of the program such as
buttons, checkboxes etc., will be created according to the underline operating systems, these components are
known as heavy weight components. Because the components will be created from the operating system. As
a result the look and feel of the program may change from one platform to another platform.
Swing is an enhancement for the AWT which provides the same look and feel even when we run the
program on multiple platforms.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Container c = getContentPane( );
c.add(b1);
c.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
181 SATEESH N
SATEESH N
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
MyFrame( )
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
catch(Exception ex)
{
System.out.println("Cannot change the interface");
}
c = getContentPane();
c.setLayout(new FlowLayout()); E:\adv\swings>javac frametest.java
c.add(t1);
c.add(b1);
c.add(b2);
c.add(t2);
c.add(cb1);
c.add(courses);
182 SATEESH N
SATEESH N
b1.addActionListener(this);
b2.addActionListener(this); E:\adv\swings>javac frametest.java
E:\adv\swings>java frametest
t1.addActionListener(this);
t2.addActionListener(this);
cb1.addItemListener(this);
courses.addItem("C Language");
courses.addItem("Visual Basic");
courses.addItem("Developer 2000");
}
UIManager.setLookAndFeel( “ com.sun.java.swing.plaf.windows.WindowsLookAndFeel “ );
UIManager.setLookAndFeel( “ com.sun.java.swing.plaf.motif.MotifLookAndFeel “ );
183 SATEESH N
SATEESH N
vsp :
hsp :
The TreeNode is an interface that can contain text and subnodes also. To create a node the following
class can be used.
DefaultMutableTreeNode :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
DefaultMutableTreeNode root,lang,pack;
treetest1()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch(Exception ex)
{
System.out.println("Cannot change the interface");
}
184 SATEESH N
SATEESH N
lang.add(new DefaultMutableTreeNode("C language"));
lang.add(new DefaultMutableTreeNode("C ++"));
lang.add(new DefaultMutableTreeNode("Java"));
pack.add(new DefaultMutableTreeNode("Visual Basic"));
pack.add(new DefaultMutableTreeNode("Power Builder"));
pack.add(new DefaultMutableTreeNode("Developer 2000"));
tree = new JTree(root);
jsp = new JScrollPane(tree,vsp,hsp);
getContentPane().add(jsp);
}
class emptree
{
public static void main(String args[])
{
MyFrame f = new MyFrame();
f.setBounds(100,100,400,500);
f.setVisible(true);
}
}
MyFrame()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch(Exception ex)
{
System.out.println("Cannot change the interface");
}
185 SATEESH N
SATEESH N
c = getContentPane();
createNodes();
c.add(jsp);
}
void createNodes()
{
try
{
System.out.println("Getting Connection....");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select empno,ename,job,sal,deptno from emp");
while(rs.next())
{
int empno = rs.getInt(1);
String ename = rs.getString(2);
String job = rs.getString(3);
double sal = rs.getDouble(4);
int deptno = rs.getInt(5);
root.add(empNode);
}
rs.close();
stmt.close();
con.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Error in getting data");
}
}
}
186 SATEESH N
SATEESH N
JOptionPane : This class is providing the following functions which are generally used for displaying taking
input etc.,
static void showMessageDialog( Component parent, String msg ) : It displays the message in a separate
window, like msgbox in VB.
static String showInputDialog( objecgt message ) : Accepts input from the user in a dialog box and returns that
text.
// File name: ipdialogandmsgbox.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ipdialogand extends JFrame implements ActionListener
{
JButton b1;
ipdialogbox()
{
changeLookAndFeel();
b1 = new JButton("Show Dialog");
Container c = getContentPane();
c.setFont(new Font("Sanserif",Font.BOLD,14));
c.setLayout(new FlowLayout());
c.add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
String msg = JOptionPane.showInputDialog("Enter a String: ");
if(msg == null)
JOptionPane.showMessageDialog(null,"Invalid Data");
else
JOptionPane.showMessageDialog(null,"Data: "+msg);
}
}
public static void main(String args[])
{
Frame f = new ipdialogbox();
f.setBounds(50,50,300,200);
f.setVisible(true);
}
void changeLookAndFeel()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch(Exception ex)
{
System.out.println("Cannot change the Interface");
}
}
}
187 SATEESH N
SATEESH N
JTable : JTable is used for displaying the information in rows and columns.
JTable( Vector rowData, Vector heads ) : The “heads” contains the headings of the JTable. “RowData” is a
collection of vectors, where each such vector contains one record data.
Vector : Vector is an utility class which works similar to a linked list. We can add any number of objects to the
list, we can remove any object from the list.
Constructors :
void Remove( object obj ) : Removes the object from the list.
Object elementAt( int index ) : Returns the element at the specified index.
W.A.P to accept a query and display the selected records in a table format.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.Vector;
MyFrame()
{
l1 = new JLabel("Enter Query: ");
query = new JTextArea();
188 SATEESH N
SATEESH N
p1 = new JPanel();
b1 = new JButton("Execute Query");
b2 = new JButton("Exit Program");
c = getContentPane();
c.add(l1,BorderLayout.NORTH);
c.add(query,BorderLayout.CENTER);
query.setFont(new Font("SanSerif",Font.BOLD,14));
c.add(p1,BorderLayout.SOUTH);
p1.setLayout(new FlowLayout());
p1.add(b1);
p1.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
openConnection();
}
void openConnection()
{
try
{
System.out.println("Getting Connection .....");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
stmt = con.createStatement();
System.out.println("Ok");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Error: "+ex);
}
}
void closeConnection()
{
try
{
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
System.out.println("Connection closed....");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Error: "+ex);
}
}
void showData()
{
try
{
String str = query.getText().trim();
ResultSet rs = stmt.executeQuery(str);
ResultSetMetaData rsmd = rs.getMetaData();
int i,n;
n = rsmd.getColumnCount();
for(i=1;i<=n;i++)
{
heads.add(rsmd.getColumnLabel(i));
}
while(rs.next())
{
Vector curRow = new Vector();
for(i=1;i<=n;i++)
{
curRow.add(rs.getString(i));
}
rowData.add(curRow);
}
f.setBounds(50,50,600,300);
f.setTitle(str);
f.setVisible(true);
rs.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Cannot execute query");
}
}
}
c.add(jsp);
}
}
191 SATEESH N
SATEESH N
For many WEB applications server side processing is necessary. i.e., whenever a WEB Browser
sends the data to a WEB Server the WEB Server forwards the same to a program on the server which is
referred as ServerSideProgram. The ServerSideProgram receives the data from the WEB Server, process the
data and returns the output back to the WEB Server which will be given to the WEB Browser. The WEB
Browser receives the data and presents the data on the document. These ServerSidePrograms can be written
in any language such as C, C++, UNIX Shell programming, perl, Servlets etc., and the current technologies
the ServerSidePrograms are designed using ASP,JSP etc.,
WEB Browser
http://yahoo.com
checkmail
A WEB Browser after receiving the details from the user cab forward to the WEB Server in any of the
following 3 methods.
GET
POST
HEAD
A WEB Server after receiving the data from the WEB Browser should forward the same to the ssp in
the following 3 corresponding methods.
www.yahoo.com
GET Environment variables
user name :
password : POST Streams
WEB Server Server Side Program
Login HEAD Commandline args
URL Coding : Whenever a WEB Browser is required to send data to the WEB Server the WEB Browser
converts the data in a particualar format, which is known as URL coding. The server isde program receives the
converted data undos the conversion and process the data.
The following 4 rules will be used by the WEB Browsers for URL coding.
Ex: http://myserver.com/SSPname?Empno=101&Ename=abc+xyz&Job=clk%xxAcc
Creating a Servlet : To create a servlet create a class that extends the “HttpServlet” class and override
any or both of the following methods (i) doGet( ) (ii) doPost( )
If the WEB Browser sends the data in the “Get( ) “ method then “doGet( )” method of servlet will be
executed.
If the WEB Browser sends the data in the “Post” method then the “doPost( )” method of the servlet
will be execued.
If the WEB Browser doesnot specify any method, then the “doGet( )” will be executed.
Syntax :
The “request” object contains the data that was received from the WebBrowser and the “response”
allows us to send the output back to the WebBrowser.
While exchanging data between the WEB Browser and WEB Server the following 2 objects are used:
Request and Response.
tomcat
www.yahoo.com
Methods :
String getParameter(String paramname) : Returns the value of the specified parameter. It returns null if the
parameter is not available.
Cookie[ ] get Cookie( ) : Returns all the cookies that are received from the WebBrowser.
Methods :
PrintWriter getWriter( ) : Returns the output stream for sending the output to the WebBrowser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
194 SATEESH N
SATEESH N
// w.a.servlet to send employee details to the WebBrowser.
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class getempdetservlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body bgcolor=white text=black>");
out.println("<h2 style='background-color:green;color:yellow;text-align:center'> Exployee Details </h2>");
try
{
// getting data
// Class.forName("oracle.jdbc.driver.OracleDriver");
// Connection con = DriverManager.getConnection("jdbc:oracle:thin:@orasrv:1521:miracle","scott","tiger");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
HTML Forms : A HTML form is a collection of input fields such as text boxes, check boxes etc., HTML
forms are used for sending data from the WebBrowser to the WebServer. Each HTML form contains the
following.
Action : The name of the server side program for processing the data.
SUBMIT button : A special button which sends the accepted data to the WebServer.
// w.a.s which accepts employee details from WebBrowser (html) and sends them to the WebServer (ssp). The
servlet after receiving the data should echo the details back to the WebBrowser.
<!-- iptoservletoptowb.html-->
<html>
<body>
<h2> Enter Employee Details </h2>
<form name = EMPFORM method = GET action= 'http://localhost:8080/satclass/servlet/iptoservletoptowb'>
Employee Number <input type = text name=EMPNO size=15> <br> <br>
Employee Name <input type = text name=ENAME size=25><br> <br>
Employee JOb <input type = text name=JOB size=15>
<br>
<input type = SUBMIT value='Send Data'>
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String p1 = request.getParameter("EMPNO");
String p2 = request.getParameter("ENAME");
String p3 = request.getParameter("JOB");
196 SATEESH N
SATEESH N
out.println("<h2> received details </h2>");
out.println("<br>");
out.println("<h3> Employee Number: "+p1+"<br>");
out.println(" Employee Name : "+p2+"<br>");
out.println(" Employee JOB : "+p3+"</h3>");
out.println("</body></html>");
}
}
// w.a. html file which accepts an employee number and sends the employee number to the servlet. The
servlet should return the corresponding employee details back to the WebBrowser.
<!--findempservlet.html-->
<html>
<body>
<h2> Find Employee Details </h2>
<form name = EMPFORM method=GET action='http://localhost:8080/satclass/servlet/findempservlet'>
Enter Employee Number <input type=text name=EMPNO size=15>
<input type=submit value='Find Employee Record'>
</form>
</body>
</html>
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
ps.setInt(1,empno);
ResultSet rs = ps.executeQuery();
197 SATEESH N
SATEESH N
if(rs.next())
{
out.println(" <h2> RecordFound </h2> ");
out.println("<br> Employee Number: "+rs.getString(1));
out.println("<br> Employee Name: "+rs.getString(2));
out.println("<br> JOB: "+rs.getString(3));
out.println("<br> Salary: "+rs.getString(4));
out.println("<br> Department No: "+rs.getString(5));
}
else
{
out.println(" <h2> Record Not Found: "+empno+" </h2> ");
}
}
catch(Exception ex)
{
out.println("<br> Error: "+ex);
}
out.println(" <hr size=5 color=red> ");
out.println(" <a href = '/satclass/findempservlet.html'> Find Another </a>");
out.println("</body> </html>");
}
}
// w.a. html file which accepts employee details and sends them to the servlet. The servlet after receiving the
employee details should insert them into the database.
<!--saveempservlet.html-->
<html>
<body>
<h2 style=background-color:#0086b2;color:white;text-align:center>New Employee Record</h2>
Employee Number
<input type=text name=EMPNO size=15> <br> <br>
Employee Name
<input type=text name=ENAME size=25> <br> <br>
Employe Job
<input type=text name=JOB size=15> <br> <br>
Basic Salary
<input type=text name=SAL size=10> <br> <br>
Department Number
<input type=text name=DEPTNO size=5> <br> <br>
<input type=SUBMIT value='Save Details'>
</form>
</body>
</html>
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
198 SATEESH N
SATEESH N
try
{
// Receive the employee details
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
ps = con.prepareStatement("insert into emp(empno,ename,job,sal,deptno) values(?,?,?,?,?)");
ps.setInt(1,empno);
ps.setString(2,ename);
ps.setString(3,job);
ps.setDouble(4,sal);
ps.setInt(5,deptno);
int n = ps.executeUpdate();
if(n==1)
out.println("<h3> Record Saved </h3>");
else
out.println("<h3> Record Not Saved </h3>");
ps.close();
con.close();
}
catch(Exception ex)
{
out.println("<br> Error: "+ex);
}
out.println(" <hr size=5 color=red> ");
out.println(" <a href = '/satclass/saveempservlet.html'> Save Another </a>");
out.println("</body> </html>");
}
}
199 SATEESH N
SATEESH N
Session Management :
HTTP is a stateless protocol. i.e., whenever a WebBrowser sends a request to the WebBrowser, the
WebServer provides a response to the WebBrowser and closes the connection. i.e., the WebBrowser doesn’t
store any information of WebBrowser. Some times we want the server side program to identify what values are
given to the clients in the previous response.
Session management is concept which makes a server side program to identify what values are given
to the clients in the previous response.
1. Hidden Variables
2. Cookies
3. Sessions
Hidden Variables : A Hidden Variable is a input field in a form which contains a value and which will not be
displayed on the document. Whenever the user clicks on the submit button the value of the hidden variable will
also be submitted along with the other input fields.
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
int rno = 0;
if(RNO!=null)
{
rno = Integer.parseInt(RNO);
}
rno++;
try
{
// send the employee record
openConnection();
200 SATEESH N
SATEESH N
// PreparedStatement ps = con.prepareStatement("select empno,ename,job,sal,deptno from employee
where empno = ?");
ps.setInt(1,rno);
ResultSet rs = ps.executeQuery();
if( rs.next() )
{
out.println(" <h3> Record Found: " +rno+ "</h3> ");
}
else
{
out.println(" <h3> Record Not Found: " +rno+ "</h3> ");
}
rs.close();
ps.close();
}
catch(Exception ex)
{
out.println(" <br> Error: "+ex);
}
Cookies : A cookie is a piece of information created by the server and will be given to the clients
WebBrowser. The WebBrowser receives the cookie and it will not be displayed on the document. The
WebBrowser stores the cookie in a separate memory area. Whenever the WebBrowser connects to the
WebServer all the cookies of that WebServer will be given from the WebBrowser to the WebServer. As a
result the server side program can retrieve any values stored into cookie.
A WebBrowser generally stores upto 20 cookies for each WebServer. A cookie contains the name and
value. In java cookies are managed using the cookie class. Each cookie contains a name and value.
Creating a Cookie : In java cookies are managed using the cookie class each contains a name, value,
expire date and time etc.,
String getValue( ) :
HttpServletResponse :
void addCookie(Cookie ck) : Sends a cookie to the WebBrowser. If a cookie with the same name is already
existing on the WebBrowser it will bhe replaced by the latest value.
HttpServletRequest :
Cookie[ ] getCookies( ) : Returns all the cookies that are received from the WebBrowser.
// File name: nextempservlet2.java
// using cookies
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
202 SATEESH N
SATEESH N
PrintWriter out = response.getWriter();
int rno = 0;
if(arr!=null)
{
for(int i=0;i<arr.length;i++)
{
if(arr[i].getName().equals("RNO"))
{
rno = Integer.parseInt(arr[i].getValue());
break;
}
}
}
rno++;
sendRecord(rno,out);
response.addCookie(ck);
ps.setInt(1,rno);
ResultSet rs = ps.executeQuery();
203 SATEESH N
SATEESH N
if( rs.next() )
{
out.println(" <h3> Record Found: " +rno+ "</h3> ");
}
else
{
out.println(" <h3> Record Not Found: " +rno+ "</h3> ");
}
rs.close();
ps.close();
}
catch(Exception ex)
{
out.println(" <br> Error: "+ex);
}
}
}
204 SATEESH N
SATEESH N
JSP is an enhancement for the servlets, which allows us to place java statements in HTML documents.
Whenever a jsp document is requested for the first time, the document will be converted into a servlet
and it will be compiled, executed. For the remaining requests the compiled version will be executed.
All the java statements in a jsp document must be given between the following tags.
<%
%>
<!--test.jsp-->
<html>
<head>
<title>
Test Program in JSP
</title>
</head>
<body>
<h2>
Sample JSP Program
</h2>
<%
out.println(" <h3> First JSP Program </h3> ");
int a = 10;
int b = 20;
int c = a+b;
<hr>
Total is: <%= c %>
<hr>
Employee Number: <%= empno %> <br>
Employee Name : <%= ename %> <br>
</body>
</html>
out : PrintWriter
request : HttpServletRequest
response : HttpServletResponse
205 SATEESH N
SATEESH N
session : HttpSession
page : this
application : ServletContext
in : BufferedReader
<html>
<head>
<title>
Employee Details
</title>
</head>
<body>
<h2 style='background-color:blue; color:white; text-align:center'>
Employee Details
</h2>
<%
try
{
System.out.println("Getting Connection.....");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select empno,ename,job,sal,deptno from emp");
%>
<%
while(rs.next())
{
%>
<tr>
<td> <%=rs.getString(1) %> </td>
<td> <%=rs.getString(2) %> </td>
<td> <%=rs.getString(3) %> </td>
<td> <%=rs.getString(4) %> </td>
<td> <%=rs.getString(5) %> </td>
</tr>
<%
}
out.println("</table>");
rs.close();
stmt.close();
}
206 SATEESH N
SATEESH N
catch(Exception ex)
{
out.println("<br> Error: "+ex);
}
%>
</body>
</html>
// w.a. html file to send the employee details from WebBrowser to jsp program, after receiving employee
details the jsp program send back the details to the WebBrowser.
<!-- empecho.html-->
<html>
<body>
<h2> Enter Employee Details </h2>
<form name = EMPFORM method=GET action='empecho.jsp'>
Employee Number <input type=text name=empno size=10> <br><br>
Employee Name <input type=text name=ename size=20> <br><br>
Employee Job <input type=text name=job size=10> <br><br>
Employee Salary <input type=text name=sal size=10> <br><br>
Department No <input type=text name=deptno size=10> <br><br>
<input type=SUBMIT value='Send Data'> <br><br>
</form>
</body>
</html>
207 SATEESH N
SATEESH N
// w.a. html file to accept an employee number and send that number to the jsp program, the jsp program
receives the employee number and send the corresponding employee details back to WebBrowser.
<!--findemp.html-->
<html>
<body>
<h2> Find Employee Details </h2>
<form name = EMPFORM method=GET action='http://localhost:8080/satclass/findemp.jsp'>
Enter Employee Number <input type=text name=EMPNO size=15>
<input type=submit value='Find Employee Record'>
</form>
</body>
</html>
Error Page : The error page directive can be given in any “ jsp “ programs, which takes a jsp document
name.
Whenever an error occurs in the “ jsp “ program the control will be transferred to the specified error
page.
<html>
<body>
<h2 style='background-color:blue;color:white;text-align:center'>
Servlet Beans :
A bean is a java class, which is a reusable component. Once a bean is created it can be used in any
number of programs.
In servlets and jsp’s all the beans must be created in the driveletter:\tomcat\webapps\virtual directory
name\WEB-INF\classes sub directory.
To use a bean in a jsp program the “jsp: useBean” directory should be applied.
employee emp;
emp = new employee();
Application : For all the clients only one instance of the bean will be created and the bean will be created on
the server.
209 SATEESH N
SATEESH N
Page : Request :
Bean ex2.jsp ex2.jsp
Bean
server server
In page and Request whenever user connects, the new bean is created, the old bean will be
destroyed. When the connection is braked.
Application : Session :
Bean
Bean ex1.jsp ex1.jsp
Bean
server server
In application if all the users are connecting to In session for each user a separate bean is
the same jsp program all are connected to one created.
bean only.
package mycon;
import java.sql.*;
public ConnectionException()
{
msg = "Connection Exception occurred";
}
210 SATEESH N
SATEESH N
public ConnectionException(String msg)
{
this.msg = msg;
}
package mycon;
import java.sql.*;
public mycon()
{
con = null;
}
cont…
catch(Exception e)
{
%>
<%=e %>
<%
}
%>
<table width=100% bgcolor=cyan border=2 bordercolor=blue cellspacing=0>
<tr>
<th>Employee Number</th> <th>Employee Name</th> <th>Employee Job</th> <th>Basic
Salary</th><th>Department No.</th>
</tr>
<%
if(rs!=null)
{
while(rs.next())
{
%>
<tr>
<td> <%=rs.getString(1) %> </td>
<td> <%=rs.getString(2) %> </td>
<td> <%=rs.getString(3) %> </td>
<td> <%=rs.getString(4) %> </td>
<td> <%=rs.getString(5) %> </td>
212 SATEESH N
SATEESH N
</tr>
<%
} // end of while
out.println("</table>");
rs.close();
stmt.close();
}
%>
</body>
</html>
DiplayAllEmployees.jsp should display all the employee records in a table format. Whenever the user
click on any employee number the selected employee number should be forwarded to the DisplaySelected
Employee.jsp which should open the selected record for editing. After the user modifies the employee record
the last program UpdateEmployee.jsp should update the data in the datbase.
<!-- DiplayAllEmployees.jsp-->
cont…
<html>
<body link=blue vlink=pink alink=red>
<h2 style='background-color:blue;color:white;text-align:center'>
Employee Details
</h2>
<%
Statement stmt = null;
ResultSet rs = null;
try
{
stmt = con.createStatement();
rs = stmt.executeQuery("select empno,ename,job,sal,deptno from emp");
}
catch(Exception ex)
{
%>
<%=ex %>
<%
}
%>
<table width=100% bgcolor=cyan border=2 bordercolor=blue>
<tr>
<th> EmpNo </th>
<th> Employee Name</th>
<th> Job </th>
<th> Salary </th>
213 SATEESH N
SATEESH N
<th> DeptNo </th>
</tr>
<%
if(rs!=null)
{
while(rs.next())
{
int empno = rs.getInt(1);
%>
<tr>
<td align=center>
<a href='DisplaySelectedEmployee.jsp?EmpNo=<%=empno%>'>
<%=empno %>
</a>
</td>
<td> <%=rs.getString(2) %> </td>
<td> <%=rs.getString(3) %> </td>
<td> <%=rs.getString(4) %> </td>
<td> <%=rs.getString(5) %> </td>
</tr>
<%
} // end of while
out.println("</table>");
rs.close();
stmt.close();
} // end of if
%>
</body>
</html>
<html>
<body link=blue vlink=green alink=red>
<h2 style='background-color:blue;color:white;text-align:center'>
SelectedEmployee Details
</h2>
<%
int empno = Integer.parseInt(request.getParameter("EmpNo"));
ResultSet rs = null;
PreparedStatement ps =null;
try
{
ps = con.prepareStatement("select empno,ename,job,sal,deptno from emp where empno=?");
ps.setInt(1,empno);
rs = ps.executeQuery();
}
catch(Exception e)
{
%>
<%=e%>
<%
}
214 SATEESH N
SATEESH N
if(rs.next())
{
%>
<form name=EMPFORM method = GET action='UpdateEmployee.jsp'>
<table width=75% bgcolor=cyan border=0 align=center>
<tr>
<td> Employee Number </td>
<td>
<input type = text name=EMPNO size=15 value='<%=rs.getString(1) %>'READONLY>
</td>
<tr>
<tr>
<td> Employee Name </td>
<td>
<input type = text name=ENAME size=15 value='<%=rs.getString(2) %>'READONLY>
</td>
<tr>
<tr>
<td> Employee Job </td>
<td>
<input type = text name=JOB size=15 value='<%=rs.getString(3) %>'>
</td>
<tr>
<tr>
<td> Employee Salary </td>
<td>
<input type = text name=SAL size=15 value='<%=rs.getString(4) %>'>
</td>
<tr>
<tr>
<td> Employee DepartmentNumber </td>
<td>
<input type = text name=DEPTNO size=5 value='<%=rs.getString(5) %>'>
</td>
<tr>
<tr>
<td colspan=2 align=center>
<input type = submit value='UPDATE RECORD'>
<input type = reset value='RESET'>
</td>
</tr>
</table>
</form>
<%
} // end of if
else
{
out.println("<h2> Record Not Found ! </h2>");
}
rs.close();
ps.close();
%>
<hr size=5 color = red>
<a href='DisplayAllEmployees.jsp'> All Employee Details </a>
</body>
</html>
215 SATEESH N
SATEESH N
if(rs.next())
{
%>
<form name=UPDATEFORM method = GET action='DisplayAllEmployee.jsp'>
<table width=75% bgcolor=cyan border=0 align=center>
<tr>
<td> Employee Number </td>
<td>
<input type = text name=EMPNO size=15 value='<%=rs.getInt(1) %>'READONLY>
</td>
<tr>
<tr>
<td> Employee Name </td>
<td>
<input type = text name=ENAME size=15 value='<%=rs.getString(2) %>'READONLY>
</td>
<tr>
216 SATEESH N
SATEESH N
<tr>
<td> Employee Job </td>
<td>
<input type = text name=JOB size=15 value='<%=rs.getString(3) %>'READONLY>
</td>
<tr>
<tr>
<td> Employee Salary </td>
<td>
<input type = text name=SAL size=15 value='<%=rs.getFloat(4) %>'READONLY>
</td>
<tr>
<tr>
<td> Employee DepartmentNumber </td>
<td>
<input type = text name=DEPTNO size=5 value='<%=rs.getInt(5) %>'READONLY>
</td>
<tr>
</table>
</form>
<%
} // end of if
else
{
out.println("<h2> Record Not Found ! </h2>");
}
rs.close();
ps.close();
%>
Sessions : A session is a piece of memory allocated by the WebServer for each WebBrowser. The server
side program can store any value in that WebBrowser’s session. Each session contains a unique id & such
unique-id is given to the WebBrowser. The WebBrowser stores the session-id in the form of a cookie and
whenever the WebBrowser connects to the same WebServer, the WebBrowser sends the session-id to the
WebServer. As a result, the server side program receives the session-id and is able to open the session of the
corresponding WebBrowser.
In a jsp program the current session can be accessed using the session Object.
HttpSession :
Methods :
ResultSet rs=null;
PreparedStatement ps=null;
try
{
ps = con.prepareStatement("select empno,ename,job,sal,deptno from emp where empno=?");
ps.setInt(1,rno);
rs= ps.executeQuery();
%>
<%=rno%>
<%
}
catch(Exception e)
{
%>
<%=e%>
<%
}
%>
<table width=100% bgcolor=cyan border=2 bordercolor=blue cellspacing=0>
<%
if(rs.next())
{
%>
<tr>
<td> Employee Number </td>
<td> <%=rs.getString(1) %> </td>
</tr>
<tr>
<td> Employee Name </td>
<td> <%=rs.getString(2) %> </td>
</tr>
218 SATEESH N
SATEESH N
<tr>
<td> Employee Job </td>
<td> <%=rs.getString(3) %> </td>
</tr>
<tr>
<td> Employee Salary </td>
<td> <%=rs.getString(4) %> </td>
</tr>
<tr>
<td> Department Number </td>
<td> <%=rs.getString(5) %> </td>
</tr>
</table>
<%
} // end of if
else
{
<html>
<body>
<h2 style='background-color:blue;color:white;text-align:center'>
Employee Records
</h2>
<%
int rno = 0;
String RNO = (String)session.getAttribute("RNO");
if(RNO != null)
{
rno = Integer.parseInt(RNO);
}
int opt = 0;
String OPT = request.getParameter("OPT");
if(OPT != null)
{
opt = Integer.parseInt(OPT);
219 SATEESH N
SATEESH N
switch(opt)
{
case 1: rno=1; break;
case 2: rno--; if(rno==0) rno=1; break;
case 4: rno=14; break;
case 3:
default: rno++; if(rno==15) rno=14; break;
}
}
else
{
rno++; // to start from 1st record
}
<tr>
<td> Employee Name </td>
<td> <%=rs.getString(2) %> </td>
</tr>
<tr>
<td> Employee Job </td>
<td> <%=rs.getString(3) %> </td>
</tr>
<tr>
<td> Employee Salary </td>
<td> <%=rs.getString(4) %> </td>
</tr>
220 SATEESH N
SATEESH N
<tr>
<td> Department Number </td>
<td> <%=rs.getString(5) %> </td>
</tr>
</table>
<%
} // end of if
else
{
out.println("<h3> Record Not Found !</h3>");
}
rs.close();
ps.close();
%>
<hr size=5 color=red>
<a href='NavigateRecords.jsp?OPT=1'>FIRST</a>
<a href='NavigateRecords.jsp?OPT=3'>NEXT</a>
<a href='NavigateRecords.jsp?OPT=2'>PREVIOUS</a>
<a href='NavigateRecords.jsp?OPT=4'>LAST</a>
</body>
</html>
1. UserData.java
2. GetData.jsp
3. SaveName.jsp
4. NextPage.jsp
package mycon;
<html>
<body>
<form method=post action="SaveName.jsp">
What's your name? <input type=text name=username size=20> <br>
What's your e-mail address? <input type=text name=email size=20><br>
What's your age? <input type=text name=age size=4>
<p><input type=SUBMIT> </p>
</form>
</body>
</html>
222 SATEESH N
SATEESH N
JSP Standard Tag Library ( JSTL )
JSTL is an enhancement of JSP which allows us to place custom tags into the jsp programs. JSTL is a
collection of predefined tages which can be placed into the JSP programs. The JSTL should be downloaded
separately in a compressed format. After uncompressing we can find the following types of files.
*.tld
*.jar
*.class
After downloading the tld file and the jar files place all the tld files in the satclass\WEB-INF sub
directory. Place all the jar files in the lib sub directory.
The tld file contains the names of the tags and their params that can be applied in JSP programs.
Whenever a custom tag was used in a jsp program the corresponding tag class will be called from the
jar file.
The tld file is text file which contains the tag name and that params. The tld should be imported into
the required jsp programs before using them for each such import a prefix is also require.
Using a custom tag : In order to use a custom tag the tld file should be imported to jsp program. A
prefix is also required.
out : Takes a value and sends the value to the WEB Browser. This is equal to the out.println.
EL (Expression Language) : EL is a new technology which can be embedded within jsp programs to execute
the given expressions. All the expressions must be given within a block prefix with a ${ } .
param : The param object contains all the parameters in the request object.
223 SATEESH N
SATEESH N
Creating a variable : To create a variable the SET will be used.
Choose : For checking more than one condition. Along with the choose we should also apply the when.
Syntax: <c:choice>
<c:when test=”${condition1}”
// statemnt(s);
</c:when>
----
----
----
<c:otherwise>
// statement(s);
</c:otherwise>
</c:choose>
for :
catch : Executes statement in a try block. If any exception occurs it will be stored in a given variable.
<html>
<body>
<h2> sample program on JSP Tag Library </h2>
<c:out value="sateesh">
</c:out>
<br>
<c:out value="testing"/>
</c:out>
</body>
</html>
224 SATEESH N
SATEESH N
<html>
<body>
<h2> sample program on JSP Tag Library </h2>
<c:out value="sateesh">
</c:out>
<br>
Total is:<c:out value="${10+20}"/>
</body>
</html>
<html>
<body>
<h2> Enter Employee Details </h2>
<form name = EMPFORM method=GET action='http://localhost:8080/satclass/jstlc3.jsp'>
Employee Number <input type=text name=empno size=10> <br><br>
Employee Name <input type=text name=ename size=20> <br><br>
Employee Job <input type=text name=job size=10> <br><br>
Employee Salary <input type=text name=sal size=10> <br><br>
Department No <input type=text name=deptno size=10> <br><br>
<input type=SUBMIT value='Send Data'> <br><br>
</form>
</body>
</html>
<html>
<body>
225 SATEESH N
SATEESH N
<!-- jstlc4.jsp -->
<%@ taglib uri='/WEB-INF/tlds/c.tld' prefix="c" %>
<html>
</body>
<h2> Testing " for " statement in JSTL </h2>
<c:forEach var="i" begin="10" end="100" step="10">
<br> Value is: <c:out value="${i}"/>
</c:forEach>
</body>
</html>
<html>
</body>
<c:set var="start" value="10" />
<c:set var="end" value="100" />
<c:forEach var="i" begin="${start}" end="${end}" step="10">
<br>
value is: <c:out value="${i}" />
</c:forEach>
</body>
</html>
<html>
<body>
<c:set var="start" value="1" />
<c:set var="end" value="20" />
Even no's between 1 to 20:
<c:forEach var="i" begin="${start}" end="${end}" step="1">
<br>
<c:if test="${i%2==0}">
<c:out value="${i}"/>
</c:if>
</c:forEach>
</body>
</html>
<!-- jstlc7.jsp -->
<html>
<body>
<c:choose>
<c:when test="${ch==1}">
<c:out value="one"/>
</c:when>
<c:when test="${ch==2}">
<c:out value="two"/>
</c:when>
226 SATEESH N
SATEESH N
<c:when test="${ch==3}">
<c:out value="three"/>
</c:when>
<c:when test="${ch==5}">
<c:out value="five"/>
</c:when>
<c:when test="${ch==4}">
<c:out value="four"/>
</c:when>
<c:otherwise>
<c:out value="chosen number<1 or >5"/>
</c:otherwise>
</c:choose>
</body>
</html>
<html>
<head>
<title>Catch an Exception?</title>
</head>
<body>
<c:catch var="e">
10 divided by 0 is: <c:out value="${10/0}" /> <br />
</c:catch>
<c:if test="${e!=null}">
The caught exception is: <c:out value="${e}" /> <br />
sat it was caught
</c:if>
<c:if test="${e==null}">
No exception was thrown <br />
</c:if>
</body>
</html>
227 SATEESH N
SATEESH N
<html>
<body>
<h2> STUDENT DETAILS </h2>
<form name=STUDFORM method=POST action="http://localhost:8080/satclass/exjstl.jsp">
<input type=hidden name=OPT value=1>
<table width=100% bgcolor='#D5D5AA'border=0>
<tr>
<td>
Enter student Number
</td>
<td>
<input type=text name=sno size=15>
</td>
</tr>
<tr>
<td>
Enter student Name
</td>
<td>
<input type=text name=sname size=25>
</td>
</tr>
<tr>
<td>
Enter Total Fee
</td>
<td>
<input type=text name=tfee size=15>
</td>
</tr>
<tr>
<td colspan=2 align=right>
<input type=SUBMIT value='send data'>
</td>
</tr>
</table>
</form>
<h2> EMPLOYEE DETAILS </h2>
<form name=EMPFORM method=POST action='http://localhost:8080/satclass/exjstl.jsp'>
<input type=hidden name=OPT value=2>
<table width=100% bgcolor='#D5D5AA'border=0>
<tr>
<td>
Enter EMployee Number
</td>
<td>
<input type=text name=empno size=15>
</td>
</tr>
<tr>
<td>
Enter Employee Name
</td>
<td>
<input type=text name=ename size=25>
</td>
</tr>
228 SATEESH N
SATEESH N
<tr>
<td>
Enter Salary
</td>
<td>
<input type=text name=sal size=15>
</td>
</tr>
<tr>
<td colspan=2 align=right>
<input type=SUBMIT value='send data'>
</td>
</tr>
</table>
</form>
</body>
</html>
<html>
<c:if test="${param.OPT==1}">
<jsp:forward page='http://localhost:8080/satclass/studjstl.jsp'/>
</c:if>
<c:if test="${param.OPT==2}">
<jsp:forward page='http://localhost:8080/satclass/empjstl.jsp'/>
</c:if>
</html>
<html>
<body>
<h2> Received Student Details </h2>
Student Number:
<c:out value="${param.sno}" default="- - -" /> <br>
Student Name:
<c:out value="${param.sname}" default="- - -" /> <br>
Total Fee :
<c:out value="${param.tfee}" default="- - -" /> <br>
</body>
</html>
<html>
<body>
<h2> Received Employee Details </h2>
<form action="">
Employee Number:
229 SATEESH N
SATEESH N
<c:out value="${param.empno}" default="- - -" /> <br>
Employee Name:
<c:out value="${param.ename}" default="- - -" /> <br>
Salary :
<c:out value="${param.sal}" default="- - -" /> <br>
</form>
</body>
</html>
230 SATEESH N
SATEESH N
RMI
( Remote Method Invocation )
Distributed Programming
This feature of java allows an object running on one machine to call the methods of another object
which is running on another machine. For example object c on machine one can call method f1 of object s
which is on machine two. Object s is a remote object to object c . The methods of s will become as remote
methods to object c .
Inorder to make the RMI possible two special programs are used which are known as stub & skeleton.
C S
Stub Skeleton
NetWork
Whenever object c calls a method of object s object c actually calls a method of stub. The stub
will be loaded along with the object c receives the call works with Java & RMI systems and serializes the
call to the machine two. On the machine two the call will be received by skeleton which works with Java & RMI
system and calls the corresponding method of object s. Any returned value of such function will be given back
to object c on the same style.
1. Define the Remote Interface : The remote interface contains the signatures of all the remote methods that
a client application can call.
Create an interface that extends the Remote Interface and provide the signatures of all the remote
methods. All the remote methods should throw RemoteException.
3. Generate the stub and skeletons : Compile the implementation class using the rmi compiler rmic.
Ex: e:\adv\rmi> rmic accountimpl
accountimpl_stub class
accountimpl_skel class
Naming class : The naming class is containing the following methods used for binding the remote
object or for locating the remote object.
public static void bind( String name, Remote obj ) : Binds the remote object with the given name.
public static void unbind( String name) : Unbinds the remote object.
public static void rebind( String name, Remote obj ) : unbind + bind.
public static Remote lookup( String url ) : Locate the remote object & returns its reference.
4. Design the Server program : The server program should create an instance of the implementation class
and should bind with a suitable name.
232 SATEESH N
SATEESH N
5. The Client program : The client program locates the remote object with the binded name and is able to call
the remote methods. It can access the remote object using naming lookup.
Note : Before running the server program start the rmi registry.
E:\adv\rmi>start rmiregistry
rmiregistry works on portno. 1099 and provides communication between stub and skeletons.
[diagram from Qusay Mahmoud, Distributed Programming with Java, Manning, 2000]
These layers are independent of one another. Each implements its own interface and protocol. Each could be
replaced with other implementations without affecting the others.
233 SATEESH N
SATEESH N
Remote Reference Layer
This middle layer sets up connections to remote address spaces, manages connections, listens for incoming
calls, and various other purposes.
The RMI programmer does not see the transport and remote reference layers. The stubs and skeletons do
appear to the programmer. (One of the most annoying bugs in RMI programming is losing track of the stub!).
The stubs and skeletons are not written by the programmer. They are generated by a special compiler called
rmic.
Stubs and skeletons represent the interface between the RMI system and the application programs.
The stub is a proxy at the client side for a remote object. The skeleton represents information about the client
at the server side.
The client side stub representing a remote object does the following:
Arguments to a method are always "pass by value", as in C. That is, the method receives copies of the actual
parameters. However, in many cases, these arguments are references to objects. Objects are effectively "pass
by reference" because using the (copy) of the reference, you can change the public members of the actual
object. The object itself is not copied.
With RMI, even if the arguments for a remote method (on the server) are references to (local on the client)
objects, what arrives at the server are copies of the actual objects referered to, not the references to those
objects, as would be the case for a local call.
Therefore, changes made to the object on the remote server are not reflected by on the original object still
sitting on the client machine. The only way to get a change back from the remote method is via the return
value of the method.
The situation is more like it would be in a functional language such as Scheme or ML.
234 SATEESH N
SATEESH N
Serialization
Objects sent as arguments or returned as results across the network must be serializable. That is, they must
implement the Serializable interface.
A class that implements the Serializable interface need not implement any special methods (as, for example,
you must do if you implement, say, the Runnable interface). The serializable interface is just a marker, or flag.
Note that if a class is serializable, all its subclasses inherit this property. Many of the Java API provided classes
are already serializable so there is no need to declare any of their subclasses serializable. You can check in the
documentation.
However if you create your own class to be sent across the network, and it is only a subclass of, say, Object,
you must declare it as implementing the serializable interface.
Another problem can sometimes arise when you serialize your own object creations. All the objects from which
your object are composed must also be serializable, or your object cannot move down the net. ( References to
such non-serializable objects can be declared transient to avoid this problem.)
Marshaling
The term marshaling applies to the process of serializing. When a serialized object is to be sent across the
network, it is "marshaled". The object is converted into a byte stream for transmission. At the receiving end it
is "unmarshaled". The object is reconstructed in its structured form from the incoming byte stream. ("Beam
me up, Charlie" ins Star Trek.)
// Remote Interface
// In the following program three accounts are binded on the remote server.
// These accounts can be accessible from remote locations.
import java.rmi.*;
235 SATEESH N
SATEESH N
import java.rmi.*;
import java.rmi.server.*;
236 SATEESH N
SATEESH N
//server program,to place 3 accounts which can be accessible from Remote location
import java.rmi.*;
// creating 3 accounts
Naming.unbind("101");
Naming.unbind("102");
Naming.unbind("103");
System.exit(0);
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}
import java.rmi.*;
import java.io.*;
if(args.length >=1)
host = args[0];
int ch = 1;
while(ch!=5)
{
try
{
System.out.println("\nMENU");
System.out.println("1.Open \n2.Details \n3.Deposit \n4.Withdraw \n5.Exit\n");
D:\adv\rmi>java accountclient
System.out.print("Enter u r choice: ");
ch = Integer.parseInt(stdin.readLine()); // Accept choice MENU
1.Open
switch(ch) 2.Details
{ 3.Deposit
case 1: // opens the given account 4.Withdraw
System.out.print("Enter an Account Number to open: "); 5.Exit
int accno = Integer.parseInt(stdin.readLine());
String url = "rmi://"+host+"/"+accno; Enter u r choice: 1
System.out.println("Finding: "+url); Enter an account number to open: 1
r = (account)Naming.lookup(url); Finding: rmi://localhost/101
System.out.println("Account Found"); Account Found
case 5: break;
} // end of try
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
238 SATEESH N
SATEESH N
} // end of while
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
} // end of main
} // end of client
239 SATEESH N