Вы находитесь на странице: 1из 239

SATEESH N

INDEX

Introduction 3 JDBC 163


First Java Program 4 SWINGS 181
Data Types in Java 9 Servlets 192
Arrays 10 JSP 205
Class & Object 13 JSTL 223
Constructors 14 Java Beans
Static Variables & Static Functions 16 XML
Static Blocks 18 RMI 231
Garbaze Collection 19 EJB
Method Overloading 22 CORBA
Access Specifiers 23 Java Mail
Call by Value and Call by Reference 24 JMS
Inner Classes 29 Struts
Inheritance 34 JSF
Overridden Functions 37 JNDI
Abstract Functions and Abstract Classes 42 LDAP
Interfaces 47 Web Services
Packages 51 ANT
Object Class 53 Log4J
Exception Handling 59 JUnit
String Class 64
Input & Output Streams 68
Integer Class 94
Multi Threading 95
Synchronization 100
util package 105
Collections 113
APPLETS & AWT 127
:: Applets ::
Applet Class 128
Graphic Class 128
Sending Parameters to Applet 130
Drawing Images on the Applet 131
:: AWT ::
Placing Components on the Applet 132
Handling Components 134
Layout Management 142
Frames 150
Menus 156

2 SATEESH N
SATEESH N

INTRODUCTION

About the Java Technology :

Java technology is both a n O b j e c t O r i e nt e d programming language and a platform u se d


f o r d ev el o pi n g a p p l i c a t i o n s f o r t h e i n t e r n et .

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,

Differe between Application and Applet :


This question can be answered on many levels. Technically an application is a Java class that has a
main() method. An applet is a Java class which extends java.applet.Applet. A class which extends
java.applet.Applet and also has a main() method is both an application and an applet.

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

// it displays the text ‘First Java Program’ . Out put:

class First E:\Core>javac First.java


{
public static void main(String args[]) E:\Core>java First
{ First Java Program
System.out.println("First Java Program");
E:\Core>
}
}

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.

Java Virtual Machine :

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

The Java Platform

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)

You've already been introduced to the Java VM. It's


the base for the Java platform and is ported onto various
hardware-based platforms.

Java APIs are libraries of compiled code that you


can use in your programs. They let you add ready-made
Your Computer System and customizable functionality to save you programming
time. The Java API is grouped into libraries of related
classes and interfaces; these libraries are known as
packages.

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)

Increment & Decrement Operators : ++ and --


Post-increment and Post-decrement
Pre-increment and Pre-decrement

Logical Operators : Logical AND Logical OR Logical NOT


&& || !

Boolean Operators : Boolean AND Boolean OR Boolean NOT


& | ^

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
~ & | ^ << >> >>>

Class and Object Operators :


Class Test Operator Class Instantiation Class Member Access method invocation
instanceOf new . (dot) ()

Object Cast String Concatenation Array Element Access


(X) + []

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

public class Goto_break


{
public static void main(String[] args)
{
boolean t = true;
first:
{
second:
{
third:
{
System.out.println("Before break."); // break out of second block
if(t)
break second;
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
} o u tp u t :

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

Java Primitive Data Types


Type Values Default Size Range
byte signed integers 0 8 bits -128 to 127
short signed integers 0 16 bits - 32768 to 32767
31 31
int signed integers 0 32 bits -2147483648 to 2147483647 ( - 2 to2 –1)
-9223372036854775808 to
long signed integers 0 64 bits 63 63
9223372036854775807 ( - 2 t o 2 – 1 )
+ / - 1 . 4E - 4 5 t o + / - 3 . 4 0 2 8 2 3 5 E + 3 8 ,
float IEEE 754 floating point 0.0 32 bits
+ / -i n fi n i t y , + / - 0 , N AN
+ / - 4 . 9E - 3 2 4 t o
double IEEE 754 floating point 0.0 64 bits +/-1.7976931348623157E+308,
+ / -i n fi n i t y , + / - 0 , N a N
char Unicode character \u0000 16 bits \u0000 to \uFFFF
1 bit used in
boolean true, false false NA
32 bit integer

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 = new i nt[5];

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

// initializing the array and display the elements


Out put:
class OneDArrIni
value of a[0] is: 10
{
value of a[1] is: 20
public static void main(String args[])
value of a[2] is: 30
{
value of a[3] is: 40
int a[]={10,20,30,40,50},i;
value of a[4] is: 50
for(i=0;i<a.length;i++)
System.out.println("value of a["+i+"] is: "+a[i]);
}
}

10 SATEESH N
SATEESH N
/ / E x a mp l e : O n e D Ar r . j a v a

// assigning elements into the array and display the elements

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] = new i nt [4]; / / f or 1 s t r o w 4 c o l s


nd
a[1] = new i nt [3]; // f or 2 row 3 cols
rd
a[2] = new i nt [5]; // f or 3 row 5 cols

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

1 1,0 1,1 1,2

2 2,0 2,1 2,2 2,3 2,4

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
}

Defining Classes and Creating Objects

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 .

• If a class doesn’t have a constructor defined, Java provides a default constructor.


• Default constructor has no argument.
* Initializes all nonstatic members to their defaults.
• Once class has a user-defined constructor, the default is ignored.
* Calling default constructor when user-defined constructor exists results in compiler error.
• One constructor can be invoked from another via the this or super keyword.
• Call to other constructor MUST be first line in method.

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

// i. to refer to the functions of the current class. Ex: this.display( );

class Vals
{
int x,y;

Vals(int p,int q) // Constructor


{
x=p;
y=q;
}

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[])
{

Student s = new Student(); //calls the 1st constructor

Student t= new Student(22,"Sanju"); //calls the 2nd constructor


Out put:
s.display();
t.display(); Student no. : 11
Student name: Raj
s.accept(33,"Sateesh");
Student no. : 22
s.display();
Student name: Sanju
}
} Student no. : 33
Student name: Sateesh
15 SATEESH N
SATEESH N

/ / 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

// iii. calling a constructor form another constructor : To call a constructor


from another constructor the this keyword should be applied in a function type.

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

class ConstructortoConstructor Val of x : 50


{ Val of y : 60
public static void main(String args[ ])
{

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.x=10; s.y=20; s.z=99;


t.x=50; t.y=60;

System.out.println("\n Val of Z: "+Vals.z);

System.out.println("\n Val of s.x : "+s.x+"\n Val of s.y : "+s.y+"\n Val of


s.z : "+s.z);
System.out.println("\n Val of t.x : "+t.x+"\n Val of t.y : "+t.y+"\n Val of
t.z : "+t.z);

System.out.println("\n Val of Z: "+Vals.z);


}
}

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);
}

static void print()


{
System.out.println("\n Value is : "+z);
}
}

class StaticMethod
{
public static void main(String args[])
{
Vals.print(); //calling static function using class name i.e., vals

Vals s = new Vals();


Vals t = new Vals(); Out put:

Value is : 77
s.x=10; s.y=20; s.z=99;
t.x=50; t.y=60; Values are : 10 20 99

s.display(); Values are : 50 60 99


t.display(); Value is : 99
s.print(); Value is : 99
t.print();
Value is : 99
Vals.print();
}
}

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

class StaticBlocks Out put:


{
static First Static Block
{
System.out.println("First Static Block"); Second Static Block
}
public static void main(String args[]) In the main program
{
System.out.println("In the main program");
}
static
{
System.out.println("Second Static Block");
}
}

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.

Example: Class1.java and Class2.java


Class1.java
public class Class1
{
public static void main(String[] args)
{
Class2 class2obj1 = new Class2();
System.out.println("----------------------");
Class2 class2obj2 = new Class2();
}
}

Class2.java

public class Class2


{
Class2() o u tp u t :
{
System.out.println("U r in Constructor"); U r in Static block
} U r in Constructor
----------------------
static U r in Constructor
{
System.out.println("U r in Static block");
}
}

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....");
}
}

Forcing Finalization and Garbage Collection :

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.

Running the Garbage Collector :


You can ask the garbage collector to run at any time by calling System's gc method:

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;
}

protected void finalize()


{
System.out.println("GC1 object " + id + " has been finalized.");
}
}
Output :
Available Free Memory: 1911256
GC1 object 5531 has been finalized.
GC1 object 5532 has been finalized.
GC1 object 5533 has been finalized.
GC1 object 5534 has been finalized.
GC1 object 5535 has been finalized.
Free Memory before call to gc(): 1222864
GC1 object 9259 has been finalized.
GC1 object 9260 has been finalized. So on. . . .

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 */

// fullname: 1 space between first and last names:


public String get_fullname()
{
String fn = "Sateesh";
String ln = "Natchireddy";
String space = "";
int spaces=1;

for(int s = 1; s <= spaces; s++)


space = space + " ";

return fn+space+ln;
} // method get_fullname (0 arguments)

// fullname: arbitrary # of spaces between first and last names


public String get_fullname(int spaces)
{
String fn = "Sateesh";
String ln = "Natchireddy";
String space = "";

for(int s = 1; s <= spaces; s++)


space = space + " ";

return fn+space+ln;
} // method get_fullname (1 argument)

// fullname: insert middle name


public String get_fullname(String middle)
{
String fn = "Sateesh";
String ln = "Natchireddy"; Output :
return fn+" "+middle+" "+ln;
} // method get_fullname (1 argument) Test1: Sateesh Natchireddy
} Test2: Sateesh Natchireddy
public class MethodOverloading_Ex1
Test3: Sateesh Kumar Natchireddy
{
public static void main(String[] args)
{
Person_name pn = new Person_name();

// Determine fullname by three differebnt (and overloaded) methods

System.out.println("Test1: " + pn.get_fullname());


System.out.println("Test2: " + pn.get_fullname(2));
System.out.println("Test3: " + pn.get_fullname("Kumar"));
}
}
22 SATEESH N
SATEESH N
A c c e s s S pe c i fie r s

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;

// doesn't effect the original values


}

public static void f1(A a)


{
// a will be received by reference

a.x = a.x + 10;


a.y = a.y + 20;

// will effect the original object in main i.e., ' a '


}
}

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("Before : "+x+" "+y);


System.out.println("Before : "+a.x+" "+a.y);

System.out.println();

B.f1(x,y); // sending by values Out put:


B.f1(a); // sending by reference Before : 10 20
Before : 10 20
System.out.println("After : "+x+" "+y);
System.out.println("After : "+a.x+" "+a.y); After : 10 20
} After : 20 40
}

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,

 For primitives, you pass a copy of the actual value.

 For references to objects, you pass a copy of the reference

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

Figure 1. Reference variable b refers to a 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

public void methodX(Button y)

If we call this method passing in a reference to a button object e.g.

Button b = new Button( );

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

Figure 3. The two different variables now reference different objects.

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.*;

public class PassByValue


{
//Demonstrates that Java parameters are always passed by value
public static void main(String[] args)
{
System.out.println("In main");
//the reference to an object is passed by value
Button b = new Button("AAA");
System.out.println("The value of b's label is " + b.getLabel());
methodX(b);
System.out.println("Back in main");
System.out.println("The value of b's label is " + b.getLabel());
System.out.println("");
//primitives are passed by value as well
int i = 5;
System.out.println("The value of i is " + i);
methodZ(i);
System.out.println("Back in main");
System.out.println("The value of i is " + i);
System.exit(0);
}

//the reference to an object is passed by value


public static void methodX(Button y)
{
System.out.println("In methodX");
System.out.println("The value of y's label is " + y.getLabel());

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());
}

//primitives are passed by value as well


public static void methodZ(int j)
{
System.out.println("In methodZ");
System.out.println("The value of j is " + j);
//change value of j - doesn't affect variable i within main
j = 6;
System.out.println("The value of j is " + j);
}
} Output :
In main
The value of b's label is AAA
In methodX
The value of y's label is AAA
The value of y's label is BBB
The value of y's label is CCC
The value of y's label is DDD
Back in main
The value of b's label is BBB

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

public class Use_Obj_as_Param_and_Returning_Obj


{
public static void main(String args[])
{
Interval a = new Interval(1,2); // a = [1,2]
Interval b = new Interval(3,4); // b = [3,4]

// add a+b 5 different ways


// all 5 tests give the same result = [4,6]
// test1
Interval t1;
t1 = a.addint(b); Output :
t1.print("Test1: ");
Test1: [4.0,6.0]
// test2
Interval t2 = a.addint(b); Test2: [4.0,6.0]
t2.print("Test2: "); Test3: [4.0,6.0]
Test4: [4.0,6.0]
// test3 Test5: [4.0,6.0]
Interval t3 = new Interval();
t3 = a.addint(b);
t3.print("Test3: ");
// test4
Interval t4 = new Interval(0,0);
t4 = a.addint(b);
t4.print("Test4: ");
// test5
a.addint(b).print("Test5: ");
} // method main
} // class returning_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.

Named Inner Classes

An inner class is a class defined inside another 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.

Inner classes are very useful in factory pattern situations.

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 */

// obj.inner1_method(); /* Error,The method inner1_method is


undefined for type class2 */

class1 obj2 = new class1();


obj2.outer_method();
}
}

Anonymous Inner Classes

Anonymous inner class: An inner class with no name.

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 very similar to named inner classes:

Anonymous inner classes can override methods of the superclass.

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.

But there are some important differences:

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.

Two ways to pass initializing parameters to an inner class:

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:

Base bref1 = new Base( )


{
void method1()
{
}
};

Base bref2 = new Base( )


{
void method1()
{
}
};

Each anonymous class is declared within an expression.

Nested Classes
Inner Classes
An inner class is a type of nested class that is not explicitly or implicitly declared static.

Inner class types


 Local inner class.
o A local class is a nested class that is not a member of any class and that has a
name.
o Every local class declaration statement is contained by a block.
o The scope of a local class declared in a block is within the rest of the block.
o Local class defined in a method has access to final method variables and also to
the outer class's member variables.
 Anonymous inner class.
o Anonymous inner class does not have name.
o It can extend a class or implement an interface but cannot do both at the same
time. (For example, an anonymous inner class cannot say extends and implements
at the same time.)
o The definition, construction and first use of such class is at same place.
o Programmer cannot define specific constructor for anonymous class but he/she
can pass arguments (to call implicit constructor of its super class.)
o An anonymous class is never abstract. An anonymous class is always an inner
class; it is never static. An anonymous class is always implicitly final.
o Anonymous class defined in a method has access to final method variables and
also to the outer class's member variables.
32 SATEESH N
SATEESH N

 Non-static member class.


o A member class is a inner class whose declaration is directly enclosed in another
class or interface declaration.
o Member inner class can be public, private, protected or default/friendly.
o Non-static member inner class has access to member variables of the outer class.
o Non-static member inner class can be instantiated on the instance of the outer
class.
Static nested classes.
 Nested class can also be static. It has access to only static member variables of the outer
class.
 Static nested class may be instantiated/accessed without the instance of the outer class.
It is accessed just like any other static member variable of a class.
For example, instance method accessTest() of public static nested class "Inner" can be
invoked as...

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);
}
}

class Inheritence Out put:


{
public static void main(String args[]) Student No. : 10
{ Student Name: Sateesh
student s = new student(); Total Fee :5000
customer c = new customer();
s.accept(); Customer No. : 101
c.accept(); Customer name : Raj
Item purchased: SAMSUNG key board
s.display(); Quantity : 2
c.display(); Price : 150.0
} Total Bill : 300.0
}

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);
}
}

class C o n st r u c t o r T O C o n st r u c t o r _ I n h e r e i t e nc e Out put:


{
Values are: 10 20 30
public static void main(String args[])
{
B b = new B(10,20,30); // calls B's constructor which calls A's constructor
b.display();
}
}

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

r.accept(); Out put:


r.display();
} Enter 1: Student 2: Customer
} 2
Customer Details: 20 Raj Mouse 2 150

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");
}
}

class student extends common


{
void accept( )
{
System.out.println("method accept() in class studnet");
}
void display()
{
System.out.println("method display() in class student");
}
} Output :
public class Inheritence_Ex2 Through object "r"
{ method accept() in class common
public static void main(String[] args) method display() in class common
{ Through object "obj"
common r = new common(); method accept() in class studnet
method display() in class student
System.out.println("Throgh object \"r\""); Through object "r2"
r.accept(); method accept() in class studnet
r.display(); method display() in class student

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();
}
}

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

For the methods : A f i n a l m e t h o d c a n ’ t b e ov er r i d d e n .


Ex: c l a ss A
{
f i n al v o i d f 1( )
{
}
}
c l a ss B ex t e n d s A
{
f i n al v o i d f 1( ) / / E r r o r c a n ’ t ov e r ri d e f i n al m et h o d
{
}
}

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.

Ex: class student extends common


{
void accept( )
{
}
}
T h e a b ov e ex am p l e g e n e r a t e s E r r o r i n c om pl e t e ov e r ri di n g .

Ex: class student extends common


{
void accept( )
{
}
void display( )
{
}
}
T h e a b ov e e x am pl e d o e s n o t g e n e r a t e a n y e r r o r s, b e c a u s e a l l t h e f u n ct i o n s o f
c l a ss c o m m o n a r e ov e rr i di n g i n cl a ss st u d e n t .

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();

abstract void f2();


}
class Hi extends abstractclass
{
void f1()
{
System.out.println("Hi");
}
42 SATEESH N
SATEESH N
void f2()
{
System.out.println("Hello");
}
}
class AbstractClass_Ex1
{
public static void main(String args[]) Output:
{
Hi
Hi h = new Hi();
Hello
h.f1();
Hi
h.f2();
Hello
abstractclass obj;
obj = new Hi();
obj.f1();
obj.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

abstract class common


{
abstract void accept( ); // abstract method
abstract void display( ); // abstract method

void f1( ) // non abstract method


{
System.out.println("HI");
}
void f2( ) // non abstract method
{
}
}
class student extends common
{
void accept( )
{
System.out.println("Hello");
}
void display( )
{
}
}
class Abstract_abstmeth_nonabstmeth
{
public static void main(String args[]) Output:
{ Hello
common r; HI
r = new student ( );
r.accept( ); // calls student accept( );
r.f1( ); // calls non-abstract method f1( ) from the common class
}
}

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

abstract class common


{
void accept()
{
System.out.println("Hello");
}
void display()
{
}
}
class student extends common
{
void display()
{
System.out.println("HI");
}
} Output:
public class AbstractClass_nonabstmeth
{ Hello
public static void main(String[] args) HI
{
// common obj = new common(); // Error, the type common can not be instantiated
common obj = new student();
obj.accept();
obj.display();
}
}

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( ) :

abstract class MyAbstractClass


{
abstract void 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:

MyAbstractClass myClass = new MyAbstractClass( )


{
void do( )
{
// Redefine here the abstract method
}
};

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

abstract class abstclass1


{
public abstract void add(int a,int b);
}

abstract class abstclass2 extends abstclass1


{
public abstract void sub(int a,int b);
}

class abstclass3 extends abstclass1


{
int a,b;
abstclass3()
{
this.a=0;
this.b=0;
}
// overridden method
public void add(int a,int b)
{
System.out.println(a+b);
}
// new method
public void sub(int a,int b)
{
System.out.println(a-b);
}
}

class abstclass4 extends abstclass2


{
int a,b;
abstclass4()
{
this.a=0;
this.b=0;
}
// overridden method
public void add(int a,int b)
{
System.out.println(a+b);
}
// overridden method
public void sub(int a,int b)
{
System.out.println(a-b);
}
}

public class AbstractClass_Ex2


{
public static void main(String[] args)
{
abstclass1 obj = new abstclass1()
{
public void add(int a,int b)
{
System.out.println((a+b));
}
45 SATEESH N
SATEESH N
// defining a new method
public void sub(int a,int b)
{
System.out.println((a-b));
}
};
// calling abstractclass1 methods
obj.add(20,30);
//obj.sub(20,30); // can't call sub() method, bcoz not declared in abstract
//class abstractclass1

abstclass2 obj1 = new abstclass2()


{
public void add(int a,int b) out put :
{
System.out.println((a+b)); 50
} 50
public void sub(int a,int b) -10
{ 45
System.out.println((a-b)); 20
} 45
}; 20
// calling abstractclass2 methods
obj1.add(20,30);
obj1.sub(20,30);

abstclass3 st3 = new abstclass3();


st3.add(10,35); // calling overridden method
st3.sub(50,30); // calling newly defined method in abstractclass3

abstclass4 st4 = new abstclass4();


st4.add(10,35); // calling overridden method
st4.sub(50,30); // calling overridden method
}
}

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 C implements A,B


{
public void f1( )
{
System.out.println("Hi");
}
public void f2( )
{
System.out.println("Hello");
}
}

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( );
}

abstract class B implements A


{
public void f1( )
{
System.out.println("Hi");
}
}

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();
}
}

Interface vs. Abstract Class

difference between an interface and an abstract class :

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 .

D : \ > S E T C L A S S PA T H= d : \ sam p a c k D ; f : \ sam pa c k F ;

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 : / > S E T C L A S S PA T H= % cl a ssp a t h % ; E : \ > sa m p a c kE ;

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 ;

// filename : A.java // placed in d:\sampackD\p1\A.java

package p1;
public class A
{
public void display()
{
System.out.println("Display from A");
}
}

// filename : B.java // placed in d:\sampackD\p1\B.java

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

import p1.A; // import the selected class


import p1.B;
import p2.*; // import all the classes

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("S Hash code: "+s.hashCode());


System.out.println("T Hash code: "+t.hashCode());
System.out.println("R Hash code: "+r.hashCode());

System.out.println();

if(s.equals(t)) Out put:


System.out.println("S and T are equal");
else S Hash code: 3541984
System.out.println("S and T are not equal"); T Hash code: 4565111
R Hash code: 3541984
if(s.equals(r))
System.out.println("S and R are equal"); S and T are not equal
else S and R are equal
System.out.println("S and R are not equal");
student@360be0
System.out.println(); student@45a877
student@360be0
System.out.println(s.toString());
System.out.println(t.toString()); student@360be0
System.out.println(r.toString()); student@45a877
student@360be0
System.out.println();

System.out.println(s); // calls System.out.println(s.toString());


System.out.println(t);
System.out.println(r);

}
}

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:

class Student implements Cloneable


{
- - - - -
}

 Since clone( ) is a general method, it has a return type of Object. So we need to type-cast the result.

 The clone( ) method is declared in Object to throw the CloneNotSupportedException, so we need to


handle this error.

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.

A clone( ) method MUST:


 have a return type of Object
 take no parameters
 call super.clone();
 handle or throw a CloneNotSupportedException

Here is what the clone( ) method for Student may look like::

public Object clone()


{
try
{
return super.clone();
}
catch (CloneNotSupportedException e )
{
throw new Error("This should never happen!");
}
}

Example : Shallow_clone_Ex1.java

class Marks
{
int datacommunications;
int networks;
int cryptography;

void accept(int dc, int net,int cryp)


{
datacommunications = dc;
networks = net;
cryptography = cryp;
}

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";
}

public Object clone()


{
try
{
return super.clone();
}
catch (CloneNotSupportedException e )
{
throw new Error("This should never happen!");
}
}
}

public class Shallow_clone_Ex1 //implements Cloneable


{
public static void main(String [] args)
{
Student obj_one = new Student ();
System.out.println("Before clone Contents in obj_one: ");
System.out.println("sno: "+obj_one.sno+" "+"Name: "+obj_one.sname);
obj_one.m.accept(40,38,46);
obj_one.m.display();

// copying contents of obj_one into obj_two


Student obj_two = (Student)obj_one.clone();

System.out.println("After clone Contents in obj_one: ");


System.out.println("sno: "+obj_one.sno+" "+"Name: "+obj_one.sname);
obj_one.m.display();
System.out.println("After clone Contents in obj_two: ");
System.out.println("sno: "+obj_two.sno+" "+"Name: "+obj_two.sname);
obj_two.m.display();

System.out.println("Modifying obj_two..... ");


obj_two.sno = 200;
obj_two.sname = "Kumar";
obj_one.m.accept(44,44,44);
System.out.println("Modified obj_two. ");
// Values of Inner Object " m " of class Marks gets change in both objects
// obj_one and obj_two, because they share same memory locations.
System.out.println("After modified obj_two Contents in obj_one: ");

System.out.println("sno: "+obj_one.sno+" "+"Name: "+obj_one.sname);


obj_one.m.display();

System.out.println("After modified obj_two Contents in obj_two: ");


System.out.println("sno: "+obj_two.sno+" "+"Name: "+obj_two.sname);
obj_one.m.display();
}
}

57 SATEESH N
SATEESH N

Output :

Before clone Contents in obj_one: Modifying obj_two.....


sno: 100 Name: sateesh Modified obj_two.
Marks:: After modified obj_two Contents
DataCommunications : 40 in obj_one:
NetWorks : 38 sno: 100 Name: sateesh
CryptoGraphy : 46 Marks::
After clone Contents in obj_one: DataCommunications : 44
sno: 100 Name: sateesh NetWorks : 44
Marks:: CryptoGraphy : 44
DataCommunications : 40 After modified obj_two Contents
NetWorks : 38 in obj_two:
CryptoGraphy : 46 sno: 200 Name: Kumar
After clone Contents in obj_two: Marks::
sno: 100 Name: sateesh DataCommunications : 44
Marks:: NetWorks : 44
DataCommunications : 40 CryptoGraphy : 44
NetWorks : 38
CryptoGraphy : 46
cont. . .

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 :

 provide an attractive alternative to the rather pathological clone method


 are easily implemented
 simply extract the argument's data, and forward to a regular constructor
 are unnecessary for immutable objects

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.

Here's the general form of these statements:


try
{
statement(s)
}
catch (exceptiontype name)
{
statement(s)
}
finally
{
statement(s)
}

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

Exceptions are of two types:

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.

Difference between Error and Excepiton :

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.).

There are two ways to handle exceptions,

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");
}

public static void main(String args[])


{
try
{ Out put:
f1(2); OK
f1(5); OK
f1(0); Arithmetic Error Occured
}
catch(ArithmeticException ex)
{
System.out.println("Arithmetic Error Occured");
}
catch(NegativeArraySizeException ex)
{
System.out.println("Invalid size for Array");
}
}
}

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 Clause

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.

class MyException1 extends Exception


{
String msg;

MyException1()
{
msg = "First Exception Occured";
}
public String toString()
{
return msg;
}
}

class MyException2 extends Exception


{
String 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

b o o l e a n e q u a l sI g n o r e C a s e ( String s2 ) : Com pares the st r i n g s wi t h o u t case


se n si t i v e n e ss.

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.

Ex: st 1 = “ abc xyz “;


st 2 = st 1 . t ri m ( ) ;  “abc xyz”

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 ” ;

i f ( st . st a r t sW i t h ( “ T hi s” ) ) Both are true.


i f ( st . e n d sW i t h ( “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();

for ( int j=data.length()-1; j >= 0; j-- )


rev += data.charAt(j);

return rev;
}

public static void main ( String[] args )


{
System.out.println( reverse( "Hello" ) );
}
}

/* 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);

As the statement starts to execute, rev refers to a String. The


concatenation operator "+" creates a new String with one more character on
the end. The new String reference is assigned to rev (the old String is now
garbage).

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

p u bl i c St ri n gBuf f er (i nt c ap aci t y ): c r e at e a St ri n gB uf f e r wi t h i ni t i al r oom f o


r c ap aci t y c ha ra ct er s

p u bl i c St ri n gBuf f er (S tri ng st ) : c r e at e a St ri n gB uf f e r c ont ai ni n g t he c h ar acte r


s f rom st

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 ( i nt i ) : Co nv ert i t o c har ac t er s, t h en ap pe nd t hem t o t h e e n


d of t h e St ri n gB uf f er , sam e f o r ot h er prim i t iv e d at a t y pe s.

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.

i nt ca paci t y () : R et u rn t h e c ur re nt ca pa cit y (c ap aci t y wi ll gro w a s n e ed ed ).

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 .

S t ri n gBuf f er i n se rt ( i nt i nd ex , c ha r c ) : I nse rt ch ar act er c at i n dex ( ol d c ha ra ct er s m ov e


ov er t o m ak e r oom ).

S t ri n gBuf f er i n se rt ( i nt i nd ex , St ri ng st ): I n sert c h ar act er s f r om st st art i ng at po si ti o n i .

S t ri n gBuf f er i nse r t ( i nt i nd ex , i nt i ) : Conv er t i t o c har ac t er s, t hen i nser t t hem st ar t i ng


a t i nd ex , sam e f or ot her d at a t y p es

i nt l e ngt h( ) : R et u rn t h e n um b er of c har ac t er s.

StringBuffer reverse() : R ev erse t he or de r of t he c h ar act er s.

v oi d se t C ha rAt ( i nt i nd ex , c h ar c ) : S e t t h e c har ac t er at i n dex t o c.

S t ri n g t o St ri ng () : R et u rn a St ri n g o bj ect c ont ai ni n g t he c ha ra ct e r s i n t h e St ri n gBuf f er.

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.

public class ReverseTester_St_Buf


{
public static String reverse( String data )
{
StringBuffer temp = new StringBuffer();

for ( int j=data.length()-1; j >= 0; j-- )


temp.append( data.charAt(j) );

return temp.toString();
}

public static void main ( String[] args )


{
System.out.println( reverse( "Hello" ) );
}
}

Data Conversions :

public class DataTypeConverter


{
public static void main(String artgs[])
{
// Converting int to string
int my_int = 3;
// approach 1
String my_str = Integer.toString(my_int);
System.out.println("int to String (1): "+my_str);
// approach 2
String my_str2 = ""+my_int;
System.out.println("int to String (2): "+my_str2);

// Converting string to int


String str;
str = "25";

// 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);

// Converting string to double


double d = Double.valueOf(str).doubleValue();
System.out.println("String to double : "+d);
}
}
67 SATEESH N
SATEESH N
IO Management

What is a a stream?

Java programs perform I/O operations through streams.

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.

Character Streams versus Byte Streams

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.

Bridging the Gap Between Byte and Character 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:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

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

These input streams each have a pushback buffer. When reading


PushbackReader
Peeking Ahead data from a stream, it is sometimes useful to peek at the next few
PushbackInputStream bytes or characters in the stream to decide what to do next.

Contain convenient printing methods. These are the easiest


PrintWriter
Printing streams to write to, so you will often see other writable streams
PrintStream wrapped in one of these.
BufferedReader Buffer data while reading or writing, thereby reducing the number
BufferedWriter of accesses required on the original data source. Buffered
Buffering
BufferedInputStream streams are typically more efficient than similar nonbuffered
BufferedOutputStream streams and are often used with other streams.
FilterReader
FilterWriter These abstract classes define the interface for filter streams,
Filtering
FilterInputStream which filter data as it's being read or written.
FilterOutputStream

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").

StreamTokenizer : A class used to parse the input streams called StreamTokenizer.

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 :

F i l e ( S t ri n g p a t h n am e ) : The file instance can be created with a path name.

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

ByteArrayInputStream : A ByteArrayInputStream is a stream whose data comes from a byte array.


None of the methods of this class throw an IOException because the data comes from an array instead of an
actual I/O device. This class does not support the ability to mark a position in the stream. A call to reset(),
however, does position the stream at the beginning of the byte array.

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( ) : Creates a new byte array output stream.

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;

public class ByteArrayIOStreams


{
public static void main(String args[]) throws IOException
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();

String s = "This is a test.";

for(int i=0;i<s.length();++i)
outStream.write(s.charAt(i));
73 SATEESH N
SATEESH N

System.out.println("outstream: " + outStream); OutPut :


System.out.println("size: " + outStream.size());
outstream: This is a test.
ByteArrayInputStream inStream = new size: 15
ByteArrayInputStream(outStream.toByteArray()); inStream has 15 available bytes
15 bytes were read
int inBytes = inStream.available(); They are: This is a test.

System.out.println("inStream has " + inBytes + " available bytes");

byte inBuf[] = new byte[inBytes];


int bytesRead = inStream.read(inBuf, 0, inBytes);
System.out.println(bytesRead + " bytes were read" );
System.out.println("They are: " + new String(inBuf));
}
}

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;

public class CharArrayIOReadWrite


{
public static void main(String args[]) throws IOException
{
CharArrayWriter out = new CharArrayWriter();
74 SATEESH N
SATEESH N

String s = "This is a test.";

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();

System.out.println(s.length()+" characters were read");


System.out.println("They are: "+s);
}
}

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;

public class StringReadWrite


{
public static void main(String args[]) throws IOException
{
StringWriter outStream = new StringWriter();

String s = "This is a test.";

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());

StringReader inStream = new StringReader(outStream.toString());

int ch=0;

StringBuffer sb = new StringBuffer("");


while((ch = inStream.read()) != -1) Output :
sb.append((char) ch);
outstream: This is a test.
s = sb.toString(); size: 15
15 characters were read
System.out.println(s.length()+" characters were read"); They are: This is a test.
System.out.println("They are: "+s);
}
}

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 :

F i l e I n p u t St r e am ( St ri n g f i l e n a m e ) t h r o ws F i l e N o t F o u n d E x c e pt i o n : Opens the giv en


f i l e i n t h e i n p u t m o d e . I f t hi s f i l e c a n ’ t b e o p e n e d t h e F i l e N o t F o u n d Ex c e p t i o n wi l l be
t h r o wn .

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 :

F i l e O ut p u t S t r e am ( S t ri n g f i l e n am e ) t h r o ws I O E x c e pt i o n : This constructor creates a


FileOutputStream that sends its output to the file named by the specified String.

F i l e O ut p u t S t r e am ( F i l e f i l e o b j e c t ) t h r o ws I O Ex c e p t i o n : This constructor creates a


FileOutputStream that sends its output to the file represented by the specified File.

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";

FileInputStream fin = new FileInputStream(in_fname);

FileOutputStream fout = new FileOutputStream(out_fname);

int ch = fin.read(); // to read 1st character

while(ch != -1) // while(ch != EOF) Out put:


{
// Displaying on console This sample file is created
System.out.print( (char) ch); for testing io streams.
fileinputstreamreader,
// Wrinting into output file
fileoutputstreamreader,
fout.write(ch);
bufferedreader etc.,
ch = fin.read(); // read remaining characters
}
fin.close();
fout.close();
}
catch(FileNotFoundException ex)
{
System.out.println("File not found");
}
77 SATEESH N
SATEESH N
catch(IOException ex)
{
System.out.println("Read/Write Error");
}
}
}

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.*;

public class CopyFile


{
public static void main(String[] args) throws IOException
{
try
{
File inputFile = new File("D://sateesh_inputfile.txt ");
File outputFile = new File("D://sateesh_outputfile.txt ");

FileReader in = new FileReader(inputFile);


FileWriter out = new FileWriter(outputFile);
int c;
78 SATEESH N
SATEESH N

while ((c = in.read()) != -1)


out.write(c);

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)

S e q u en c e I n p u tS t r e a m : The SequenceInputStream creates a single input stream from multiple input


sources.

C o n s t r u c to r s :

SequenceInputStream(InputStream s1, InputStream s2) : This constructor creates a SequenceInputStream


that reads first from s1 and then from s2.

SequenceInputStream(Enumeration e) : This constructor creates a SequenceInputStream that reads from


each of the InputStream objects in the given Enumeration. Each object in the Enumeration must be an
InputStream.

This example program, Concatenate, uses SequenceInputStream to implement a concatenation utility


that sequentially concatenates files together in the order they are listed.

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;

public class Concatenate_SeqIS_Ex1


{
public static void main(String[] args) throws FileNotFoundException
{
String filelist[] = {"D://sateesh_file1.txt","D://sateesh_file2.txt"};

InputStream is1 = new FileInputStream(filelist[0]);


InputStream is2 = new FileInputStream(filelist[1]);

try
{
SequenceInputStream s = new SequenceInputStream(is1,is2);
int c;

while ((c = s.read()) != -1)


{
System.out.write(c);
}
s.close();
}
79 SATEESH N
SATEESH N
catch (IOException e)
{ Output :
System.err.println("Concatenate: " + e);
} File name: sateesh_fiel1.txt
} This sample file is created
} for testing io streams.
E x a m p l e : Concatenate_SeqIS_Ex2.java inputstreamreader,
outputstreamreader,
import java.io.FileInputStream; bufferedreader etc.,
import java.io.FileNotFoundException;
import java.io.IOException; File name: sateesh_fiel2.txt
import java.io.InputStream;
red
import java.io.SequenceInputStream;
green
import java.util.Enumeration;
blue
import java.util.Vector;
yellow
black
public class Concatenate_SeqIS_Ex2
{
public static void main(String[] args) throws FileNotFoundException
{
String filelist[] = {"D://sateesh_file1.txt","D://sateesh_file2.txt"};
Vector vfilelist = new Vector();
InputStream is1 = new FileInputStream(filelist[0]);
InputStream is2 = new FileInputStream(filelist[1]);
vfilelist.add(is1);
vfilelist.add(is2);
Enumeration e = vfilelist.elements();
try
{
SequenceInputStream s = new SequenceInputStream(e);
//SequenceInputStream s = new SequenceInputStream(vfilelist.elements());
int c;

while ((c = s.read()) != -1) Output :


System.out.write(c); Same as above program

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:

DataInputStream d = new DataInputStream(in);

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.

Data Type Method

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

Reading lines from the file : I n o r d e r t o r e a d l i n e f r om a n y i n p u t st r e a m t h e


f ol l o wi n g 2 cl a sse s a r e u se d .

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.

Here's an example that shows InputStreamReader in action.


// Connect a BufferedReader, to an InputStreamReader which is connected to an InputStream called 'in'.

BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) );

You can do the same with an OutputStream to a Writer (OutputStreamWriter).

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.

public InputStreamReader(InputStream in, String enc) throws UnsupportedEncodingException : This


construc-tor creates an InputStreamReader that gets its data from in and translates bytes to characters using
the given 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";

FileInputStream fin = new FileInputStream(fname);


InputStreamReader isr = new InputStreamReader(fin);
BufferedReader br = new BufferedReader(isr);

// BufferedReader br = new BufferedReader(new InputStreamReader(new


FileInputStream(fname))); //this statement can be used instead of above 3 lines

String str = br.readLine( );

int n = 0; Out put:


while( str != null)
1:
{ 2: This sample file is created
n++; 3: for testing i/o streams.
System.out.println(n+": "+str); 4:
str = br.readLine(); 5: InputStreamReader,
} 6: OutputStreamReader,
7: BufferedReader etc.,
br.close();
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}

BufferedInputStream : The BufferedInputStream's contribution to its attached stream is the addition


of a buffer, or cache, to the stream. This has the effect of improving the performance of some input streams,
especially those bound to slower sources like a file or network connection.

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.

readLine( ) : This method is used to read a line of text.

read( ) : This method is used to read single character.

skip( ) : This method is used to skip number of characters.


84 SATEESH N
SATEESH N

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");

LineNumberReader inLines = new LineNumberReader(inFile);

String inputLine;

while ((inputLine=inLines.readLine()) != null)


{
System.out.println(inLines.getLineNumber()+". "+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.*;

class ISR_BR_ReadLines Out put :


{
public static void main(String args[]) Enter 5 strings:
{
try Red
{ Green
InputStreamReader isr = new InputStreamReader(System.in); Blue
BufferedReader stdin = new BufferedReader(isr); Yellow
Black
// BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in)); Black
Yellow
int i; Blue
Green
String arr[] = new String[5]; Red

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

BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in) );

//output

PrintWriter out = new PrintWriter(new FileOutputStream("D://sateesh.txt"));

86 SATEESH N
SATEESH N
for(int i=1;i<=5;i++)
{
System.out.print("Enter: ");

String str = stdin.readLine(); //read from key board


Output :
out.println(str); //write into out, i.e, into file
} Enter: red
Enter: green
stdin.close(); Enter: blue
out.close(); Enter: yellow
System.out.println("File Created.."); Enter: black
} File Created..

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

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

// reading filename
System.out.print ("Enter source file name: ");
String sourcefname = stdin.readLine();

System.out.print("Enter target file name: ");


String targetfname = stdin.readLine();

// open the 1st file in input mode


BufferedReader in = new BufferedReader(new InputStreamReader(new
FileInputStream(sourcefname)));

// open the target file in output mode


PrintWriter out = new PrintWriter(new FileOutputStream(targetfname));

// 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.

Piped Stream Classes

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.*;

class MyThread extends Thread


{
private PipedReader pr;
private PipedWriter pw;

MyThread (String name, PipedReader pr, PipedWriter pw)


{
super (name);

this.pr = pr;
this.pw = pw;
}

public void run ()


{
try
{
if (getName ().equals ("src"))
{
for (int i = 0; i < 15; i++)
pw.write ("src " + " A" + i + "\n"); // src writes

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 :

MyThread mt1 = new MyThread ("src", pr, pw); src A0


MyThread mt2 = new MyThread ("dst", pr, pw); src A1
src A2
mt1.start (); src A3
src A4
try src A5
{ src A6
Thread.sleep (2000); src A7
} src A8
catch (InterruptedException e) src A9
{ src A10
} src A11
src A12
mt2.start (); src A13
} src A14
}

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.

public RandomAccessFile(String name, String mode) : This constructor creates a RandomAccessFile to


access the file with the specified name 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.

By default, a StreamTokenizer recognizes the following:

Whitespace characters between '\u0000' and '\u0020'

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 '-'

String quote characters "'" and "'"

Comment character "/"

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.

To specify that a character is not a comment character, use ordinaryChar().

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_EOF The end of the input stream has been reached.

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.

To specify that a character is not a string-quote character, use ordinaryChar(). Output :

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

Zip Stream Classes

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 .

st a t i c v oi d sl e e p ( l o n g m i l l i se c o n d s ) t h r o w s I n t e r r u p t e d E x c e p t i o n : Makes the thread


t o sl e e p f o r t h e sp e c i f i e d t i m e.

v oi d j oi n ( ) t h r o w s I n t e r r u p t e d E x c e p t i o n : Makes the current thread to wait until the


sp e c i f i e d t h r e a d f i ni sh e s.

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 ) ;

try Out put:


{ E:\Core>javac synchprinterfun.java
T h r e a d . sl e e p ( d e l a y ) ; E:\Core>java synchprinterfun
}
c a t c h (I n t e r r u p t e d Ex c e pt i o n ex ) [
{ 1
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 " ) ; 2
} 3
} 4
5
S y st em . o u t . p r i nt l n ( "] " ); 6
} 7
} 8
c l a ss u s e r e x t e n d s T h r e a d 9
{ 10
p ri n t e r p ; ]
[
i n t st a r t , e n d , d e l a y; 41
42
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 ) 43
{ 44
t h i s. p = p ; 45
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; 26
} 27
28
p u bl i c v oi d r u n ( ) 29
{ 30
sy n c h r o n i z e d ( p ) ]
{
p. p r i n t ( st a r t , e n d , d e l a y ); E:\Core>
}
}

}
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.

1 . p u b l i c v oi d wa i t ( ) t h r o w s I n t e r u p t e d E x c ep t i o n : Makes the current thread t o


wa i t .

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();

producer p = new producer(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 :

Tokens and Delimiters

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.

// File name : StrTok1.java

import java.io.*;
import java.util.*;

public class StrTok1 {


public static void main ( String[] args ) throws IOException
{
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter a string:");
String data = stdin.readLine();

StringTokenizer tok = new StringTokenizer( data );

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.

Some methods of the class:

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.

boolean hasMoreTokens( ) : Return true if there are more tokens.

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.*;

public class StrTok2 {


public static void main ( String[] args ) throws IOException
{
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));

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:

java.util.Date Represents a point in time.

Abstract java.util.Calendar
java.util.GregorianCalendar extends Interpretation and manipulation of Dates.
java.util.Calendar

Abstract java.util.TimeZone Representation of an arbitrary offset from Greenwich Mean Time


java.util.SimpleTimeZone extends (GMT), including information about applicable daylight savings
java.util.TimeZone rules.

Abstract java.text.DateFormat extends


java.text.Format
Transformation into well-formatted, printable String and vice versa.
java.text.SimpleDateFormat extends
java.text.DateFormat

Translation of the names of months, weekdays, etc., as an


java.text.DateFormatSymbols
alternative to using the information from Locale.

java.sql.Date extends java.util.Date


Represent points in time, and also include proper formatting for
java.sql.Time extends java.util.Date
use in SQL statements.
java.sql.Timestamp extends java.util.Date
Note that DateFormat and related classes are in the java.text.* package. All date-handling classes in the
java.sql.* package extend java.util.Date. All other classes are in the java.util.* package.

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.

There are several ways to construct a Date object.

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.

Date dt1 = new Date(); //defaults to now

Date dt2 = new Date(100,01,29); //deprecated! year + 1900,month + 1,day

Date dt3 = new Date("02/30/2005"); //deprecated! parses a String

DateFormat df = DateFormat.getDateInstance(); //factory for a SimpleDateFormat

System.out.println("Date1=" + df.format(dt1)); //prints todays date

System.out.println("Date2=" + df.format(dt2)); //prints Feb 29, 2005

System.out.println("Date3=" + df.format(dt3)); //prints Mar 1, 2005!

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.

The preferred way to get specific Dates is by manipulating a Calendar.

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

//Get a default (Gregorian) Calendar set to now


Calendar cal = Calendar.getInstance();

//Set the DAY field to 1 and get the date


java.util.Date today = cal.getTime();
cal.set(java.util.Calendar.DAY_OF_MONTH, 1);
java.util.Date firstOfMonth = cal.getTime();

//Add 1 month to the calendar - may also change the year!


cal.add(Calendar.MONTH, 1);

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.

java.text.DateFormat is an abstract class that is extended by the java.text.SimpleDateFormat class.


You can use both these classes to display java.util.Date objects in various String formats and parse String
representations of dates into Date objects.

java.util.Date today = new java.util.Date();

DateFormat df1 = DateFormat.getDateInstance(); //get default format for current Locale

108 SATEESH N
SATEESH N

DateFormat df2 = new SimpleDateFormat("MMMM, yyyy"); //display month and year

DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy"); //standard mdy format

System.out.println(df1.format(today)); //prints "Jan 31, 2005"

System.out.println(df2.format(today)); //prints "January, 2005"

System.out.println(df3.format(today)); //prints "01/31/2005"

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.

java.util.Date reportDate = null;


java.text.SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");

//Beware date literals without centuries!


String newReportDate = "02/28/05"; //Feb 28th 0005 AD
try
{
//turn a String into a Date object
reportDate = df.parse(newReportDate);
}
catch (java.text.ParseException e1)
{
System.out.println("Invalid date entered = " + newReportDate);
}

// File name : SimpleDateForm.java

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. */

int year = new Date().getYear() + 1900;


System.out.println("Present Year : "+year);

int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};


GregorianCalendar c = new GregorianCalendar();
daysInMonths[1] += c.isLeapYear(c.get(GregorianCalendar.YEAR)) ? 1 : 0;
109 SATEESH N
SATEESH N
System.out.println("No. of Days in current Month is :
"+daysInMonths[c.get(GregorianCalendar.MONTH)]);

System.out.println("No. of Days in current Month is :


"+c.getActualMaximum(GregorianCalendar.DAY_OF_MONTH));

int day = c.get(Calendar.DAY_OF_WEEK );


System.out.println("Day of Week is : "+day);

System.out.println("Day of Month is : "+c.get( Calendar.DAY_OF_MONTH ));


System.out.println("Week of Month is: "+c.get( Calendar.DAY_OF_WEEK_IN_MONTH ));
System.out.println("Day of year is : "+c.get( Calendar.DAY_OF_YEAR ));
System.out.println("Day of Month is : "+c.get( Calendar.DATE ));
}
}

output :

Todays Date is: 19/02/2005


Present Year : 2005
No. of Days in current Month is : 28
No. of Days in current Month is : 28
Day of Week is : 7
Day of Month is : 19
Week of Month is: 3
Day of year is : 50
Day of Month is : 19

// File name : GetDayName.java

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));
}

public static String sayDayName(Date d)


{
DateFormat f = new SimpleDateFormat("EEEE");
try
{
return f.format(d);
}
catch(Exception e) output :
{
e.printStackTrace(); 1989-10-17 was a Tuesday
return ""; Today is a Saturday
}
}
}
110 SATEESH N
SATEESH N

// File name: StringTODate_Converter.java

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringTODate_Converter


{
public static void main(String[] args) throws ParseException
{

String today_str = "04-01-2005";

SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");

Date today_date = new Date();

today_date = df.parse(today_str);

Date cur_date = new Date();

System.out.println(today_date.toString());
System.out.println(cur_date.toString());

int res = today_date.compareTo(cur_date);


System.out.println(res);

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");
}
}
}

// File name: ValidateDate.java

// 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");
}

/* Using GregorianCalendar, give months 0 - jan to 11 - dec otherwise it


will throw exception */
try
{
GregorianCalendar gc = new GregorianCalendar();
gc.setLenient(false); // must do this
gc.set(GregorianCalendar.YEAR, 2004);
gc.set(GregorianCalendar.MONTH, 11); // 12 is invalid month
gc.set(GregorianCalendar.DATE, 24);

System.out.println(gc.getTime()); // exception thrown here


}
catch (Exception e) output :
{
e.printStackTrace(); Unparseable date: "1990/10/88"
} Date is ok = Sat Feb 19 00:00:00 IST 2005(050219)
} Fri Dec 24 02:22:06 IST 2004
}

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

The Collection Interface and its Class Hierarchy

Querying methods (returns some kind of value):

 size( ) - returns the number of elements in the collection


 isEmpty( ) - returns whether or not there are any elements in the collection
 contains(Object obj) - returns whether or not the given object is in the collection (uses .equals( )
method for comparison)
 containsAll(Collection c) - same as above but looks for ALL elements specified in the given
collection parameter.

Modifying methods (changes the collection in some way):

 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.

Examining the diagram, we notice a few things of interest:

 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):

The List classes:

 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.

There are 4 main List implementations:

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

 methods for double-ended access, no direct access from the middle


 (you'll see more on this in your data structures course)

Stack

 accessible from one end only (the top).

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.

A Vector (or ArrayList):

 can store arbitrary objects like an array.


 cannot store values of primitive data types unless they are wrapped up in a wrapper class.
 will grow automatically as space is needed (grows either by a default or user-defined amount).
 has an efficient method for adding an element, except when the vector gets full ... in that case, it takes
time to "grow" the vector before adding the new element.

Here are two ways of making one and storing it in a variable:

Vector aVector = new Vector();


Vector aVector = new Vector(Collection col);

ArrayList anArrayList = new ArrayList();


ArrayList anArrayList = new ArrayList(Collection col);

Once created, you can then apply any of the standard collection methods (plus others):

Vector myList = new Vector( ); ArrayList myList = new ArrayList( );


myList.add("Hello"); myList.add("Hello");
myList.add(new Date()); myList.add(new Date());
myList.add(new BankAccount()); myList.add(new BankAccount());
System.out.println(myList.size()); System.out.println(myList.size());

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.

 it is as if JAVA forgot what kind of object was put in there


 we need to “type-cast” the value to an appropriate type.

E.g., Consider creating a Vector of Customer objects:

String[] names = {"Sateesh", "Rahul", "Sanjana", "Nani"};


Vector v = new Vector(); //can use ArrayList v = new ArrayList( ); instead

for(int i=0; i<names.length; i++)


{
Customer c = new Customer();
c.setNamenames[i]);
v.add(c);
}

To get the Customers back out later, we must type-cast the result of the get(int index) method:

for (int i=0; i<v.size();i++)


{
Customer c = (Customer)v.get(i);

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( ) : Constructs an empty list with an initial capacity of ten.

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.*;

public class Vector_Ex1


{
public static void main(String argv[])
{
Vector_Ex1 obj = new Vector_Ex1();
obj.amethod();
}//End of main

public void amethod()


{
Vector mv = new Vector(); // or ArrayList mv = new ArrayList();
//Note how a vector can store objects of different types

mv.addElement("Hello");
mv.addElement(Color.red);
mv.addElement(new Integer(99));

//This would cause an error,As a vector will not storeprimitives


//mv.addElement(99)

//Walk through each element of the vector


for(int i=0; i< mv.size(); i++)
System.out.println(mv.elementAt(i));

}//End of amethod
}

116 SATEESH N
SATEESH N
out put :

Hello
java.awt.Color[r=255,g=0,b=0]
99

Enumerations and Iterators

Enumerations are objects that:

 generate elements from a collection one by one.


 are meant to be used to traversing (i.e., enumerate through) the elements of a collection once

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.

Enumerations have two methods:

 hasMoreElements( ) ... are there any more left ?


 nextElement( ) ... get me the next one

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 :

Here is an example of how to use the Enumeration class on a Vector:

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"};

Vector aVector = new Vector(java.util.Arrays.asList(num));

System.out.println("Before Vector: " + aVector);

Enumeration nums = aVector.elements();

int elementno = 1;

System.out.println("Element NO. Element");

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.

There are 3 methods:

 hasNext( ) ... are there any more left ?


 next( ) ... get me the next one
 remove( ) ... remove the latest item from the collection

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;

public class Iterator_Ex1


{
public static void main(String args[])
{
String[] num = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
Vector aVector = new Vector(java.util.Arrays.asList(num));
System.out.println("Before Vector: " + aVector);
Iterator nums = aVector.iterator(); // Returns an Iterator for forward traversal
//ListIterator nums = aVector.listIterator(); // Returns a ListIterator
for forward / backward / modifying traversal.
int elementno = 1;
System.out.println("Element NO. Element");
while(nums.hasNext())
{
String aString = (String)nums.next();
System.out.println(elementno+" "+aString);
if (aString.length() > 4)
nums.remove();
elementno++;
}
System.out.println("After Vector: " + aVector);
}
}
119 SATEESH N
SATEESH N
out put:

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.

// Use an Integer as a wrapper for an int


Integer integer = new Integer ( i );
hash.put( integer, data);

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.

// Get all values with an enumeration of the keys


for (Enumeration e = hash.keys(); e.hasMoreElements();)
{
String str = (String) hash.get( e.nextElement() );
System.out.println (str);
}

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. */

public class HashTable


{
public static void main (String args[]) throws Exception
{
// Start with ten, expand by ten when limit reached
120 SATEESH N
SATEESH N
Hashtable hash = new Hashtable(10,10);

for (int i = 0; i <= 100; i++)


{
Integer integer = new Integer ( i );
hash.put( integer, "Number : " + i);
}

// Get value out again


System.out.println (hash.get(new Integer(5)));

// Get value out again


System.out.println (hash.get(new Integer(21)));

// Get all values


Enumeration e = hash.keys();
int hashkey;
System.out.println ("Displaying all values of Hashtable.. (Hashtable is
unordered )");

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.

Dealing With Duplicates

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();

public int size()


{
return keys.size();
}

public boolean isEmpty()


{
return keys.isEmpty();
}

public Object put(Object key, Object value)


{
keys.addElement(key);
values.addElement(value);
return key;
}

public Object get(Object key)


{
int index = keys.indexOf(key);
// indexOf() Returns -1 if key not found:
if(index == -1) return null;
return values.elementAt(index);
}

public Object remove(Object key)


{
int index = keys.indexOf(key);
if(index == -1) return null;
keys.removeElementAt(index);
Object returnval = values.elementAt(index);
values.removeElementAt(index);
return returnval;
}

public Enumeration keys()


{
return keys.elements();
}

public Enumeration elements()


{
return values.elements();
}
122 SATEESH N
SATEESH N

// Test it:
public static void main(String[] args)
{
AssocArray_Dictionary aa = new AssocArray_Dictionary();

for(char c = 'a'; c <= 'z'; c++)


aa.put(String.valueOf(c),String.valueOf(c).toUpperCase());

char[] ca = { 's', 'a', 't', 'i', 's', 'h' };

for(int i = 0; i < ca.length; i++)


System.out.println("Uppercase: " +aa.get(String.valueOf(ca[i])));
}

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

public class BitSet1


{
public static void main(String[] args)
{
Random rand = new Random();
// Take the LSB of nextInt():
byte bt = (byte)rand.nextInt();
BitSet bb = new BitSet();
for(int i = 7; i >=0; i--)
if(((1 << i) & bt) != 0)
bb.set(i);
else
bb.clear(i);
123 SATEESH N
SATEESH N
System.out.println("byte value: " + bt);
printBitSet(bb);

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);

// Test bitsets >= 64 bits:


BitSet b127 = new BitSet();
b127.set(127);
System.out.println("set bit 127: " + b127);
BitSet b255 = new BitSet(65);
b255.set(255);
System.out.println("set bit 255: " + b255);
BitSet b1023 = new BitSet(512);

// Without the following, an exception is thrown


// in the Java 1.0 implementation of BitSet:
// b1023.set(1023);
b1023.set(1024);
System.out.println("set bit 1023: " + b1023);
}

static void printBitSet(BitSet b)


{
System.out.println("bits: " + b);
String bbits = new String();
for(int j = 0; j < b.size() ; j++)
bbits += (b.get(j) ? "1" : "0");
System.out.println("bit pattern: " + bbits);
}

out put:

byte value: -30


bits: {1, 5, 6, 7}
bit pattern: 0100011100000000000000000000000000000000000000000000000000000000
short value: -14048
bits: {5, 8, 11, 14, 15}
bit pattern: 0000010010010011000000000000000000000000000000000000000000000000
int value: -1916419530
bits: {1, 2, 4, 5, 9, 14, 15, 16, 18, 22, 23, 24, 26, 27, 31}
bit pattern: 0110110001000011101000111011000100000000000000000000000000000000
124 SATEESH N
SATEESH N
set bit 127: {127}
set bit 255: {255}
set bit 1023: {1024}

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.

What do we use a stack for ?

 useful for recording the state of a computation as it unfolds


 evaluation of expressions that involve precedence and nesting

can be used for reversing items

To make a new stack we just say something like this:

Stack myStack = new Stack();

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.*;

public class StackDemo2


{
static String[] months = {
"January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December" };
125 SATEESH N
SATEESH N

public static void main(String[] args)


{
Stack stk = new Stack();
for(int i = 0; i < months.length; i++)
stk.push(months[i] + " ");

System.out.println("stk = " + stk);

// Treating a stack as a Vector:


stk.addElement("The last line");

System.out.println("element 5 = " + stk.elementAt(5));

System.out.println("popping elements:");
while(!stk.empty())
System.out.println(stk.pop());
}
}

output :

stk = [January , February , March , April , May , June , July , August ,


September , October , November , December ]
element 5 = June
popping elements:
The last line
December
November
October
September
August
July
June
May
April
March
February
January

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 ) ;
}
}

< ! - - H T M L c o d e f o r a p p l e t 1 . j av a sav e f i l e n a m e a s a p p l e t 1 . ht m l - - >


<html>
< a p p l e t c o d e = “ a p p l e t 1. cl a ss” wi d t h = 4 0 0 h e i g h t = 3 0 0>
< / a p p l et >
</html>

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 .

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 ) : Returns the v al u e of the sp e c i f i e d


p a r a m e t e r. I t r et u r n s n u l l i f t h e p a r am e t e r i s n o t av ai l a bl e .

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 ) :

color.red c o l o r . wh i t e col or.m agenta col or.li ghtgray


color.green c o l o r . bl a c k c o l o r . y el l o w color.gray
c o l o r . bl u e color.cyan color.orange color.darkgray
c o l o r . pi n k

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 ) :

Graphics Class Methods : T h e G r a p hi c c l a ss c o n t a i n s t h e G r a p h i c s c o n t e x t d e t ai l s


wh i c h i s c o n t a i ni n g t h e f o l l o wi n g m e t h o d s.

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

p u b l i c c l a ss a p p sh a p e s e x t e n d s A p p l e t E:\Core> appletviewer appshapes.html


{
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 . b l a ck ) ;
}
p u b l i c v oi d p ai n t (G r a p h i c s g )
{
D i m e n si o n d = g e t Si z e ( ) ;
i nt w = d . wi d t h ;
i nt h = d. h e i g h t ; cont….

/ / 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 nt y , I m a g e O b se r v e r o b ) : Draw the im age at x,y


v al u e s o n t h e g i v e n I m a g e o b se rv e r .

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

< ! – appimg.html -- >


< a p p l e t c o d e = ' a p p i m g. cl a ss' wi d t h = 3 0 0 h e i g h t = 4 0 0 >
< / a p p l et >

/ / 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 b l i c c l a ss a p p i m g ex t e n d s A p p l e t E:\Core> appletviewer appimg.html


{
Im age im g;

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 B a c k g r o u n d ( C o l o r c o l o r ) : Sets the background col or.

v o i d se t F o r e g r o u n d ( C o l o r c ol o r ) : Sets the f oreground col or.

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 :

add(b1); E:\Core> javac buttontest3.java


add(b2);
E:\Core> appletviewer buttontest3.html
b 1 . a d d A ct i o n Li st e n e r ( n e w C o m m o n 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 C o m m o n H a n d l e r ( ) );
}

/ / 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 )

There are 2 im portant m ethods “

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 :

p u b l i c v oi d i ni t ( ) E:\Core> javac texttest.java


{
t 1 = n e w T ex t F i e l d ( 3 5 ); E:\Core> appletviewer texttest.html
t 2 = n e w T ex t F i e l d ( 3 5 );

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 : ";

m sg = m sg + ( c b 1 . g e t St a t e ( ) = = t r u e ? " C H E C K E D O N " : " C H E C K E D O F F " );


}
e l se i f ( e . g e t S o u r c e ( ) = = c b 2 )
{
m sg = " S e c o n d C h e c k B ox : " ;

m sg = m sg + ( c b 2 . g et S t a t e () = = t r u e ? " C H E C K E D O N " : " C H E C K E D O F F " );


}
sh o wS t a t u s( m sg ) ;
}

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 + ( c b 1 . g e t St a t e ( ) = = t r u e ? " O N " : " O F F " ) ;

m sg = m sg + " S e c o n d C h e c k B ox " ;

m sg = m sg + ( c b 2 . g e t St a t e ( ) = = t r u e ? " O N " : " O F F " ) ;

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

add(opt1); E:\Core> appletviewer radiotest.html


add(opt2);
add(opt3);
add(opt4);
add(opt5);

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 );

Label l1 = new Label();

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 ( ) ;

// get the new col or

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 ) ;

sh o wS t a t u s( " R e d : " + r+ "G r e e n : "+ g + " Bl u e : "+ b ) ;


}

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 wL a y o u t BorderLayout G ri d L a yo u t CardLayout GridBagLayout

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 .

/ / F i l e n am e : flowlay.java Out Put :

i m p o r t j av a. a wt . * ; E:\Core> javac flowlay.java


i m p o r t j av a. a p p l e t . * ;
E:\Core> appletviewer flowlay.html
p u b l i c c l a ss f l o wl 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 . pi n k ) ;
se t F o n t ( n e w F o n t ( "B o o k A n t i q u a " , F o n t . BO L D , 1 6 ) ) ;
se t L a y o u t ( n e w F l o wL a y o u t ( F l o wL a y o u t . R I G H T , 5 , 1 0 ) ) ;
f or ( i nt i = 1; i < = 2 5 ; i + + )
{
add(new Button("Button"+ i ));
}
}
}

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 :

p u b l i c c l a ss b o r d e r l a y ex t e n d s A p p l e t E:\Core> javac borderlay.java


{
S c r ol l b a r s1 = n e w S c r ol l b a r ( Sc r o l l b a r . VER T I C A L ) ; E:\Core> appletviewer borderlay.html
S c r ol l b a r s2 = n e w S c r ol l b a r ( Sc r o l l b a r . VER T I C A L ) ;

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 :

G r i dl a y o u t (i n t r o ws, i n t c o l s, i n t v sp a c e , i n t hsp a se ) : E:\Core> javac gridlay.java

E:\Core> appletviewer gridlay.html


/ / F i l e n am e : gridlay.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 . * ;

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 .

/ / F i l e n am e : p a n e l l a y . j a v a E:\Core> javac panellay.java

E:\Core> appletviewer panellay.html


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 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 ( ) ) ;

add(new Tex tFi el d(25));


add(new Tex tFi el d(25));
add(new Tex tFi el d(25));
}
}

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 " ) ;

CardLayout myLayout = new CardLayout();

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.

They are i. int g r di x ;


ii. int g ri d y ;
iii .i nt g r i d wi d t h ;
iv. int g r i d h ei g h t ;

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 " );

Gri dBagLayout gb = new Gri dBagLayout();

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

p u bl i c v oi d i n i t ( ) E:\Core> appletviewer nulltest.html


{
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 " );

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

c l a ss M y F r am e ex t e n d s F r am e E:\Core> java getfontlist


{
M yF r am e ( ) Supported font names
{ Dialog
se t T i t l e ("f o n t d em o " ) ; SansSerif
S y st em . o u t . p r i nt l n ( "S u p p o r t e d f o n t n am e s " ) ; Serif
Monospaced
T o ol k i t t k = g et T o o l k i t ( ) ;
DialogInput
/ / T o ol Ki t i s av ai l a bl e i n c o n t ai n e r s

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 ( ) ;

MenuBar m bar = new MenuBar();

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 ;

C h e c k b ox M e n u I t em o p t a u t o sav e = n e w C h e c k b o x M e n u I t em ( " A u t o S av e " ) ;

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

o p t o p e n = n e w M e n u I t em (" o p e n " , n e w M e n u S h o r t c u t ( ' O ', t r u e ) );

/ / 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 " );

// add the m enu bar

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 ( ) ;

PopupMenu popup = new PopupMenu();

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

E:\Core> java filetest


Functi ons :

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 ( );

Panel p1 = new Panel();

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.

The following driver will be installed with jdk.

DriverName : JdbcOdbcBridge, which is of the type1 driver. The above driver uses Microsoft ODBC to
connect with the data bases.

Java JdbcOdbcBridge Microsoft Data Base


Application Driver ODBC

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 :

static Class forName( String class-name ) throws ClassNotFoundException

Ex: Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” );


Driver class name

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

1. public static Connection getConnection( String url ) throws SQLException


2. public static Connection getConnection( String url, String uname, String pwd ) throws SQLException
Ex : Connection con = DriverManager.getConnection( “jdbc:odbc:javaoracle”, ”scott”, “tiger” );

“ 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

// File name : testcon.java

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);
}
}
}

Connection Interface : Manages a connection with the database.

Methods :

Statement createStatement( ) throws SQLException : Creates a statement. A statement is used for executing
SQL statements against the database.

PreparedStatement prepareStatement ( String sql statement ) throws SQLException : prepareStatement


takes a query and compiles the query. It can be used for executing any number of times of compiled query.

164 SATEESH N
SATEESH N
CallableStatement prepareCall ( String sql statement ) : Prepares a callable statement, which is used for
executing stored procedures of the database.

void commit( ) : Makes the changes permanent.


void rollback( ) : Moves cursor to the last saved position.
void setAutoCommit( Boolean autocommit ) : Sets on or off the auto commit, default is true.
DatabaseMetaData getMetaData( ) : Returns the DatabaseMetaData which contains the details of the
connection.
void close ( ) : Closes the connection.

Statement : For executing the SQL statements against 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.

ResultSet getResultSet( ) : Returns the result set.

int getUpdateCount( ) : Returns the number of records that are effected in the last execution.

void close( ) : Closes the statement.

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 .

int getInt( String field name ) :

String getString( int fieldno ) :

String getString( String fieldname ) :

Similarly the other get methods are available for the remaining data types.

ResultSetMetaData getMetaData( ) : Returns the ResultSetMetaData, which contains the details of the
resultset.

void close( ) : Closes the result set.

ResultSetMetaData : Contains the results of the result set.

int getColumnCount( ) : Returns the number of selected fields.

String getColumnLabel( int field no ) : Returns the label of the specified column.

165 SATEESH N
SATEESH N
// File name : getrecords.java

// to print the employee details from thel emp table of oracle

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");

// create the statement

Statement stmt = con.createStatement();

// execute the query and get the resultset

ResultSet rs = stmt.executeQuery("select * from emp");

// display the resultset

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();

System.out.print("Enter Query:> ");


String query = stdin.readLine();
// execute the query and get the resultset
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rm = rs.getMetaData();

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);
}

static void displayRecords(ResultSet rs)


{
try
{
int i,n;
ResultSetMetaData rsmd = rs.getMetaData();
n = rsmd.getColumnCount();

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-----------------------------------------");

// display the record values

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.

Statement createStatement( int ResultSetType, int concurrencyType ) throws SQLException :

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 :

1. ResultSet.CONCUR_READ_ONLY : The values in the ResultSet can’t be modified.


2. ResultSet.CONCUR_UPDATABLE : The values in the ResultSet can be modified.

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.

int getRow( ) : Returns the current row number


Ex: int rowNum = rs.getRow();

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

// File name : navigaterecords.java

// to display the employee details in a frame

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];

String fieldNames[] = {"Emp No","EName","Job","Sal","Deptno"};

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());

Panel p1 = new Panel();


Panel p2 = new Panel();

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
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource() == b1)
displayRecord(1);
else if(e.getSource() == b2)
displayRecord(2);
else if(e.getSource() == b3)
displayRecord(3);
else if(e.getSource() == b4)
displayRecord(4);
else if(e.getSource() == b5)
{
closeConnection();
setVisible(false);
System.exit(0);
}
}

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);
}
}

void displayRecord(int opt)


{
// move record pointer according to the pm

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

Making Updates to Updatable Result Sets :

Creating an Updatable Result Set :


Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

Updating a Result Set Programmatically :

An update is the modification of a column value in the current row.

Ex: stmt.executeUpdate("UPDATE EMP SET SAL = 10000 WHERE EMPNO = 7839);

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.

ResultSet rs = stmt.executeQuery(“SELECT * FROM EMP”);

rs.last( );
rs.updateFloat("SAL", 6000);
rs.cancelRowUpdates( );
rs.updateFloat("SAL", 6000);
rs.updateRow( );

Inserting and Deleting Rows Programmatically :

Inserting a Row :

int n = stmt.executeUpdate("insert into emp(empno,ename,job,sal,deptno) values ("+empno+",'"+ename+"',


'"+job+"',"+sal+","+deptno+")" );

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:

rs.absolute(4); // Moves the cursor to the fourth row


rs.deleteRow();

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:

Ex: int level = con.getTransactionIsolation( );


174 SATEESH N
SATEESH N

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();

// File name : insertrecord.java

// 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());

String query = "insert into emp(empno,ename,job,sal,deptno) values


("+empno+",'"+ename+"','"+job+"',"+sal+","+deptno+")";
System.out.println(query);
int n = stmt.executeUpdate(query);

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.

// File name : prepstmt.java

import java.io.*;
import java.sql.*;

class prepstmt
{
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");
PreparedStatement ps = con.prepareStatement("insert into emp(empno,ename,job,sal,deptno) values
(?,?,?,?,?)");
while(true)
{
try
{
System.out.println();
System.out.print("Employee Number: ");
int empno = Integer.parseInt(stdin.readLine());

System.out.print("Employee Name: ");


String ename = stdin.readLine();

System.out.print("Employee Job: ");


String job = stdin.readLine();

System.out.print("Basic Salary: ");


double sal = Double.parseDouble(stdin.readLine());

System.out.print("Department No: ");


int deptno = Integer.parseInt(stdin.readLine());

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);
}

System.out.print("Any more Records [y/n]: ");

String str = stdin.readLine().toUpperCase();

if(str.startsWith("N"))
break;
}
ps.close();
con.close();
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}

Using a Loop to Set Values :

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.

// 1. File name : getnetamt.sql

SQL> Create or Replace Function


getnetamt(qty in Number,rate in Number)
return Number
Is
tamt number(12,2);
tdisc number(12,2);
tnet number(12,2);
Begin
tamt:= qty * rate;

if tamt >= 5000 then


tdisc:=(tamt * 10)/100;
else
tdisc:=(tamt * 5)/100;
end if;

tnet:= tamt - tdisc;

return tnet;
end;

// 2. File name : calstmt.java

// 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);

System.out.println("Enter Qty purchased: ");


int qty = Integer.parseInt(stdin.readLine());

System.out.println("Enter Rate per unit: ");


rate = Double.parseDouble(stdin.readLine());

cs.setInt(2,qty);
cs.setDouble(3,rate);

cs.execute(); // call the oracle function getnetamt

net = cs.getDouble(1); // 1st parameter


System.out.println("----------------------------------------");
System.out.println("Net Amount: "+net);
cs.close();
}
catch(Exception ex)
{
//System.out.println("Error: "+ex);

ex.printStackTrace();
}

System.out.print("Any more Data [y/n]: ");

String str = stdin.readLine().toUpperCase().trim();

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");

Connection dbCon = DriverManager.getConnection ("jdbc:oracle:thin:@orasrv:1521:miracle",


"scott","tiger");
dbCon.setAutoCommit(false);

Statement stmt= dbCon.createStatement();

stmt.addBatch("INSERT INTO student VALUES (111, 'SANJU', 'MRN')");


stmt.addBatch("INSERT INTO student VALUES (555, 'USHA’, 'GRD')");
stmt.addBatch("INSERT INTO student VALUES (666, 'SATEESH’, 'GWK')");

try
{
int[] updCnt = stmt.executeBatch( );
}
catch(Exception ex)
{
ex.printStackTrace();
}

dbCon.commit( );

stmt.close();
dbCon.close();

}
catch (BatchUpdateException be)
{
//handle batch update exception

int[] counts = be.getUpdateCounts();

for (int i=0; i<counts.length; i++)


{
System.out.println("Statement["+i+"] :"+counts[i]);
}
}

}
}

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.

// File name: buttontest.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class buttontest extends JApplet implements ActionListener


{
JButton b1,b2;

public void init()


{ E:\adv\swings>javac buttontest.java
b1 = new JButton("First Button"); E:\adv\swings>appleviewer buttontest.html
b2 = new JButton("Second Button");

Container c = getContentPane( );

c.setLayout(new FlowLayout( ));

c.add(b1);
c.add(b2);

b1.addActionListener(this);
b2.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource( ) == b1)
showStatus("First Button Clicked");
else if(e.getSource( ) == b2)
showStatus("Clicked on Second Button");
}
}

File name: buttontest.html

<applet code='buttontest.class' width=500 height=200>


</applet>

181 SATEESH N
SATEESH N

// File name: frametest.java

// changing the LookAndFeel

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class frametest


{
public static void main(String args[ ])
{
MyFrame f = new MyFrame( );
f.setBounds(100,100,300,200);
f.setVisible(true);
f.setTitle("Sample Frame");
}
}
class MyFrame extends JFrame implements ActionListener,ItemListener
{
JTextField t1,t2;
JButton b1,b2;
JCheckBox cb1;
JComboBox courses;
Container c;

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

t1 = new JTextField(25); E:\adv\swings>java frametest


t2 = new JTextField(25);

b1 = new JButton("Copy Dwon");


b2 = new JButton("Copy Up");

cb1 = new JCheckBox("Sample CheckBox");

courses = new JComboBox();

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");
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource() == b1 || e.getSource() == t1)
{
t2.setText(t1.getText());
t1.setText("");
t2.requestFocus();
}
else if(e.getSource() ==b2 || e.getSource() == t2)
{
t1.setText(t2.getText());
t2.setText("");
t1.requestFocus();
}
}

public void itemStateChanged(ItemEvent e)


{
if(cb1.isSelected() == true)
{
JOptionPane.showMessageDialog(null,"CheckBox CHECKED ON");
}
else
{
JOptionPane.showMessageDialog(null,"CheckBox CHECKED OFF");
}
}
}

Change the LookAndFeel :

UIManager.setLookAndFeel( “ com.sun.java.swing.plaf.windows.WindowsLookAndFeel “ );

UIManager.setLookAndFeel( “ com.sun.java.swing.plaf.motif.MotifLookAndFeel “ );

JScrollPane : Provides scrolling effect for the given component.

Ex: JScrollPane( Component c, int vsp, int hsp )

vsp : Vertical Scrollbar Policy


hsp : Horizontal Scrollbar Policy

183 SATEESH N
SATEESH N
vsp :

1. JScrollPane.VERTICAL_SCROLLBAR_NEVER : Hides the scrollbar.


2. JScrollPane.VERTICAL_SCROLLBAR_ALWAYS : The scrollbar will always be displayed.
3. JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED : Scrollbar will be displayed depending on
the requirement.

hsp :

1. JScrollPane.HORIZONTAL_SCROLLBAR_NEVER : Hides the scrollbar.


2. JScrollPane. HORIZONTAL_SCROLLBAR_ALWAYS : The scrollbar will always be displayed.
3. JScrollPane. HORIZONTAL _SCROLLBAR_AS_NEEDED : Scrollbar will be displayed depending
on the requirement.

JTree : JTree is used for displaying the information in a hierarchical format.

JTree( TreeNode root) :

The TreeNode is an interface that can contain text and subnodes also. To create a node the following
class can be used.

DefaultMutableTreeNode :

// File name : treetest1.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;

public class treetest1 extends JFrame


{
JTree tree;
JScrollPane jsp;

int vsp = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED;


int hsp = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED;

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");
}

root = new DefaultMutableTreeNode("Details");


lang = new DefaultMutableTreeNode("Languages");
pack = new DefaultMutableTreeNode("Packages");
root.add(lang);
root.add(pack);

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);
}

public static void main(String args[])


{
Frame f = new treetest1( );
f.setBounds(50,50,300,200);
f.setTitle("Tree Test1");
f.setVisible(true);
}
}

// File name : emptree.java


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.sql.*;

class emptree
{
public static void main(String args[])
{
MyFrame f = new MyFrame();
f.setBounds(100,100,400,500);
f.setVisible(true);
}
}

class MyFrame extends JFrame


{
JTree tree;
DefaultMutableTreeNode root;
JScrollPane jsp;
Container c;

int vsp = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED;


int hsp = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED;

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();

tree = new JTree(root);

jsp = new JScrollPane(tree,vsp,hsp);

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");

root = new DefaultMutableTreeNode("Employee Details");

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);

DefaultMutableTreeNode empNode = new DefaultMutableTreeNode(String.valueOf(empno));


empNode.add(new DefaultMutableTreeNode("Empno: "+empno));
empNode.add(new DefaultMutableTreeNode("Ename: "+ename));
empNode.add(new DefaultMutableTreeNode("JOB : "+job));
empNode.add(new DefaultMutableTreeNode("SAL : "+sal));
empNode.add(new DefaultMutableTreeNode("Dept : "+deptno));

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.

“ JTable “ can be added to “JScrollPane” for Scrolling effect.

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 :

Vector( ) : creates a vector.

void add( object obj ) : Adds the object to the list.

void Remove( object obj ) : Removes the object from the list.

int size( ) : Returns the number of elements in 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.

// File name : tabletest.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.Vector;

public class tabletest


{
public static void main(String args[])
{
MyFrame f = new MyFrame();
f.setTitle("Query Frame");
f.setBounds(50,50,350,200);
f.setVisible(true);
}
}

class MyFrame extends JFrame implements ActionListener


{
JLabel l1;
JTextArea query;
JPanel p1;
JButton b1,b2;
Container c;
Connection con;
Statement stmt;

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);
}
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource() == b1)
showData();
else if(e.getSource() == b2)
{
closeConnection();
System.exit(0);
}
}
189 SATEESH N
SATEESH N

void showData()
{
try
{
String str = query.getText().trim();
ResultSet rs = stmt.executeQuery(str);
ResultSetMetaData rsmd = rs.getMetaData();

int i,n;

n = rsmd.getColumnCount();

Vector heads = new Vector();


Vector rowData = new Vector();

// Getting Headings into the 1st vector

for(i=1;i<=n;i++)
{
heads.add(rsmd.getColumnLabel(i));
}

// Getting Data into the rowData

while(rs.next())
{
Vector curRow = new Vector();

for(i=1;i<=n;i++)
{
curRow.add(rs.getString(i));
}

// Add the current row to the row data

rowData.add(curRow);
}

DisplayFrame f = new DisplayFrame(rowData,heads);

f.setBounds(50,50,600,300);
f.setTitle(str);
f.setVisible(true);
rs.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Cannot execute query");
}
}
}

class DisplayFrame extends JFrame


{
JScrollPane jsp;
JTable table;
Container c;

int vsp = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED;


int hsp = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED;
190 SATEESH N
SATEESH N

DisplayFrame(Vector rowData,Vector heads)


{
c = getContentPane();
table = new JTable(rowData,heads);
table.setFont(new Font("SanSerif",Font.BOLD,14));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

jsp = new JScrollPane(table,vsp,hsp);

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

User Name ServerSideProgram


Password Yahoo
WEB Server
Login

checkmail

Particular ID’s Mail Box Documents


delete will be opened

The following are the famous WEB servers :

IIS (Internet Information Serverm )  MircroSoft  supports ASP


PWS ( Personal WEB Server )  MircroSoft  supports ASP
Apache  Apache  only for HTML
Tomcat  Jakarta  supports servlets,,jsp, tomcat doesn’t supports for EJB.
http://apache.jakarta.org
Java Web Server 
J2EE 
Weblogic  BEA
Websphere  IBM
JRun 
JBoss  etc.,

Methods of sending data :

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.

GET Environment variables


POST Streams
HEAD Commandline arguments
192 SATEESH N
SATEESH N

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.

1. All the fields will be separated by & symbol.


2. Each field contains the name of the field and the value of the field separated by = symbol.
3. All spaces will be converted to + symbols.
4. All special characters such as +, & etc., will be converted to hexadecimal values prefixed with %
symbol.

Ex: http://myserver.com/SSPname?Empno=101&Ename=abc+xyz&Job=clk%xxAcc

Server ssp param1 value1 p2 v2 p3 v3

In Java the SSPs can be written in sevlets and jsp.

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 :

DoGet( ) : public void doGet(HttpServletRequest, HttpServletResponse) throws ServletException,IO Exception

DoPost( ):public void doPost(HttpServletRequest,HttpServletResponse) throws ServletException,IO Exception

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

user name : request


password : WEB Server Server Side Program
Login
response
193 SATEESH N
SATEESH N
HttpServletRequest : For receiving input from the WebBrowser.

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.

HttpSession getSession( ) : Returns the current HttpSession.

HttpServletResponse : For sending output to the WebBrowser.

Methods :

void setContentType(String mimeType) : Sets the content type as mime type.


MIME(Multipurpose Internet Mail Extension )

Mime Types : text/html text/plain image/gif

PrintWriter getWriter( ) : Returns the output stream for sending the output to the WebBrowser.

void addCookie(Cookie ck) : Sends a cookie to the WebBrowser.

// w.a.Servlet to send the text to WebBrowser.

// File name : firstservlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class firstservlet extends HttpServlet


{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,
IOException
{
// send the output to the webbrowser
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY bgcolor=#0086b2 text=white>");
out.println("<H1 align =center>Welcome to Servlet Programming</H1>");
out.println("<HR size=5 color=black>");
out.println("<H3> First Servlet Program</H3>");
out.println("</BODY>");
out.println("</HTML>");
}
}

194 SATEESH N
SATEESH N
// w.a.servlet to send employee details to the WebBrowser.

// File name : getempdetservlet.java

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");

Statement stmt = con.createStatement();


ResultSet rs = stmt.executeQuery("select empno,ename,job,sal,deptno from emp");

//constructing table format


out.println("<table width=100% bgcolor=pink border=2 bordercolor=red cellspacing=0>");
out.println("<tr>");
out.println("<th>Employee Number</th>");
out.println("<th>Employee Name</th>");
out.println("<th>JOB</th>");
out.println("<th>Salary</th>");
out.println("<th>Department No.</th>");
out.println("</tr>");

// placing the records into table


while(rs.next())
{
out.println("<tr>");
for(int i=1;i<=5;i++)
{
out.println("<td>"+rs.getString(i)+"</td>");
}
out.println("</tr>");
}
out.println("</table>");
rs.close();
stmt.close();
con.close();
}
catch(Exception ex)
{
out.println("<br> Error: "+ex);
}
out.println("</body></html>");
}
}
195 SATEESH N
SATEESH N

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.

Name : form name

Method : GET || POST

Action : The name of the server side program for processing the data.

Elements : One or more input fields.

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.

// File name : iptoservletoptowb.html

<!-- 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>

// File name : iptoservletoptowb.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class iptoservletoptowb extends HttpServlet


{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");

// read data from the request

String p1 = request.getParameter("EMPNO");
String p2 = request.getParameter("ENAME");
String p3 = request.getParameter("JOB");

// send the received details to the client

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>

// File name: findempservlet.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class findempservlet extends HttpServlet


{
static Connection con;
static PreparedStatement ps;

public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,


IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");

// Receive the employee number

int empno = Integer.parseInt(request.getParameter("EMPNO"));

// Get the record


try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:javaoralce","scott","tiger");
ps = con.prepareStatement("select empno,ename,job,sal,deptno from emp where empno=?");

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>

<form name = EMPFORM method=GET action='http://localhost:8080/satclass/servlet/saveempservlet'>

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>

// File name: saveempservlet.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

198 SATEESH N
SATEESH N

public class saveempservlet extends HttpServlet


{
static Connection con;
static PreparedStatement ps;

public void doGet(HttpServletRequest request,HttpServletResponse response)throws


ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");

try
{
// Receive the employee details

int empno = Integer.parseInt(request.getParameter("EMPNO"));


String ename = request.getParameter("ENAME");
String job = request.getParameter("JOB");
double sal = Double.parseDouble(request.getParameter("SAL"));
int deptno = Integer.parseInt(request.getParameter("DEPTNO"));

// open the connection

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.

Sessin management can achieve in three different ways.

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.

// File name: nextempservlet.java

// using hidden variables

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class nextempservlet extends HttpServlet


{
static Connection con = null;

public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,


IOException
{
response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html> <body> <h2> Employee Record </h2>");

int rno = 0;

String RNO = request.getParameter("RNO");

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 = ?");

PreparedStatement ps = con.prepareStatement("select sno,sname,saddr from student where sno = ?");

ps.setInt(1,rno);

ResultSet rs = ps.executeQuery();

if( rs.next() )
{
out.println(" <h3> Record Found: " +rno+ "</h3> ");

// out.println(" <br> Employee Number: " +rs.getString(1) );


// out.println(" <br> Employee Name : " +rs.getString(2) );
// out.println(" <br> Employee Job : " +rs.getString(3) );
// out.println(" <br> Basic Salary : " +rs.getString(4) );
// out.println(" <br> Department No. : " +rs.getString(5) );

out.println(" <br> Student Number : " +rs.getString(1) );


out.println(" <br> Student Name : " +rs.getString(2) );
out.println(" <br> Student Address: " +rs.getString(3) );

}
else
{
out.println(" <h3> Record Not Found: " +rno+ "</h3> ");
}

rs.close();
ps.close();
}
catch(Exception ex)
{
out.println(" <br> Error: "+ex);
}

// send the latest rno from the webserver to webbrowser

out.println(" <hr size = 5 color = red> ");


out.println(" <form name=EMPFORM method=GET action='http://localhost:8080/satclass/servlet/
nextempservlet'> ");
out.println(" <input type=Hidden name=RNO value="+rno+"> ");
out.println(" <input type=Submit value='Next Record'> ");
out.println("</form>");
out.println("</body></html>");
}

void openConnection()throws SQLException


{
try
{
System.out.println("Getting Connection....");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
}
catch(ClassNotFoundException ex)
{
throw new SQLException("Driver Class Not Found");
}
201 SATEESH N
SATEESH N
catch(SQLException ex)
{
throw 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.,

Cookie(String name, String value) :

String getValue( ) :

void setValue(String value) :

Sending a cookie to the WebBrowser :

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.

Receiving the Cookies from the WebBrowser :

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.*;

public class nextempservlet2 extends HttpServlet


{
static Connection con = null;

public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,


IOException
{
response.setContentType("text/html");

202 SATEESH N
SATEESH N
PrintWriter out = response.getWriter();

out.println("<html> <body> <h2> Employee Record </h2>");

int rno = 0;

Cookie arr[] = request.getCookies();

// find the cookie with the name "RNO"

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++;

// send the record of "rno" to "out"

sendRecord(rno,out);

// send the latest cookie to the webbrowser

Cookie ck = new Cookie("RNO",String.valueOf(rno));

response.addCookie(ck);

out.println(" <hr size = 5 color = red> ");

out.println(" <a href='http://localhost:8080/satclass/servlet/nextempservlet2'> Next Employee Record </a> ");

out.println(" </body> </html> ");


}

void sendRecord(int rno,PrintWriter out)throws IOException


{
try
{
if(con==null)
{
System.out.println("Getting Connection .....");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
}

// PreparedStatement ps = con.prepareStatement("select empno,ename,job,sal,deptno from emp where


empno = ?");

PreparedStatement ps = con.prepareStatement("select sno,sname,saddr from student where sno = ?");

ps.setInt(1,rno);

ResultSet rs = ps.executeQuery();

203 SATEESH N
SATEESH N
if( rs.next() )
{
out.println(" <h3> Record Found: " +rno+ "</h3> ");

// out.println(" <br> Employee Number: " +rs.getString(1) );


// out.println(" <br> Employee Name : " +rs.getString(2) );
// out.println(" <br> Employee Job : " +rs.getString(3) );
// out.println(" <br> Basic Salary : " +rs.getString(4) );
// out.println(" <br> Department No. : " +rs.getString(5) );

out.println(" <br> Student Number : " +rs.getString(1) );


out.println(" <br> Student Name : " +rs.getString(2) );
out.println(" <br> Student Address: " +rs.getString(3) );

}
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.

<%

// java statements script let

%>

// File name: test.jsp

<!--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;

out.println(" <br> Total is: "+c );


int empno = b;
String ename = "abc";
%>

<hr>
Total is: <%= c %>
<hr>
Employee Number: <%= empno %> <br>
Employee Name : <%= ename %> <br>
</body>
</html>

Every “ jsp ” program contains the following objects by default.

out : PrintWriter

request : HttpServletRequest

response : HttpServletResponse

205 SATEESH N
SATEESH N
session : HttpSession

page : this

application : ServletContext

in : BufferedReader

// w.a.jsp program which sends the employee details in a table format.

<!-- getempdet.jsp -->

<%@ page import = "java.sql.*" %>

<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");
%>

<table width=100% bgcolor=pink border=2 bordercolor=blue cellspacing=0>


<tr>
<th> Empno </th>
<th> Ename </th>
<th> Job </th>
<th> Salary</th>
<th> Deptno</th>
</tr>

<%
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>

// File name: empecho.jsp

<!-- empecho.jsp -->

<%@ page errorPage = "error.jsp"%>


<html>
<body>
<h2> Received Details </h2>
<%
int empno=Integer.parseInt(request.getParameter("empno"));
String ename = request.getParameter("ename");
String job = request.getParameter("job");
int sal = Integer.parseInt(request.getParameter("sal"));
int deptno = Integer.parseInt(request.getParameter("deptno"));
%>
<br> Employee Number: <%= empno %>
<br> Employee Name : <%= ename %>
<br> Employee Job : <%= job %>
<br> Employee Salary: <%= sal %>
<br> Department No. : <%= deptno %>
<hr size=5 color=red>
<a href='empecho.html'> Another Record </a>
</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>

// File name: findemp.jsp

<!-- findemp.jsp -->

<%@ page import = "java.sql.*" %>


<html>
<body>
<h2> Employee Details </h2>
<%
try
{
int empno=Integer.parseInt(request.getParameter("EMPNO"));
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
PreparedStatement ps = con.prepareStatement("select empno,ename,job,sal,deptno from emp where
empno=?");
ps.setInt(1,empno);
ResultSet rs = ps.executeQuery();
if(rs.next())
{
%>
<h3> Record Found </h3>
<br> Employee Number: <%=rs.getString(1)%>
<br> Employee Name : <%=rs.getString(2)%>
<br> Employee Job : <%=rs.getString(3)%>
<br> Employee Salary: <%=rs.getString(4)%>
<br> Department No. : <%=rs.getString(5)%>
<%
}
else
{
out.println("<h3> Record Not Found </h3>");
}
rs.close();
ps.close();
con.close();
}
catch(Exception ex)
{
out.println("Error: "+ex);
}
%>
<hr size=5 color=red>
<a href='findemp.html'>Find Another Record</a>
</body>
</html>
208 SATEESH N
SATEESH N

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.

<!-- error.jsp -->

<% @ Page is ErrorPage = "true" %>

<html>
<body>
<h2 style='background-color:blue;color:white;text-align:center'>

<h3> Error: <%=exception.getMessage()%></h3>


<br>
Error: <%=Exception.toString()%>
</body>
</html>

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.

To create a “ bean “, create a “ class “ that follows the “ bean specification “.

i. Every java bean is a java class


ii. The bean must be placed in a package
iii. The bean should contain a zero argument constructor
iv. Provide the set and get methods for accessing the data members of the bean

In servlets and jsp’s all the beans must be created in the driveletter:\tomcat\webapps\virtual directory
name\WEB-INF\classes sub directory.

Using a bean in a jsp program :

To use a bean in a jsp program the “jsp: useBean” directory should be applied.

Ex: <jsp:useBean id=”emp” class”emp.employee” scope=”session”/>

The above ex. Will perform the following action

employee emp;
emp = new employee();

The scope can be one among the following.

Application : For all the clients only one instance of the bean will be created and the bean will be created on
the server.

Session : For each client a separate bean will be created.

Request : For each request a bean will be created.

Page : For each page a bean will be created.

209 SATEESH N
SATEESH N

Page : Request :
Bean ex2.jsp ex2.jsp
Bean

Bean ex1.jsp ex1.jsp

server server

User1 User2 User n User1 User2 User n

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

User1 User2 User n User1 User2 User n

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.

// File name: ConnectionException.java

package mycon;

import java.sql.*;

public class ConnectionException extends Exception


{
String msg;

public ConnectionException()
{
msg = "Connection Exception occurred";
}

210 SATEESH N
SATEESH N
public ConnectionException(String msg)
{
this.msg = msg;
}

public String toString()


{
return msg;
}
}

// File name: mycon.java

package mycon;

import java.sql.*;

public class mycon


{
Connection con;

public mycon()
{
con = null;
}

void openConnection() throws ConnectionException


{
try
{
System.out.println("Getting connection....");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
}
catch(Exception ex)
{
throw new ConnectionException("Cannot Establish Connection");
}
}

public Statement createStatement() throws ConnectionException


{
try
{
if(con == null)
openConnection();
return con.createStatement();
}
catch(Exception ex)
{
throw new ConnectionException(ex.toString());
}
}

public PreparedStatement prepareStatement(String sql) throws ConnectionException


{
try
{
if(con == null)
openConnection();
211 SATEESH N
SATEESH N
return con.prepareStatement(sql);
}
catch(Exception ex)
{
throw new ConnectionException(ex.toString());
}
}
}

// File name: empusebean.jsp

<!-- empusebean.jsp -->

<%@ page import = "java.sql.*" %>


<%@ page errorPage = "error.jsp" %>
<jsp:useBean id="con" class="mycon.mycon" scope="application"/>
<html>
<head>
<title>
Employee Details
</title>
</head>
<body>
<h2 style='background-color:blue;color:white;text-align:center'>
Employee Details
</h2>
<%
ResultSet rs=null;
Statement stmt=null;
try
{
stmt = con.createStatement();
rs= stmt.executeQuery("select empno,ename,job,sal,deptno from emp");
}

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>

// write the following set of programs 1. DisplayAllEmployees.jsp


2. DisplaySelectedEmployee.jsp
3. UpdateEmployee.jsp

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.

// File name: DisplayAllEmployees.jsp

<!-- DiplayAllEmployees.jsp-->

<%@ page import = "java.sql.*" %>


<%@ page errorPage = "error.jsp" %>

<jsp:useBean id="con" class="mycon.mycon" scope="application"/>

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>

// File name: DisplaySelectedEmployee.jsp

<!-- DisplaySelectedEmplee.jsp -->

<%@ page import = "java.sql.*" %>


<%@ page errorPage = "error.jsp" %>

<jsp:useBean id = "con" class="mycon.mycon" scope="application" />

<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

// File name: UpdateEmployee.jsp

<!-- UpdateEmployee.jsp -->

<%@ page import = "java.sql.*" %>


<%@ page errorPage = "error.jsp" %>

<jsp:useBean id = "con" class="mycon.mycon" scope="application" />


<html>
<body link=blue vlink=green alink=red>
<h2 style='background-color:blue;color:white;text-align:center'>
Updated Employee Details
</h2>
<%
int empno = Integer.parseInt(request.getParameter("EMPNO"));
String ename = request.getParameter("ENAME");
String job = request.getParameter("JOB");
double sal= Double.parseDouble(request.getParameter("SAL"));
int deptno = Integer.parseInt(request.getParameter("DEPTNO"));
ResultSet rs = null;
PreparedStatement ps =null;
PreparedStatement pss =null;
try
{
ps = con.prepareStatement("update emp set job=?,sal=?,deptno=? where empno=?");
ps.setString(1,job);
ps.setDouble(2,sal);
ps.setInt(3,deptno);
ps.setInt(4,empno);
ps.executeUpdate();

pss = con.prepareStatement("select empno,ename,job,sal,deptno from emp where empno=?");


pss.setInt(1,empno);
rs = pss.executeQuery();
}
catch(Exception e)
{
%>
<%=e%>
<%
}

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();
%>

<hr size=5 color = red>


<a href='DisplayAllEmployees.jsp'> All Employee Details </a>
</body>
</html>

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 :

String getId( ) : Returns the session ID.

void setAttribute(String name, Object obj ) : Adds an object to the session.

void getAttribute(String name) : Retrieves the value from the session.

Integer( int val ) : It is a class to store the integer value.

int intValue( ) : It is a function to retrieve the value.


217 SATEESH N
SATEESH N

// File name: Nextemp.jsp

<!-- Nextemp.jsp -->

<%@ page import = "java.sql.*" %>


<%@ page errorPage = "error.jsp" %>
<jsp:useBean id="con" class="mycon.mycon" scope="application"/>
<html>
<body>
<h2 style='background-color:blue;color:white;text-align:center'>
Employee Details
</h2>
<%
int rno = 0;
Integer integer = (Integer)session.getAttribute("RNO");
if(integer != null)
{
rno = integer.intValue();
}
rno++;

// put the latest value into the session

integer = new Integer(rno);


session.setAttribute("RNO",integer);

// Retrieve the record for rno

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
{

out.println("<h3> Record Not Found !</h3>");


}
rs.close();
ps.close();
%>
<hr size=5 color=red>
<a href='Nextemp.jsp'>Next Employee Record</a>
</body>
</html>

// File name: NavigateRecords.jsp

<!-- NavigateRecords.jsp -->

<%@ page import = "java.sql.*" %>


<%@ page errorPage = "error.jsp" %>

<jsp:useBean id="con" class="mycon.mycon" scope="application"/>

<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
}

// put the latest value RNO into the session


session.setAttribute("RNO",String.valueOf(rno));
// Get the record and display it
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>

<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>

// w.an application using setProperty

1. UserData.java
2. GetData.jsp
3. SaveName.jsp
4. NextPage.jsp

// File name : UserData.java

package mycon;

public class UserData


{
String username;
String email;
int age;

public void setUsername( String value )


{
username = value;
}

public void setEmail( String value )


{
email = value;
}

public void setAge( int value )


{
age = value;
}

public String getUsername()


{
return username;
}
221 SATEESH N
SATEESH N

public String getEmail()


{
return email;
}

public int getAge()


{
return age;
}
}

// File name: GetName.jsp

<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>

// File name: SaveName.jsp

<jsp:useBean id="user" class="mycon.UserData" scope="application" />


<jsp:setProperty name="user" property="*"/>
<html>
<body>
<a href="NextPage.jsp">Continue</a>
</body>
</html>

// File name: NextPage.jsp

<jsp:useBean id="user" class="mycon.UserData" scope="application"/>


<html>
<body>
You entered <br>
Name: <%= user.getUsername() %> <br>
Email: <%= user.getEmail() %> <br>
Age: <%= user.getAge() %> <br>
</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.

For any custom tags 2 types of programs are required.

.tld : ( Tag Library Discriptor )


.jar : ( Java Archieve Files )

The tld file contains the names of the tags and their params that can be applied in JSP programs.

The jar file contains the tag classes.

Whenever a custom tag was used in a jsp program the corresponding tag class will be called from the
jar file.

The JSTL package is containing the following files.

Tlds : c.tld fmt.tld sql.tld x.tld

Jars : standard.jar jstl.jar

The c.tld contains the core tags such as if,out,choose,forEach etc.,


The fmt.tld contains the tags for formatting, date data etc.,
The sql.tld contains the tags for sql access etc.,
The x.tld contains the tags for xml access etc.,

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.

The following objects can be available in jstl.

param, session, request, page etc.,

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.

Syntax : <c:set var=”variable name” value=”val” />

Ex : <c:set var=”start” value=”10” />

if: The following parameters should be given

Syntax : <c:if test = “condition” >

Ex: <c:if test=”${start == 10}”>

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 :

Ex: <c:forEach var=”i” items=”10,20,30,40,50”>

Ex : <c:forEach vari=”i” begin=”10” end=”25” step=”2”>

catch : Executes statement in a try block. If any exception occurs it will be stored in a given variable.

Ex: <c:catch var=”ex”>


// statement(s);
</c:catch>

fmt : The following tag of fmt.tld is used for formatting numbers.

Ex: <fmt:formatNumber value=”${param.tfee}” pattern=”##,##0.00” />

<!-- jstlc1.jsp -->


<%@ taglib uri="/WEB-INF/tlds/c.tld" prefix="c" %>

<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

<!-- jstlc2.jsp -->

<%@ taglib uri="/WEB-INF/tlds/c.tld" prefix="c" %>

<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>

<!-- empecho.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>

<!-- jstlc3.jsp -->

<%@ taglib uri="/WEB-INF/tlds/c.tld" prefix="c" %>

<html>
<body>

<h2> Received Employee Details </h2>


<form action="">
Employee Number:
<c:out value="${param.empno}" default="- - -" /> <br>
Employee Name:
<c:out value="${param.ename}" default="- - -" /> <br>
Job:
<c:out value="${param.job}" default="- - -" /> <br>
Salary :
<c:out value="${param.sal}" default="- - -" /> <br>
Department no.:
<c:out value="${param.deptno}" default="- - -" /> <br>
</form>
<br>
</body>
</html>

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>

<!-- jstlc5.jsp -->

<%@ taglib uri='/WEB-INF/tlds/c.tld' prefix="c" %>

<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>

<!-- jstlc6.jsp -->

<%@ taglib uri='/WEB-INF/tlds/c.tld' prefix="c" %>

<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 -->

<%@ taglib uri='/WEB-INF/tlds/c.tld' prefix="c" %>

<html>
<body>

<c:set var="ch" value="3"/>

<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>

<!-- jstlc8.jsp -->

<%@ taglib uri='WEB-INF/tlds/c.tld' prefix="c" %>

<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>

<!-- jstlf1.jsp -->

<%@ taglib uri='/WEB-INF/tlds/fmt.tld' prefix="fmt" %>


<%@ taglib uri='/WEB-INF/tlds/c.tld' prefix="c" %>
<html>
</body>
<c:set var="n" value="1023" />
Format number :
<fmt:formatNumber value="${n}" pattern="##,##0.00"/> <br> <br>
<c:out value="${n}" />
</c:forEach>
</body>
</html>

227 SATEESH N
SATEESH N

<!-- studandemp.html -->

<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>

<!-- exjstl.jsp -->

<%@ taglib uri='/WEB-INF/tlds/c.tld' prefix="c" %>

<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>

<!-- studjstl.jsp -->

<%@ taglib uri="/WEB-INF/tlds/c.tld" prefix="c" %>

<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>

<!-- empjstl.jsp -->

<%@ taglib uri="/WEB-INF/tlds/c.tld" prefix="c" %>

<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

Java & RMI Java & RMI


System System

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.

Steps for designing the RMI program :

1. Define the Remote Interface.


2. Create the implementation class.
3. Generate the stub and skeletons.
4. Design the server program.
5. Design the client program.

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.

Ex: public interface account extends Remote


{
public int getAccno( ) throws RemoteException;
public void deposit(double int) throws RemoteException;
}
231 SATEESH N
SATEESH N
2. Create a implementation class : The implementation class contain the definition of the remote method,
create a class that extends UnicastRemoteObject and implements the interface of the step1 and overrides all
its methods. The class should also contain a constructor that also throws RemoteException.

Ex: public class accountimpl extends UnicastRemoteObject implements account


{
int accno;
double balance;
public accountimpl( ) throws RemoteException
{
accno = 101;
balance = 5000;
}

// overriding Remote interface methods

public int getAccno( ) throws RemoteException


{
return accno;
}

public void deposit( doublel amt ) throws RemoteException


{
balance + = amt;
}
}

3. Generate the stub and skeletons : Compile the implementation class using the rmi compiler rmic.
Ex: e:\adv\rmi> rmic accountimpl

// Reads accountimpl class and produces

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.

Ex: class server


{
public static void main( String args[ ] )
{
accountimpl a1 = new accountimpl( 101, 5000 ) ;
accountimpl a2 = new accountimpl( 102, 3000 ) ;
Naming.bind( “First Account”, a1 );
Naming.bind(“ Second Account”, a2 );
}
}

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.

Ex: class client


{
public static void main( String args[ ] )
{
// Find the remote objects
account r = Naming.lookup( “rmi://myserver/firstaccount” );
r.deposit(2000); // Remote method
r = Naming.lookup( “rmi://myserver/secondaccount” );
r.deposit(3000);
}
}

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.

The RMI Architecture

[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.

The Transport Layer

At the present time this is the standard TCP layer on IP.

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.

Stub and Skeleton Layer

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.

Responsibilities of the stub

The client side stub representing a remote object does the following:

 initiating remote calls


 marshaling arguments to be sent
 informing the remote reference layer that a call should be invoked on the server
 unmarshalling a return value (or exception)
 informing the remote reference layer that the call is complete

Responsibities of the skeleton

On the server, the skeleton,

 unmarshals incoming arguments


 calling the actual remote object implementation
 marshaling return values for transport to the client

Remote vs. Local Method Invocation

Local method invocation

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.

Remote method invocation

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.)

The RMI Registry

How does a client find a remote object that it wishes to invoke?


RMI provides a simple name server called rmiregistry. This runs on the same host as the RMI server.
Each object on the server host which which wishes to publicize its remotely accessible methods registereds by
name on the registry.
Client programs lookup the registered name on the server and get a reference to the remote object in return.
They use that reference to invoke the remotely accessible methods of the server object.
Name clashes
The RMI registry is quite simple. There is no way provided to guarantee that the same name will not be
registered twice. This is not a problem on small programs. Sometimes the registry is referred to as a
"boostrap" registry because, strictly speaking, it is only necessary for a first contact between client and server.
Once client and server are in touch, they can access each other without the help of the registry.

// Example RMI program

// File name: account.java

// 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.*;

public interface account extends Remote


{
public int getAccno() throws RemoteException;
public String getAccname() throws RemoteException;
public double getBalance() throws RemoteException;
public void deposit(double amt) throws RemoteException;
public void withdraw(double amt) throws RemoteException;
}

235 SATEESH N
SATEESH N

// File name: accountimpl.java

import java.rmi.*;
import java.rmi.server.*;

public class accountimpl extends UnicastRemoteObject implements account


{
int accno;
String accname;
double balance; // current balance

public accountimpl(int accno, String accname, double opeBalance)throws RemoteException


{
this.accno = accno;
this.accname = accname;
this.balance = opeBalance;
System.out.println("Account: "+accno+" Created");
}

// Overriding Remote Interface Methods: 5

public int getAccno() throws RemoteException


{
return accno;
}

public String getAccname()throws RemoteException


{
return accname;
}

public double getBalance()throws RemoteException


{
return balance;
}

public void deposit(double amt)throws RemoteException


{
balance +=amt;
System.out.println("Deposited: "+amt+" into Accno: "+accno);
}

public void withdraw(double amt)throws RemoteException


{
if(amt>balance)
throw new RemoteException("Insufficient Funds");
balance -=amt;
System.out.println("Withdrawn: "+amt+" into Accno: "+accno);
}
}

236 SATEESH N
SATEESH N

// File name: accountserver.java

//server program,to place 3 accounts which can be accessible from Remote location

import java.rmi.*;

public class accountserver


{
public static void main(String args[])
{
try
{
System.out.println("starting Server....");

// creating 3 accounts

accountimpl acc1 = new accountimpl(101,"Sateesh N",25000);


accountimpl acc2 = new accountimpl(102,"Sateesh M",5000);
accountimpl acc3 = new accountimpl(103,"Sateesh S",10000);

System.out.println("Binding Accounts"); D:\adv\rmi>java accountserver


Naming.bind("101",acc1); starting server…..
Naming.bind("102",acc2);
Naming.bind("103",acc3); Account: 101 created
Account: 102 created
System.out.println("Finished ...."); Account: 103 created
System.out.println(); Binding Accounts
System.out.println("Press Enter to close: "); Finished….
System.in.read();

Naming.unbind("101");
Naming.unbind("102");
Naming.unbind("103");

System.exit(0);
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}

// File name: accountclient.java

// to get the remote objects, and to operate on them

import java.rmi.*;
import java.io.*;

public class accountclient


{
static account r;

public static void main(String args[])


{
237 SATEESH N
SATEESH N
try
{
double amt;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String host = "localhost";

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 2: System.out.println(); DETAILS


System.out.println(" DETAILS ");
System.out.println("------------------------------"); Account Number: 101
System.out.println("Account Number : "+r.getAccno()); Account Name : Sateesh
System.out.println("Account Name : "+r.getAccname()); Current Balance: 25000.0
System.out.println("Current Balance: "+r.getBalance());
break; MENU
1.Open
case 3: System.out.print("Enter Deposit Amount: "); 2.Details
amt = Double.parseDouble(stdin.readLine()); 3.Deposit
r.deposit(amt); 4.Withdraw
System.out.println("Done"); 5.Exit
break;
Enter u r choice:
case 4: System.out.print("Enter Withdraw Amount: ");
amt = Double.parseDouble(stdin.readLine());
r.withdraw(amt);
System.out.println("Done");
break;

case 5: break;

default: System.out.println("Invalid choice");


break;
} // end of switch

} // 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

Вам также может понравиться