java

239

Upload: api-3700668

Post on 14-Nov-2014

13 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Java
Page 2: Java

SATEESH N

2 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

Page 3: Java

SATEESH N

3 SATEESH N

INTRODUCTION

About the Java Technology :

Java technology is both an Objec t Or i ented programming language and a platform used f or dev eloping appl i cat i ons f or the i n ternet .

Jav a was star ted by the f ol l owing 5 people :

Jam es Gosl i ng, Pat r i ck Naughton, Mike Sher i dan, Chri s W rath, Ed F rank

These people designed a l anguage ca l l ed OAK i n 1970’s f or consum er e lec t roni cs. But OAK was f a i l ure. The language OAK was enhanced wi th i n ternet suppor t and re l eased i n the m arket i n 1995 wi th the new nam e JAVA.

Important Features o f JAVA :

Object Or i ented Programming l anguage. Programming suppor t f or i nternet . Robust programm ing l anguage. St rongl y t yped l anguage : W e can’ t assign a v ari ab le to another v ari ab le, i f

t he range f or the r i ght si de v ari ab le i s l arger than the l ef t s i de v ari able. Ex : i n t i ; char ch; ch = i ; / / error

i = ch; / / ok Al l ows us to design applets and appl i cat i ons. Suppor t network ing, d i st r i buted programming. Suppor ts m ul t im edia. Plat f orm i ndependent . I n terpreted Secure Mul t i threaded Dynamic Por tab le Archi tec ture neut ral

Features Removed f rom C and C++ :

No More Typedef s, Def i nes, or Preprocesso r No More St ructures or Unions No Enum s No More Funct i ons No More Mul t i p l e Inher i tance No More Goto Statem ents No More Operator Ov erl oading No More Autom at i c Coercions : assign ing i n t to f l oat wi thout t ype cast i ng. No More Pointers

Page 4: Java

SATEESH N

4 SATEESH N

Programming in JAVA

I n j av a the program s are genera l l y d iv ided i n to 2 categor i es.

i . Appl i cat i ons & i i . Applets

i . Appl i cat i on : An appl i cat i on i s norm al program that runs on an i nd iv idual system .

i i . Applet : An applet i s a program designed in Jav a and wi l l be p laced on the serv er, the applet wi l l be downloaded f orm the serv er to the c l i ent a l ong wi th the HTML docum ent and runs i n the c l i ents W EB browser . i . e . , an applet wi l l run as a par t o f W EB docum ent .

An applet can conta in com ponents l i ke but tons, check box es etc . ,An applet can open connect i ons wi th network serv ers, database serv ers etc,

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.

First Java program

Example: Fi rst . java

// it displays the text ‘First Java Program’ .

class First{ public static void main(String args[]) {

System.out.println("First Java Program"); }}

compiling a JAVA program : When ev er we com pi l e a j av a program , the com pi l er c reates an i n term ediate f i l e , whi ch conta ins the byte code of the program .

D: \> jav ac Fi rst . j av a ( Enter )

Creates f i rst . c l ass By te code

To run, the j av a i n terpreter should be used, whi ch reads the i nst ruc t i ons f rom the by te code and ex ecutes them.

D: \> j av a Fi rst ( Enter ) Ex ecutes f i rst . c l ass

Out put:

E:\Core>javac First.java

E:\Core>java First

First Java Program

E:\Core>

Page 5: Java

SATEESH N

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

Page 6: Java

SATEESH N

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

Comments in Java Code

Code comm ents are placed i n source f i l es to descr i be what i s happening i n the code to som eone who m ight be reading the f i l e , to comm ent -out l i nes of code to i so la te the source of a problem f or debugging purposes, or to generate API docum entat i on.

To these ends, the Jav a l anguage suppor ts three k i nds of comm ents: double sl ashes, C-sty l e , and doc comm ents.

Double S lashes : Double sl ashes ( / / ) a re used i n the C++ programming l anguage , and te l l t he com pi l er to t reat ev ery thi ng f rom the sl ashes to the end of the l i ne as tex t .

Ex : / /A Very Sim ple Ex am ple cl ass

C-Styl e Comm ents : Instead of double sl ashes, you can use C- sty l e comm ents ( / * * / ) t o enc lose one or m ore l i nes of code to be t reated as tex t .

Ex : / * These areC-sty l e comm ents* /

Doc Comm ents : To generate docum entat ion f or your program, use the doc comm ents ( / ** * / ) to enc lose l i nes of tex t f or the j av adoc too l to f i nd. The j av adoc too l l ocates the doc comments em bedded i n source f i l es and uses those comm ents to generate API docum entat i on.

Ex : / ** Thi s c l ass d i sp lays student deta i l s a t * the console. * /

Your Computer System

Page 7: Java

SATEESH N

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

Page 8: Java

SATEESH N

8 SATEESH N

ControlStatements :

Selec t i on Statem ents:

i f swi tch

Loop Statem ents:

whi le do – while for

Jum p Statem ents:

break cont inue return

using break as a f orm of goto :

Syntax : break l abel ;

Example : Goto_break. java

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

}}

}}

Note: Although goto is a reserved word, currently the Java language does not support the goto statement. Use labeled breaks instead.

output :

Before break.

Page 9: Java

SATEESH N

9 SATEESH N

Data types in Java

Ex: boolean b ;

b = t rue; or b = f al se;

i f (b== true) i f (b==fa l se)

i f (b) checks f or i f (b== t rue)

i n t i = 1 ;

i f ( i ) i nv al i d , because i i s not a Boolean datatype

i f ( i ! =0) ok

KeyWords

Java Primitive Data TypesType Values Default Size Range

byte signed integers 0 8 bits -128 to 127

short signed integers 0 16 bits - 32768 to 32767

int signed integers 0 32 bits -2147483648 to 2147483647 ( -23 1 to23 1 –1)

long signed integers 0 64 bits -9223372036854775808 to 9223372036854775807 ( -26 3 t o 26 3 –1)

float IEEE 754 floating point 0.0 32 bits+ / -1.4E-45 to + / -3.4028235E+38,

+ / -in fini ty, +/ -0 , NAN

double IEEE 754 floating point 0.0 64 bits+ / -4.9E-324 to

+ / -1.7976931348623157E+308,+ / -in fini ty, +/ -0 , NaN

char Unicode character \u0000 16 bits \u0000 to \uFFFF

boolean true, false false1 bit used in 32 bit integer

NA

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!

Page 10: Java

SATEESH N

10 SATEESH N

Out put:

value of a[0] is: 10value of a[1] is: 20value of a[2] is: 30value of a[3] is: 40value of a[4] is: 50

Arrays

An ar ray i s a co l l ec t i on of v alues a l l are be longing to the sam e data t ype and ref er red wi th the sam e nam e to access any e lem ent of an ar ray i t s posi t i on shoul d be g iv en whi ch i s known as i ndex . In j av a ar ray i ndex ing star t s f rom 0.

Syntax : data t ype v ar i able nam e[ ] ;

Ex : i n t ar r [ ] ;

I n the abov e statem ent the ar ray wi l l be c reated wi thout any si ze. W e should a l l ocate m em ory using the new operator before accessing the ar ray .

ar r = new i n t [5 ] ;

ar r [0 ] = 10;ar r [1 ] = 20;

i f we don’ t assign or read the v alues f or rem ain ing l ocat i ons, by def aul t they wi l l be f i l l ed wi th 0 ’s.

P i ctor i al representat i on:

ar r

0 1 2 3 4

i n t arr [ ] = new i n t [5 ] ;

i n t [ ] ar r = new i n t [5 ] ;

l ength proper ty : Each ar ray conta ins the l ength proper ty , whi ch conta ins the no. o f e l em ents i n the ar ray .

Ex : System.out .pr i n t l n(ar r . l ength); / /d i sp lays the no. of l ocat i on i .e. ,5 for the abov e ex .

In i t i al iz i ng an ar ray : W hen we i n i t i a l i ze an ar ray at the t im e of c reat i ng the ar ray the new operator should not be g iv en.

/ / Example: OneDArrIn i . java

// initializing the array and display the elements

class OneDArrIni{ public static void main(String args[]) {

int a[]={10,20,30,40,50},i;

for(i=0;i<a.length;i++)

System.out.println("value of a["+i+"] is: "+a[i]); }}

10 20

Page 11: Java

SATEESH N

11 SATEESH N

Out put:

value of a[0] is: 10value of a[1] is: 20value of a[2] is: 0value of a[3] is: 0value of a[4] is: 0

/ / Example: OneDArr. java

// assigning elements into the array and display the elements

class OneDArr{ public static void main(String args[]) {

int a[],i;a=new int[5];a[0]=10;a[1]=20;

for(i=0;i<a.length;i++){ System.out.println("value of a["+i+"] is: "+a[i]);}

}}

Two – Dimensional Arrays : I n Jav a, i n a 2-d ar ray a l l t he rows need no t conta in the sam e no. of co lum ns.

i n t a[ ] [ ] ;

a = new i n t [3 ] [ ] ; / / 3 rows

a[0] = new i n t [4 ] ; / / f or 1 s t row 4 co l sa[1] = new i n t [3 ] ; / / f or 2 n d row 3 co l sa[2] = new i n t [5 ] ; / / f or 3 r d row 5 co l s

a[0] [0 ] = 10;a[0] [1 ] = 20;

P i ctor i al representat i on :

a 0 1

2

0 1 2 3 4

i n t a[ ] [ ] = new i n t [3 ] [5 ] ;

i n t [ ] [ ] a = new i n t [3] [5 ] ;

In i t i al iz i ng a 2 – D Ar ray :

/ / Example: TwoDAarr In i . java

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

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

1 , 0 1 , 1 1 , 2

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

Page 12: Java

SATEESH N

12 SATEESH N

Out put:

a[0][0] : 1 a[0][1] : 2 a[0][2] : 3 a[0][3] : 4a[1][0] : 5 a[1][1] : 6 a[2][0] : 7 a[2][1] : 8 a[2][2] : 9

Out put:

a[0][0] : 1 a[0][1] : 2 a[0][2] : 3 a[0][3] : 4a[1][0] : 1 a[1][1] : 2 a[2][0] : 1 a[2][1] : 2 a[2][2] : 3

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

}}

/ / Example: TwoDArr. java

// 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++) { a[i][j]=k; k++; } }

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

args array : The args ar ray whi ch was g iv en i n the m ain( ) contains a l l t he argum ents g iv en by the user a t the comm and l i ne.

/ / Example : CommArgs. java

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

Page 13: Java

SATEESH N

13 SATEESH N

Out put:

Total no. of Argument(s): 3args[0]: redargs[1]: greenargs[2]: blue

Out put:

Student no. : 10Student name: Sateesh

Student no. : 10Student name: Sateesh

if(args.length<1){ System.out.println("Insufficient Arguments - should give min. 1 arg"); return;}

for(int i=0;i<args.length;i++){ System.out.println("args["+i+"]: "+args[i]);}

}}

Defining Classes and Creating Objects

Class : A cl ass i s a co l l ec t i on of Data mem bers (v ar i ables) that contain i nf orm at i on necessary to represent the c l ass and Methods ( f unc t i ons) that perf orm operat i ons on the data m em bers of the c l ass. . Once a c l ass i s c reated, any no. o f i nstances of the c l ass can be c reated i n the program . 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.

Object : Objec t i s an i nstance of the cl ass or an objec t i s the basi c run- t im e ent i ty .

/ / Example: ClassandObj . java

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

Student s;

s= new Student();

s.assign();s.display();

Student t= new Student();

t.assign();t.display();

}}

Page 14: Java

SATEESH N

14 SATEESH N

CONSTRUCTORS

A const ruc tor i s a spec ia l mem ber f unc t i on whi ch i s ca l l ed autom at i ca l l y whenev er an i nstance of the c l ass i s c reat ed. The nam e of the const ruc tor should be equal to the nam e of the c l ass. Const ruc tors are genera l l y used f or i n i t i a l i z i ng the v ari ab les of the cl ass. A const ruc tor m ay or m ay not take any argum ents, but a const ruc tor wi l l not re turn any v alue. Const ruc tors can be ov er l oaded.

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

this : t h i s key word, the thi s ref erence var i ab le always ref ers to the cur rent cl ass. I t can be appl i ed i n 3 categor i es.

i . t o ref er to the f unct i ons of the cur rent class. Ex : thi s.d i sp lay( ) ;i i . t o ref er to the v ar i ables of the cur rent class. Ex : thi s.sno i i i . t o cal l a const ruc tor f rom another const ruc tor . Ex : th i s( ) ;

/ / Example : Constructor1. java

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

}}

Page 15: Java

SATEESH N

15 SATEESH N

Out put:

val of x : 10val of y : 20

Out put:

Student no. : 11Student name: Raj

Student no. : 22Student name: Sanju

Student no. : 33Student name: Sateesh

class Constructor1{ public static void main(String args[]) {

Vals s = new Vals(10,20);

s.dispxy(); }}

/ / Example : Constructor2. java

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

s.display();t.display();

s.accept(33,"Sateesh");s.display();

}}

Page 16: Java

SATEESH N

16 SATEESH N

Out put:

Val of x : 10Val of y : 20

Val of x : 50Val of y : 60

Out put:

Val of z : 77

Val of z : 99

Val of s.x : 10Val of s.y : 20Val of s.z : 99

Val of t.x : 50Val of t.y : 60Val of t.z : 99

Val of z : 99

/ / Example : Constructort toConstructor . java

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

System.out.println("\n Val of X: "+x+"\n Val of Y: "+y); }}

class ConstructortoConstructor{ 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();

}}

Static members & Static methods

Stat ic members: W henev er a v ari ab le is spec i f i ed as stat i c such v ari able wi l l be c reated onl y once i n the m em ory f or a l l t he i nstances of the c l ass. A l l t he i nstances of the c l ass wi l l share the sam e v alue of the stat i c v ar i ab le. A stat i c v ar i ab le of a cl ass can a l so be accessib l e using the nam e of the c l ass.

/ / Example: Stat icMember. java

class Vals{ int x,y; static int z=77;}

class StaticMember{ public static void main(String args[]) { System.out.println("\n Val of Z: "+Vals.z);

Page 17: Java

SATEESH N

17 SATEESH N

Out put:

Value is : 77

Values are : 10 20 99

Values are : 50 60 99

Value is : 99

Value is : 99

Value is : 99

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

Stat ic methods : A stat ic f unc t i on of a c l ass can be accessib l e using the nam e of the c l ass a l so. A stat i c f unc t i on can access onl y other sta t i c m ember of the cl ass.

/ / Example: StaticMethod.java

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

s.x=10; s.y=20; s.z=99; t.x=50; t.y=60;

s.display(); t.display();

s.print(); t.print();

Vals.print(); }}

Page 18: Java

SATEESH N

18 SATEESH N

Out put:

First Static Block

Second Static Block

In the main program

Static Blocks

I f a cl ass conta ins stat i c b l ocks a l l such b locks wi l l be ex ecuted f i rst when ev er the c l ass i s l oaded.

/ / Example : Stat icBlocks. java

class StaticBlocks{ static {

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

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

System.out.println("U r in Constructor");}

static{

System.out.println("U r in Static block");}

}

output :

U r in Static blockU r in Constructor----------------------U r in Constructor

Page 19: Java

SATEESH N

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

Finalizers

• Jav a al l ows you to def i ne a m ethod that i s autom at i cal l y cal l ed bef ore object is re turned to heap.

• Fina l i zer: Method that al l ows resourc es to be f reed bef ore objec t i s garbage co l l ected.

v oid f i nal ize( ){ . . . }

• Must be cal l ed f i na l i ze( ).

• F i nal i zer not al l owed to hav e argum ents.

• Immediate l y bef ore object i s garbage co l lec ted, Jav a runt im e wi l l ca l l f i nal i ze( ) ;

• F i nal i zer should be used onl y as a l ast -d i tch ef f or t to recov er assets bef ore they are l ost f orev er .

• Most Jav a c l asses don’ t requi re a f i nal ize m ethod.

* Jav a’s garbage co l l ec t i on m echani sm takes care of m em ory l eaks.

* Finalizer is Not a Destructor

Example: Final i zer_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"); }}

Page 20: Java

SATEESH N

20 SATEESH N

class Finalizer_Ex1{

//controlling class public static void main(String[] args) { //Guarantee finalization of all objects on exit

System.runFinalizersOnExit(true);

//Instantiate two objects to be finalized TestClassA objA = new TestClassA();

TestClassB objB = new TestClassB();

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

Output :

Terminating....Finalizing TestClassB objectFinalizing TestClassA object

Page 21: Java

SATEESH N

21 SATEESH N

Example: GC_Finalizer_Ex.java

/** Example shows garbage collector in action, Note that the finalize() method ofobject GC1 runs without being specifically called and that the id's of garbagecollected 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: 1911256GC1 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(): 1222864GC1 object 9259 has been finalized.GC1 object 9260 has been finalized. So on. . . .

Page 22: Java

SATEESH N

22 SATEESH N

Overloading Methods

• D i f ferent m ethods can hav e the sam e nam e

• The si gnature of a m ethod i s the m ethod’s nam e and the param eter t ypes ( i ncl ud ing t he order of the param eters)

• I n a cl ass, a l l m ethods m ust hav e di f f erent si gnatures

• E .g. , the abs m ethod i n the Math cl ass

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 namespublic 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 namepublic String get_fullname(String middle){

String fn = "Sateesh"; String ln = "Natchireddy"; return fn+" "+middle+" "+ln;

} // method get_fullname (1 argument)}public class MethodOverloading_Ex1{

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

}}

Output :

Test1: Sateesh NatchireddyTest2: Sateesh NatchireddyTest3: Sateesh Kumar Natchireddy

Page 23: Java

SATEESH N

23 SATEESH N

Access Specifiers

I n Jav a, we accom pl i sh encapsulat i on through the appropr i a te use of v i s i bi l i ty m odi f i ers (a m odi f i er i s a Jav a reserv ed word that spec i f i es par t i cular charac ter i st i cs of a m ethod or data v alue) .

An access spec i f i er (v i si b i l i t y m odi f i ers) def i ne who i s ab le to use th i s m ethod.

Access spec i f i ers can be:

public when anyone can ca l l t hi s m ethod (publ i c m ethods are a l so ca l l ed serv i ce m ethods; A m ethod c reated sim ply to assi st a serv i ce m ethod i s ca l l ed a suppor t m ethod) .

private when onl y m ethods i n the sam e class are permi t ted to use thi s m ethod.

protected when m ethods i n th i s c l ass and m ethods i n any subc lasses m ay use th i s m ethod.

(noth ing) when any c l asses i n th i s par t i cu lar package or di rec tory m ay access th i s m ethod.

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.

References :

An objec t ref erence holds the m em ory address of an objec t .

ClassA a = new ClassA( ) ;

Class b;

For ob ject ref erences, assignm ent copies the m em ory l ocat i on:

b = a;

Two or m ore ref erences that ref er to the sam e objec t are cal l ed a l i ases of each other.

Beforea b

Aftera b

Beforea b

Beforea b

Aftera b

Aftera b

Page 24: Java

SATEESH N

24 SATEESH N

Out put:

Before : 10 20Before : 10 20

After : 10 20After : 20 40

call by value and call by reference : W hi le sending argum ents to a f unct i on sim ple data t ypes such as i n t , f l oat e tc . , wi l l be passed by v a lues. W here as objec ts are passed by ref erence.

Example : calvalcal ref . java

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 B.f1(a); // sending by reference

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

Page 25: Java

SATEESH N

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

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.

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.

b Object

buttonobject

Object b

y

buttonobject

Page 26: Java

SATEESH N

26 SATEESH N

For example, if in methodX we had y = new Button("another button"); we get the situation shown in Figure 3.

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

y Object

buttonobject

b Object

buttonobject

Page 27: Java

SATEESH N

27 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 mainThe value of b's label is AAAIn methodXThe value of y's label is AAAThe value of y's label is BBBThe value of y's label is CCCThe value of y's label is DDDBack in mainThe value of b's label is BBB

The value of i is 5In methodZThe value of j is 5The value of j is 6Back in mainThe value of i is 5

Page 28: Java

SATEESH N

28 SATEESH N

Using Objects as Parameter and Returning Objects

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); t1.print("Test1: ");

// test2 Interval t2 = a.addint(b); t2.print("Test2: ");

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

Output :

Test1: [4.0,6.0]Test2: [4.0,6.0]Test3: [4.0,6.0]Test4: [4.0,6.0]Test5: [4.0,6.0]

Page 29: Java

SATEESH N

29 SATEESH N

Inner Classes

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 amore 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 classBase bref = new Base(){

void method1(){}

};}

}

Page 30: Java

SATEESH N

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

}}

}

Page 31: Java

SATEESH N

31 SATEESH N

class class2 extends class1{ void class2_method() {

System.out.println("class2 method "); System.out.println("Accessing outer_var1 of class1: "+outer_var1);

}}

public class InnerClass_Ex2{

public static void main(String[] args){

class2 obj = new class2();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.

Output:class2 method Accessing outer_var1 of class1: 10Inner1 class methodAccessing outer_var1: 10Inner2 class methodAccessing outer_var1: 10

Page 32: Java

SATEESH N

32 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 ClassesAn 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 implementsat 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.

Page 33: Java

SATEESH N

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

Page 34: Java

SATEESH N

34 SATEESH N

INHERITANCE

I nher i tance i s the process of c reat i ng new c lasses f rom ex i st i ng c l asses. The c l ass whi ch i s be ing i nheri ted i s known as ‘ super c l ass ‘ and the c l ass whi ch i nheri t s the other c l ass i s known as ‘ sub c l ass ‘ . T o i nher i t a c l ass i n to another c l ass, the key word ‘ ex tends ‘ should be used.

c l ass A A super c lass {

}

c l ass B ex tends A B sub c l ass {

}

Jav a suppor ts m ul t i l ev e l Inheri tance but does not suppor t m ul t i pl e Inher i tance.

A A BMul t i pl e Inheri tance

B Mul t i l ev el Inher i tance C not suppor ted by Jav a suppor ted by Jav a

C

Example: Inheri tence. java

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

Page 35: Java

SATEESH N

35 SATEESH N

Out put:

Student No. : 10Student Name: SateeshTotal Fee :5000

Customer No. : 101Customer name : RajItem purchased: SAMSUNG key boardQuantity : 2Price : 150.0Total Bill : 300.0

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{ public static void main(String args[]) { student s = new student(); customer c = new customer();

s.accept(); c.accept();

s.display(); c.display(); }}

Constructors in the case o f Inheri tance :

W henev er a subc lass objec t i s c reated the super c l ass const ruc tor wi l l be ca l l ed f i rst and then the subc lass const ruc tor . I f t here are m ore than one super c l asses const ruc tors wi l l be cal l ed i n the order of Inher i tance.

Ex: c l ass A{

}

c l ass B ex tends A{

Ex ecut i on takes p lace f rom bot tom to top}

c l ass C ex tends B{

}

Super keyword : The ‘ th i s ‘ re f erence v ari ab le always r ef ers to the cur rent c l ass . And the ‘ super ‘ re f erence v ar i able a lways ref ers to the imm ediate super c l ass. The ‘ super ‘ key word can be appl i ed i n 3 categor i es.

i . To ref er to the v ari ab les of the super c l ass.i i . To ref er to the m ethods of the super c l ass.i i i . To cal l a super c l ass const ruc tor f rom the sub c l ass const ruc tors.

Page 36: Java

SATEESH N

36 SATEESH N

Out put:

’x’ Value of Class A is: 10’x’ Value of Class B is: 20

Example: Constrctors_Inheri tence. java

/ / Program f or i . To ref er to the v ar i ables of the super cl ass. i i .To ref er to the m ethods of the super c l ass.

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 ASystem.out.println("’x’ Value of Class B is: "+x);

}}

class Const rc tors_Inher i tence{ public static void main(String args[]) {

B b = new B(10,20);b.display();

}}

Example : ConstructorTOConstructor_Inheri tence.java

/ / Program f or i i i . To cal l a super c l ass const ruc tor f rom the sub c l ass const ruc tors.

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 constructorthis.z=c;

}

Page 37: Java

SATEESH N

37 SATEESH N

Out put:

Values are: 10 20 30

void display() {

System.out.println("Values are: "+x+" "+y+" "+z); }}

class Const ruc torTOConst ruc tor_Inhere i tence{

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

NO TE: Cal l i ng a ‘ super c l ass ‘ const ruc tor f rom the ‘ sub c l ass ‘ const ruc tor using the ‘ super ‘ i n a f unct i on styl e m ust be the f i rst sta tem ent i n the ‘ sub c l ass ‘ const ruc tor .

Ex : B ( ) { super ( ) ;

t h i s.z=c ; }

Overridden Methods

W henev er a f unct i on of super c l ass a l so def i ned i n the sub c l ass, then the f unct i on i s known as ov er r i dden.

Ex: c l ass A{

v o id f 1( ) {

} }

c l ass B ex tends A{ v oid f 1( ) / / ov er r i dden {

}}

In Jav a a ref erence v ar i able of ‘ super c l ass ‘ can ref er to an i nstance of ‘ sub c l ass ‘ and i s ab le to cal l t he ‘ ov er r i dden ‘ f unct i on.

Ex : A a = new A( ) ;B b = new B( ) ;

a . f 1( ) ;b . f 1( ) ;A r ; / / r i s ref erence v ar i able of super c l ass A

Page 38: Java

SATEESH N

38 SATEESH N

ar = a;

rr . f 1( ) ; / / cal l s a . f1( ) ;

br = b;

r r . f 1( ) ; / / cal l s b. f 1( ) ;

Dynamic Method Dispatch :

System. in. read( ) : Reads a charac ter f rom the key board and returns the “ ASCI I v alue “ of that charac ter.

Ex : i n t ch = System .i n . read( ) ;

System .out .pr i n t l n(ch) ;

Example : DynamicMethodDispatch. java

/ / w.a.p to accept a choi ce f rom the user , i f t he choi ce i s ‘1 ’ accept and d i sp lay studen t deta i l s, i f t he choi ce i s ‘2 ’ accept and di sp lay custom er deta 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;

}

Page 39: Java

SATEESH N

39 SATEESH N

Out put:

Enter 1: Student 2: Customer1Student Details : 10 Sateesh

Out put:

Enter 1: Student 2: Customer 2Customer Details: 20 Raj Mouse 2 150

void display() // over ridden function {

System.out.println("Customer Details: "+cno+" "+cname+" "+product+" "+qty+" "+rate);

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

}}

Example : Inheri tence_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{ public static void main(String[] args) { common r = new common();

System.out.println("Throgh object \"r\""); r.accept();

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

Output :Throgh object "r"method accept() in class commonThrogh object "obj"method accept() in class commonmethod display() in class studentThrogh object "r2"method accept() in abstract class common

Page 40: Java

SATEESH N

40 SATEESH N

Note: In the abov e ex am ple the di sp lay( ) m ethod m ust be dec lared i n super c l ass comm on to access the d i sp lay( ) m ethod i n the subc lass, through ref erence v ari ab le r2 .

Example : Inheri tence_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");}

}public class Inheritence_Ex2{ public static void main(String[] args) { common r = new common(); System.out.println("Throgh object \"r\""); r.accept(); r.display();

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

Output :Through object "r"method accept() in class commonmethod display() in class commonThrough object "obj"method accept() in class studnetmethod display() in class studentThrough object "r2"method accept() in class studnetmethod display() in class student

Page 41: Java

SATEESH N

41 SATEESH N

Final key word : The ‘ f i nal ‘ key word can be spec i f i ed f or the v ari ables, m ethods and c l asses.

For the v ar i ables : W henev er a v ari able i s spec i f i ed as f i na l , such v ari ab le becom es a constant .

Ex : f i nal i n t MAX = 100; MAX = 50; / / Error , can’ t m odi f y the v alue

For the methods : A f i na l m ethod can’ t be ov er r i dden.

Ex: c l ass A{ f i nal v o id f 1( ) { }}c l ass B ex tends A{ f i nal v o id f 1( ) / / Er ror can’ t ov er r i de f i nal m ethod { }}

For the c l asses : A f i na l c l ass can’ t be ex tended.

Ex: f i nal c l ass A{}c l ass B ex tends A / / Er ror , can’ t ov er r i de ex tend f i na l c l ass.{}

Note: Abst rac t f i nal i s not al l owed.

Page 42: Java

SATEESH N

42 SATEESH N

Abstract methods and Abstract classes

W henev er a f unct i on of super c l ass i s used onl y f or the pol ym orphi sm and i s not conta in i ng any statem ents then that f unc t ion can be spec i f i ed as abst rac t by pref ix i ng the f unc t i on declarat i on wi th key word ‘ abs t rac t ‘ .

W henev er a cl ass conta ins at l east one abst rac t f unct i on then the cl ass should a l so be spec i f i ed as abst rac t .

Ex : abstract c lass comm on{ abstract void accept ( ) ; abstract void di sp lay( );}

W henev er a c l ass ex tends an abst rac t c l ass then the c l ass should com pulsor i l y ov er r i de al l t he abst rac t methods of the super c l ass.

Ex : class student extends common{ void accept( ) { } }

The abov e ex am ple generates Er ror i ncom plete ov er r i di ng .

Ex: class student extends common{ void accept( ) { } void display( ) { }}

The abov e ex am ple does not generate any er rors, because a l l t he f unct i ons of c l ass comm on are ov err i di ng i n cl ass student .

There can’ t be any i nstances of an abst rac t c l ass. Howev er , ref erence v ari ab les of the abst rac t c l asses are a l l owed i n the program .

comm on r ; / / ok

r = new comm on( ) ; / / Er ror can’ t i nstant i a te abst rac t cl ass

r = new student ( ) ; / / ok , student i s not abst rac t

Example : AbstractClass_Ex1.java

abstract class abstractclass{

abstract void f1();

abstract void f2();}class Hi extends abstractclass{

void f1(){

System.out.println("Hi");}

Page 43: Java

SATEESH N

43 SATEESH N

void f2(){

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

}class AbstractClass_Ex1{

public static void main(String args[]){

Hi h = new Hi();h.f1();h.f2();

abstractclass obj;obj = new Hi();obj.f1();obj.f1();

}}

An abst rac t cl ass can conta in abst rac t as wel l as non-abst rac t m ethods.

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

common r;

r = new student ( );

r.accept( ); // calls student accept( );

r.f1( ); // calls non-abstract method f1( ) from the common class }}

Output:

HelloHI

Output:

HiHelloHiHello

Page 44: Java

SATEESH N

44 SATEESH N

A cl ass can be spec i f i ed as abst rac t ev en i t i s not conta ini ng any abst rac t m ethods we can’ t c reate i nstances of i t s subc lasses i f t hey are not abst rac t .

Example : AbstractClass_nonabstmeth.java

abstract class common{

void accept(){

System.out.println("Hello");}void display(){}

}class student extends common{

void display(){

System.out.println("HI");}

}public class AbstractClass_nonabstmeth{ public static void main(String[] args) { // 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.

Output:

HelloHI

Page 45: Java

SATEESH N

45 SATEESH N

Example: 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 methodpublic void add(int a,int b){

System.out.println(a+b);}// new methodpublic 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 methodpublic 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)); }

Page 46: Java

SATEESH N

46 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) { System.out.println((a+b)); } public void sub(int a,int b) {

System.out.println((a-b)); }};// calling abstractclass2 methods obj1.add(20,30);obj1.sub(20,30);

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

abstclass4 st4 = new abstclass4();st4.add(10,35); // calling overridden methodst4.sub(50,30); // calling overridden method

}}

out put :

5050-1045204520

Page 47: Java

SATEESH N

47 SATEESH N

output :

Enter 1: Student 2: Customer 1Student Details : 10 Sateesh 1500

output :

Enter 1: Student 2: Customer2Customer Details: 20 Raj product2 150

Interfaces

An i n terf ace i s a co l l ec t i on of si gnatures of f unct i ons and f i na l v ar i ab les. Once an i n terf ace i s c reated a c l ass can implem ent the i n terf ace. W henev er a c l ass im plem ents the i n terf ace, the c l ass should ov er r i de al l t he m ethods of i nterf ace.

Example : In terface_Ex1. java

interface common{ void accept(); void display();}

class student implements common{ int sno; String sname; int tfee;

public void accept()//overridden function {

sno=10;sname="Sateesh";tfee=1500;

} public void display()//overridden function {

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

}}

Page 48: Java

SATEESH N

48 SATEESH N

Mul tiple implements : A c l ass can im plem ent any num ber of i nterf aces such c l as s should ov er r i de a l l t he m ethods i n a l l t he i n terf aces.

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( ); // OKc.f1( );c.f2( );

A a;a=c;a.f1();

B b;b=c;b.f2();

}}

Extended In terfaces : An i n terf ace can ex tended another i n ter f ace using the key word “ ex tends “ . W henev er a cl ass im plem ents the l ast i n terf ace the cl ass should ov er r i de al l t he m ethods i n the i n terface chain.

Ex: interface A{ void f1( );}

interface B extends A{ void f2( );}

Output :

HiHelloHiHello

Page 49: Java

SATEESH N

49 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( ); // OKc.f1( );c.f2( );

A a;a=c;a.f1();

B b;b=c;b.f2();

}}

Part ia l implements : W henev er a cl ass im plem ents an i n terface, but does not ov er r i de a l l t he m ethods of the i n terface such c l ass should be spec i f i ed as abst rac t . W e should c reate another c l ass that ex tends the abst rac t c l ass and should ov er r i de the l ef tov er m ethods.

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

}

Output :

HiHelloHiHello

Page 50: Java

SATEESH N

50 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( ); // OKc.f1( );c.f2( );

A a;a=c;a.f1();

B b;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 andconstant ( 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 . An abst rac t c l ass can conta in abst rac t as wel l as non-abst rac t m ethods. Howev er an i n terf ace conta ins onl y the si gnatures of the f unc t i ons.

2. A c l ass can ex tends onl y one c l ass. Howev er a c l ass can im plem ent any num ber of i n terf aces.

CLASSPAT H : The cl ass path i s an env i ronm ent v ari able set i n the operat i ng system whi ch conta ins a co l l ec t i on of subdi rec tor ies where each such d i rec tory can contain any num ber of cl ass f i l es. Once the c l ass path i s se we are able to access the c l asses i n the subdi rec tor i es f rom any l ocat i on i n the system .

D: \>SET CLASSPATH=d: \sam packD;f : \ sam packF ;

Ver i f y i ng the cl asspath : D: \>echo %classpath%

To adding a new subdi rec tory to prev ious subdi rec tor i es.

D: />SET CLASSPATH=%classpath%;E: \>sam packE;

D: />echo %classpath%

The cl asspath i s an env i ronm ent v ari ab le whi ch wi l l be rem ov ed once the comm and prom pt i s cl osed.

Output :

HiHelloHiHello

Page 51: Java

SATEESH N

51 SATEESH N

PACKAGES A package i s a col l ec t i on of cl asses that can be im ported i nto other program s. A package work s simi l ar to a l i brary whi ch i s a co l l ec t i on of c l asses. These c l asses can be im por ted and used i n other Jav a program s.

To c reate a package a subdi rec tory i s requi red. The nam e of the package wi l l be the nam e of the subdi rec tory . To m ake a c l ass belonging to a package, the package nam e should be spec i f i ed as the f i rst sta tem ent i n the program.Ex: d: \>

sam packD

p1

A. j av aB. j av a

f : \>

sam packF

p2

C. j av aD. j av a

e: \>

core

pack . j av a / / conta ins m ain( ) , im por ts A ,B,C,D

W e should set the cl asspath bef ore com pi l ing the packages. j av a

D: \>SET CLASSPATH=%classpath%;d: \ sam packD;f : \ sam packF;

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

Page 52: Java

SATEESH N

52 SATEESH N

Out put:

Display from ADisplay from BDisplay from CDisplay from D

// 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 classimport 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();D d = new D();

a.display();b.display();c.display();d.display();

}}

Page 53: Java

SATEESH N

53 SATEESH N

The f ol l owing are the l i st of som e predef i ned packages whi ch wi l l be i nsta l l ed wi th JDK.

j av a. l ang : Th i s package contains the im portant cl asses l i ke system , st r i ng, i nteger , objec t etc . , th i s package wi l l be im por ted i n to ev ery j av a program by def aul t .

j av a. i o : Conta ins cl asses f or I /P and O/P.

j av a.awt : AW T stands f or Abst rac t W indows Tool ki t , contains c l asses f or GUI .

j av a.applet : For applet m anagem ent .

j av a.net : For network ing.

j av a.sq l : Contains c l asses f or m anaging data base t ransac t i ons.

j av a.ut i l : Contains c l asses f or mangeing dates, co l l ect i ons etc . ,

Object Class : I t i s def i ned i n j av a. l ang package. W henev er we c reate a c l ass whi ch does not i nher i t any other cl ass by def aul t i nher i t s the objec t cl ass i . e . , ob jec t c l ass i s the super c l ass f or a l l t he cl asses. In Jav a onl y the Objec t c l ass wi l l not hav e a super c l ass. For a l l t he rem aining cl asses the Object cl ass becom es the super c l ass.

Ex : class Objec t{

}

class A { Object

} A

class B extends A B{

}

Object cl ass i s conta in i ng the f ol l owing m ethods :

publ i c i n hashCode( ) : Returns the unique ident i f i cat i on f or each i nstance of the c l ass. 2000 S

Ex: student s = new student ( ) ;

k = s; K

boolean equal s(objec t ob j ) : Com pares the hash codes of both the objec ts and returns t rue i f both are equal , o therwi se f al se.

3000 tEx : student t = new student ( ) ;

s ! = t ;

10 Sateesh 2000

2000

20 Sanju 3000

Page 54: Java

SATEESH N

54 SATEESH N

Out put:

S Hash code: 3541984T Hash code: 4565111R Hash code: 3541984

S and T are not equalS and R are equal

student@360be0student@45a877student@360be0

student@360be0student@45a877student@360be0

St r i ng toSt r i ng( ) : Returns the hash code i n the hex adec im al f orm at pref ix ed wi th nam e of the c l ass.

Example : ObjClas_hashcode_equals . j ava

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))System.out.println("S and T are equal");

elseSystem.out.println("S and T are not equal");

if(s.equals(r))System.out.println("S and R are equal");

elseSystem.out.println("S and R are not equal");

System.out.println();

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

System.out.println();

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

}}

The toSt r i ng f unc t i on can be ov er r i dden i n any c l ass to r i dden any usef u l i nf orm at i on.

Page 55: Java

SATEESH N

55 SATEESH N

Out put:

10 Sateesh 150020 Sanju 100030 Raj 1200

Example : Objclass_toString. j ava

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{ public static void main(String args[]) {

student s = new student(10,"Sateesh",1500); 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.

Page 56: Java

SATEESH N

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

}}

Page 57: Java

SATEESH N

57 SATEESH N

class Student implements Cloneable{ int sno=50; String sname = "SATEESH"; Marks m = new Marks();

{ // worked as consturctorsno = 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_twoStudent 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();

}}

Page 58: Java

SATEESH N

58 SATEESH N

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

Output :

Before clone Contents in obj_one: sno: 100 Name: sateeshMarks:: DataCommunications : 40NetWorks : 38CryptoGraphy : 46After clone Contents in obj_one: sno: 100 Name: sateeshMarks:: DataCommunications : 40NetWorks : 38CryptoGraphy : 46After clone Contents in obj_two: sno: 100 Name: sateeshMarks:: DataCommunications : 40NetWorks : 38CryptoGraphy : 46

cont. . .

Modifying obj_two..... Modified obj_two. After modified obj_two Contents in obj_one: sno: 100 Name: sateeshMarks:: DataCommunications : 44NetWorks : 44CryptoGraphy : 44After modified obj_two Contents in obj_two: sno: 200 Name: KumarMarks:: DataCommunications : 44NetWorks : 44CryptoGraphy : 44

Page 59: Java

SATEESH N

59 SATEESH N

Out put:

Value is : 30Value is : 20Invalid element no.Value is : 10

Exception Handling An Ex cept i on i s an er ror that occur s i n the runt im e of a program ( i . e . , an except i on i s a Runt im e er ror ) . In the programming l anguage whi ch does not suppor t ex cept i on handl i ng, er rors are to be checked m anual l y using er ror codes and er ror m essages. In j av a whenev er an ex cept i on occurs, an objec t represent i ng that ex cept i on wi l l be c reated and wi l l be ‘ t hrown ‘ . An ex cept i on m ust be handled using the j av a ex cept i on handl i ng key words.

There are 5 key words :

1 . t ry , 2 . catch , 3 . throw , 4. f inal ly , 5 . throws .

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

Example : TryCatch. java

class TryCatch{ static int arr[]={10,20,30}; public static void main(String args[]) {

display(2); // to display the 3rd elementdisplay(1);display(5);display(0);

} static void display(int n) {

try{

System.out.println("Value is : "+arr[n]);}catch(ArithmeticException ex){ System.out.println("Arithmetic Error");}catch(ArrayIndexOutOfBoundsException ex){ System.out.println("Invalid element no.");}catch(ArrayStoreException ex){ System.out.println("Invalid array");}

}}

Page 60: Java

SATEESH N

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

List o f predefined Exceptions :

I n j av a a l l t he except i on nam es or c l asses the f o l l owing are the genera l ex cept i ons that are av ai l ab le i n the j av a. l ang package.

1. Ari thm et icEx cept i on : Thi s except i on occurs whenev er a d iv i s i on by 0 ( zero ) occurs i n the program.

2. Ar ray Index OutOfBoundsEx cept i on : T ryi ng to access an e lem ent f rom an ar ray beyond the ar ray si ze.

3. ArrayStoreExcept i on : Inv al i d assignm ent to an elem ent i n a ar ray .

4. ClassNotFoundEx cept i on : The spec i f i ed c l ass i s not av ai l ab le i n the run t im e.

5. ClassCastEx cept i on : I nv al i d type cast i ng.

6. Nul lPointerEx cept i on : I nv al i d use of NULL ref erence v ar i able.

7. Num berFormatExcept i on : I nv al i d conv ersion f rom st r i ng data to num eri c data.

8. Except i on : Ex cept i on i s the super c l ass f or al l t he ex cept i ons. Thi s c l ass can be used to handle a l l t he unspec i f i ed ex cept i ons i n the program .

Throwing an Exception : W e can a l so throws an ex cept i on using the ‘ throw ‘ key word. W e can throw a predef i ned ex cept i on or an user def i ned ex cept i on. W e general ly throw ex cept i ons whenev er a condi t i on i s not sat i sf i ed etc . ,

Page 61: Java

SATEESH N

61 SATEESH N

Out put:

OKOKArithmetic Error Occured

Out put:

OKOKArithmetic Error Occured

Example : TryThrowCatch.java

/ / Th i s program throws a predef i ned ex cept i on and such ex cept i on wi l l be handled i n 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 {

f1(2);f1(5);f1(0);

} catch(ArithmeticException ex) {

System.out.println("Arithmetic Error Occured"); } catch(NegativeArraySizeException ex) {

System.out.println("Invalid size for Array"); }

}}

instanceof key word : Th i s operator i s used f or i dent i f y i ng the type of the cl ass f or the g iv en objec t .

Example : instanceofKW. java

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 {

f1(2);f1(5);f1(0);

} catch(Exception ex) {

Page 62: Java

SATEESH N

62 SATEESH N

if(ex instanceof ArithmeticException) System.out.println("Arithmetic Error Occured");

else if(ex instanceof NegativeArraySizeException) System.out.println("Invalid Array size");

} }}

f inal ly block : The f i nal l y b l ock can be giv en imm ediatel y af ter the t ry b l ock or af ter a l l t he catch b locks. The f i nal ly b l ock i s a lway s ex ecuted whether or not an ex cept i on i s thrown i n the program.

Ex: t ry ( ) t ry ( ){ {

} }f i nal l y( ) catch( ){ {

} }catch( ){

}f i nal l y( ){

}

throws key word : W henev er a f unc t i on i s supposed to throw an ex cept i on the f unct i on should be p laced i n a t ry b l ock at the t im e of cal l i ng i t and we should handle the cor responding Ex cept i on. I f doesn’ t requi red to handle the ex cept i on we can spec i f y that ex cept i on nam e using the throws keyword.

Ex : - - - - c l ass d i sp lay { publ i c sta t i c v oid m ain(St r i ng args[ ] ) throws Ex cept i on - - - - }

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.

Throwing an user def ined except ion : To c reate an user ex cept i on, c reate a c l ass that ex tends the ex cept i on cl ass. The ex cept i on cl ass ex tends the throwable c l ass.

Throwable

Except i on

User Def i ned Ex cept i on

An i nstance of the user except i on can be thrown using the ‘ throw ‘ keyword.

Page 63: Java

SATEESH N

63 SATEESH N

Out put:

OKOKSecond Exception Occured

Example : UserDefExcept ion. java

/ / I n the f ol l owing program the f unct i on f1( ) takes an i n teger argum ent and throws e i ther myex cept i on1 or m yexcept i on2 depending on v ari ous condi t i ons.

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

elseSystem.out.println("OK");

} public static void main(String args[]) {

try {

f1(3);f1(2);f1(-2);

} catch(MyException1 ex) {

System.out.println(ex); // calls ex.toString() } catch(MyException2 ex) {

System.out.println(ex); // calls ex.toString() }

}}

Page 64: Java

SATEESH N

64 SATEESH N

Str ing Handl ing

Str ing Class : The St r i ng c l ass i s used f or m anaging st r i ng data. I t i s conta in i ng const ruc tors and m ethods to deal wi th the st r i ng data.

Constructors :

St r i ng( ) : Creates a st r i ng wi thout any data.

St r i ng(char ar r [ ] ) : Creates a st r i ng wi th charac ters i n the giv en ar ray.

Ex : char arr [ ] = { ‘a ’ , ’b ’ , ’c ’ } ; ar r a b c

St r i ng st r = new St r i ng( ar r ) ; st r “abc”

St r i ng( S t r i ng st r ) : Creates a st r i ng f rom another st r i ng.

Methods :

i n t l ength( ) : Returns the l ength of the st r ing.

char charAt ( i nt i ndex ) : Returns the charac ter a t the spec i f i ed i ndex .

Ex: S t r i ng st r = “Test i ng” ;

System.out .pr i n t l n(st r . l ength( ) ) ; 7

System.out .pr i n t l n(st r . charAt(3) ) ; ‘ t ’

Boolean equal s( S t r i ng s2) : I f t he cur rent st r i ng i s s1, s1 wi l l be com pared wi th s2 and returns t rue i f both are equal , o therwi se f alse.

Ex : S t r i ng s1 = “abc”;S t r i ng s2 = new St r i ng( “abc” ) ;S t r i ng s3 = s1;

i f ( s1 == s2 ) f al se, because == operator com pares wi th the ref erences i .e , hash codesi f ( s1 == s3 )

t ruei f ( s3 == s1 )

i f ( s1.equal s(s2 ) t ruei f ( s1.equal s(s3) ) t ruei f ( s2.equal s(s3) ) t rue

boolean equal sIgnoreCase( St r i ng s2 ) : Com pares the st r i ngs wi thout case sensi t iv eness.

i n t com pareTo( Str i ng s2 ) : I f cur rent st r ing i s s1,s1 wi l l com pare wi th s2 and returns a v alue f rom the f ol l owing table.

re turn v a lue i f

< 0 s1 < s1 > 0 s1 > s2 = 0 s1.equal s( s2) = = t rue

com pari si on depending on ASCI I v alues.

St r i ng toUpperCase( ) : Returns the st r i ng to the upper case.

Page 65: Java

SATEESH N

65 SATEESH N

Note: In any of the st r i ng func t i ons the source wi l l not be m odi f i ed. Onl y the return v alue cotains the m odi f i ed data.

Ex : S t r i ng st1 = “Hel l o” ;S t r i ng st2 = st1. toUpperCase( ) ;

System.out .pr i n t l n(st1) ; Hel l o No change i n sourceSystem.out .pr i n t l n(st2) ; HELLO Modi f i ed v alue

St r i ng toLowerCase( ) : Returns the st r i ng to the l owercase.

St r i ng t r im ( ) : Rem ov es the l eading and t rai l i ng spaces.

Ex: st1 = “ abc xyz “ ;st2 = st1. t r im( ) ; “abc x yz”

boolean star t sW i th(St r i ng st ) : Com pares the beginning and ending por t i ons of the

boolean endsW ith(St r i ng st ) : S t r i ng.

Ex : St r i ng st = “Thi s i s to test ” ;

i f ( st . star t sW i th( “Thi s” ) ) Both are t rue.

i f ( st .endsW i th( “Test ” ) )

S t r i ng subst r i ng( i n t star t Index , i nt endIndex ) : Ex t racts a por t i on of the st r i ng f rom star t i ndex to end i ndex -1.

St r i ng subst r i ng( i n t star t Index ) : Ex t rac ts f rom star t i ndex to ending of the st r i ng.

i n t i ndex Of ( ) :

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 onthe end. The new String reference is assigned to rev (the old String is now garbage).

Page 66: Java

SATEESH N

66 SATEESH N

This is fine for programs that do a moderate amount of charactermanipulation. But such abundant construction of objects will slow down a program that does a great deal of character manipulation. Such programs areword processors, compilers, assemblers, data base programs, and many others.

*/

St ri ng Buff er : A St r i ngBuff er ob ject hol ds a St r i ng of charac ters that can be changed by appending charac ter s at the end and by i nser t i ng charac ters. Howev er , unl i ke a char ar ray, a St r i ngBuff er com es wi th m any m ethods conv enient f or c h a r a c ter mani pulat i on. A St ri ngBuff er autom ati cal ly grows i n l ength as needed.

Constructors :

publ i c St ri ngBuff er () : c reate an em pty St ri ngBuff er

publ i c St ri ngBuff er ( i nt capaci ty ): c reate a St r i ngBuf fer wi th i ni t i al room f or capaci t y characters

publ i c St ri ngBuff er (Str i ng st) : c reate a St r i ngBuf fer containi ng the characters f rom st

Usual l y, i f program ex ecut i on speed i s a concern, you should dec lare a St ri ngBuf f er to be j ust som ewhat l arger than you might need. Thi s doesn ' t waste m uch space and put s f ew dem ands on the run-t ime system .

As wi th arrays, St ri ngBuff er i ndex es start a t 0 and go up to l ength-1. Som eSt ri ngBuff er methods are:

Methods :

St ri ngBuff er append( char c ) : Append c to the end of the St ri ngBuff er

St ri ngBuff er append( i nt i ) : Conv ert i t o charac ters, then append them to the end of the St ri ngBuf f er , sam e f or other prim i t ive data types.

St ri ngBuff er append( St ri ng s ) : Append the characters i n s to the end of theSt ri ng Buff er.

i nt capaci ty () : Return the cur rent capacit y (capaci ty wi l l grow as needed).

char charAt ( i nt i ndex ) : Get the character a t i ndex .

St ri ngBuff er i nsert ( i nt i ndex , char c ) : Insert character c at i ndex (ol d characters m ov e ov er to m ake room ).

St ri ngBuff er i nsert ( i nt i ndex , Str i ng st ): Insert characters f rom st start i ng at posi ti on i .

S t ri ngBuff er i nser t ( i nt i ndex , i nt i ) : Conv er t i t o charac ters, then i nser t them star t i ng a t i ndex , sam e f or other data types

i nt l ength( ) : Return the num ber of charac ters.

StringBuffer reverse() : Rev erse the order of the characters.

v oi d setCharAt ( i nt i ndex , char c ) : Set the charac ter at i ndex to c.

St ri ng toSt r i ng() : Return a St ri ng obj ect containi ng the characters i n the St ri ngBuff er.

Page 67: Java

SATEESH N

67 SATEESH N

// In this version of reverse(), only two new objects are created: theStringBuffer 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 stringint my_int = 3; // approach 1String my_str = Integer.toString(my_int);System.out.println("int to String (1): "+my_str);// approach 2String my_str2 = ""+my_int;System.out.println("int to String (2): "+my_str2);

// Converting string to intString str; str = "25";

// approach 1 int i =Integer.parseInt(str); System.out.println("String to int (1): "+i);

// approach 2

i = Integer.valueOf(str).intValue();System.out.println("String to int (2): "+i);

// Converting string to longlong l = Long.valueOf(str).longValue();System.out.println("String to long : "+l);

// Converting string to floatstr = "25.6";float f = Float.valueOf(str).floatValue();System.out.println("String to float : "+f);

// Converting string to doubledouble d = Double.valueOf(str).doubleValue(); System.out.println("String to double : "+d);

} }

output :

int to String (1): 3int to String (2): 3String to int (1): 25String to int (2): 25String to long : 25String to float : 25.6String to double : 25.6

Page 68: Java

SATEESH N

68 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--> while more information read information--> close the stream

--> open a stream--> while more information write information--> 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.

Page 69: Java

SATEESH N

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

Page 70: Java

SATEESH N

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

Page 71: Java

SATEESH N

71 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

CharArrayReaderCharArrayWriterByteArrayInputStreamByteArrayOutputStream

Use these streams to read from and write to memory. You create these streams on an existing array and then use the read and write methods to read from or write to the array.

Memory

StringReaderStringWriterStringBufferInputStream

Use StringReader to read characters from a String in memory. Use StringWriter to write to a String. StringWriter collects the characters written to it in a StringBuffer, which can then be converted to a String.StringBufferInputStream is similar to StringReader, except that it reads bytes from a StringBuffer.

Pipe

PipedReaderPipedWriterPipedInputStreamPipedOutputStream

Implement the input and output components of a pipe. Pipes are used to channel the output from one thread into the input of another.

File

FileReaderFileWriterFileInputStreamFileOutputStream

Collectively called file streams, these streams are used to read from or write to a file on the native file system.

ConcatenationN/ASequenceInputStream Concatenates multiple input streams into one input stream.

ObjectSerialization

N/AObjectInputStreamObjectOutputStream

Used to serialize objects.

DataConversion

N/ADataInputStreamDataOutputStream

Read or write primitive data types in a machine-independent format.

CountingLineNumberReaderLineNumberInputStream

Keeps track of line numbers while reading.

Peeking AheadPushbackReaderPushbackInputStream

These input streams each have a pushback buffer. When reading data from a stream, it is sometimes useful to peek at the next few bytes or characters in the stream to decide what to do next.

PrintingPrintWriterPrintStream

Contain convenient printing methods. These are the easiest streams to write to, so you will often see other writable streams wrapped in one of these.

Buffering

BufferedReaderBufferedWriterBufferedInputStreamBufferedOutputStream

Buffer data while reading or writing, thereby reducing the number of accesses required on the original data source. Buffered streams are typically more efficient than similar nonbuffered streams and are often used with other streams.

Filtering

FilterReaderFilterWriterFilterInputStreamFilterOutputStream

These abstract classes define the interface for filter streams, which filter data as it's being read or written.

Page 72: Java

SATEESH N

72 SATEESH N

Converting between Bytes and Characters

InputStreamReaderOutputStreamWriter

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 encoding or a character encoding specified by name.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.

Fi le : 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.

Constructor :

F i l e(St r i ng pathnam 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 ong l ength( ) : Returns the l ength of the f i l e. I t returns 0 i f f i l e i s not av ai l able.

boolean i sDi rectory ( ) : Returns 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..

boolean i sFi l e( ) : Returns t rue i f t he g iv en path represents a f i l e o therwi se f al se.

boolean delete( ) : Deletes the f i l e or d i rectory , i f i t ex i sts.

boolean ex i sts( ) : Returns 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.

boolean 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 lelen. java

/ / t o f i nd the l ength of the f i l e

import java.io.*;

class FileLength{ public static void main(String args[]) {

Page 73: Java

SATEESH N

73 SATEESH N

Out put:

d://sateesh_inputfile.java file size: 13662

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

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

Page 74: Java

SATEESH N

74 SATEESH N

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

ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());

int inBytes = inStream.available();

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

OutPut :

outstream: This is a test.size: 15inStream has 15 available bytes15 bytes were readThey are: This is a test.

Page 75: Java

SATEESH N

75 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()); int ch=0; StringBuffer sb = new StringBuffer(""); while((ch = in.read()) != -1) sb.append((char) ch); 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.

output :

outstream: This is a test.size: 1515 characters were readThey are: This is a test.

Page 76: Java

SATEESH N

76 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) sb.append((char) ch);

s = sb.toString();

System.out.println(s.length()+" characters were read"); System.out.println("They are: "+s);}}

Fi leInputStream : Thi s c l ass i s used f or opening a f i l e i n the i nput m ode and a l l ows us to read the contents of the f i l e .

Constructor :

F i l e InputSt ream (St r i ng f i l enam e) throws F i leNotFoundEx cept i on : Opens the g iv en f i l e i n the i nput m ode. I f t hi s f i l e can’ t be opened the F i l eNotFoundEx cept i on wi l l be thrown.

Methods :

i n t read( ) throws IOEx cept i on : Reads a c harac ter f rom the f i l e and returns the ASCI I v alue of that charac ter . I t re turns –1 or EOF.

v oid cl ose( ) throws IOEx cept i on : Closes the opened f i l e.

Output :

outstream: This is a test.size: 1515 characters were readThey are: This is a test.

Page 77: Java

SATEESH N

77 SATEESH N

Out put:

This sample file is created for testing io streams.

fileinputstreamreader,fileoutputstreamreader,bufferedreader etc.,

Fi leOutputStream : Opens a f i l e i n the output m ode, whi ch a l l ows us to wr i te the data i n to the f i l e .

Constructor :

F i l eOutputStream (St r i ng f i l enam e) throws IOEx cept i on : This constructor creates a FileOutputStream that sends its output to the file named by the specified String.

F i l eOutputStream (Fi l e f i l eobjec t) throws IOEx cept i on : 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.

Example: FileIP_OPStreams.java

/ / Th i s program takes a f i l e nam e, opens t hat f i l e and d i sp lays the content s of f i l e on console.

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) { // Displaying on console System.out.print( (char) ch); // Wrinting into output file fout.write(ch); ch = fin.read(); // read remaining characters }

fin.close(); fout.close();

} catch(FileNotFoundException ex) { System.out.println("File not found"); }

Page 78: Java

SATEESH N

78 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 orthe 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;

Page 79: Java

SATEESH N

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

}}

SequenceInputStream : The SequenceInputStream creates a single input stream from multiple input sources.

Constructors :

SequenceInputStream(InputStream s1, InputStream s2) : This constructor creates a SequenceInputStreamthat 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.

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

}

Output :

One file is copied. (D://sateesh_outputfile.txt)

Page 80: Java

SATEESH N

80 SATEESH N

catch (IOException e){ System.err.println("Concatenate: " + e);}

}}

Example : Concatenate_SeqIS_Ex2.java

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.SequenceInputStream;import java.util.Enumeration;import java.util.Vector;

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) System.out.write(c);

s.close();}catch (IOException ex){System.err.println("Concatenate: " + e);}

}}

Data Stream Classes : A problem with the FileInputStream and FileOutputStream classes is that they only work at the byte level. What do you do when you need to read integers, write floating-point values, and read or write some other non-byte value from/to a file? The answer is to use Java's DataInputStream and DataOutputStream classes.

As with the buffered stream classes, the data stream classes are designed so that their objects can be chained to other streams. However, you can only chain data stream objects to byte-oriented streams. For example, you can chain a data input stream to a FileInputStream object and call the data input stream's methods to read integer, floating-point, and other data items, but you cannot directly chain a data input stream object to a FileReader object.

Output :

Same as above program

Output :

File name: sateesh_fiel1.txt

This sample file is created for testing io streams.

inputstreamreader,outputstreamreader,bufferedreader etc.,

File name: sateesh_fiel2.txt

redgreenblueyellowblack

Page 81: Java

SATEESH N

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

Constructor :

public DataInputStream(InputStream in) : This constructor creates a DataInputStream object that reads from, or wraps, the given input stream.

DataOutputStream : 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.

Consturctors :

public DataOutputStream(OutputStream out) : This constructor creates a DataOutputStream that uses outas its underlying stream.

Data Type Method

boolean wr i teBoolean(boolean v ) ;

by te wr i teByte( i n t v );wr i teBytes(St r i ng s) ;

char , st r i ng wr i teChar ( i n t v );wr i teChars(St r i ng s) ;

double wr i teDouble(double v ) ;

f l oat wr i teF loat(f l oat v );

i n t wr i te In t ( i n t v );

l ong wr i teLong( l ong v );

shor t wr i teShor t ( i nt v );

st r i ng wr i teUTF(St r i ng 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

Page 82: Java

SATEESH N

82 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 ++){ System.out.print(sal[i]);

out.writeDouble(sal[i]); System.out.print(" "); out.writeChar('\t'); System.out.print(dept[i]); out.writeInt(dept[i]); System.out.print(" "); out.writeChar('\t'); System.out.print(employees[i]); out.writeChars(employees[i]); System.out.println(); out.writeChar('\n');}out.close();

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

}}

Output :Writing...........Salary DeptNo EmployeeName6000.0 12 Sateesh7700.0 8 Ravi Kumar8600.0 13 Srinivas8000.0 29 Kishore12000.0 50 VarmaReading...........Salary DeptNo EmployeeName6000.0 12 Sateesh7700.0 8 Ravi Kumar8600.0 13 Srinivas8000.0 29 Kishore12000.0 50 Varma

Page 83: Java

SATEESH N

83 SATEESH N

Reading l ines f rom the f i le : I n order to read l i ne f rom any i nput st ream the f ol l owing 2 cl asses are used.

1. InputSt ream Reader , 2 . Buf feredReader .

BufferedReader : The Buf f eredReader , buf fers the charac ters and conv er ts them in to the st r i ng f ormat .

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 :

St r i ng readLine( ) throws IOEx cept i on : Reads a l i ne (St r i ng) f rom giv en i nput st ream or null if the end of the stream has been reached.

InputStreamReader : The InpurSt ream Reader , reads the data f rom the g iv en i nput st ream in the by te f ormat and conv er ts i n to the charac ter f orm at. i . e . , the InputSt ream Reader conv er ts the data f rom the by te st ream s to charac ter st ream 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).

Constructors :

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 enam e : ISR_BR_ReadLineNos.java

/ / t o accept a f i l e nam e as comm and l i ne argum ent and to d i sp lay the contents of f i le a l ong wi th the l i ne no’s.

import java.io.*;

class ISR_BR_ReadLineNos{ public static void main(String args[]) {

Page 84: Java

SATEESH N

84 SATEESH N

Out put:

1: 2: This sample file is created 3: for testing i/o streams.4: 5: InputStreamReader,6: OutputStreamReader,7: BufferedReader etc.,

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;while( str != null){ n++; System.out.println(n+": "+str); str = br.readLine();}

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.

Page 85: Java

SATEESH N

85 SATEESH N

Out put :

Enter 5 strings:

RedGreenBlueYellowBlack

BlackYellowBlueGreenRed

Example : LineNumberReader_Ex1.java

import java.lang.System;import java.io.LineNumberReader;import java.io.FileReader;import java.io.BufferedWriter;import java.io.IOException;

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

Reading l ines f rom the keyboard : To read l i nes f rom the key board the system . in should be at ta tched to the Buf feredReader .

Example : ISR_BR_ReadLines. j ava

/ / t o accept 5 l i nes f rom the key board and d i sp lay them in the rev erse order .

import java.io.*;

class ISR_BR_ReadLines{ public static void main(String args[]) {

try{ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader stdin = new BufferedReader(isr);

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

int i;

String arr[] = new String[5];

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

}

Output :

1.2. This file is created 3. for testing io streams.4. 5. fileinputstreamreader,6. fileoutputstreamreader,7. bufferedreader etc.,

Page 86: Java

SATEESH N

86 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 OutputStreamWriterthat 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 bis 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 : PrintWri ter_KB. java

/ / t o accept 5 l i nes f rom the key board and sav e them in the f i l e sateesh_output f i l e . tx t ( f i l enam 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"));

Page 87: Java

SATEESH N

87 SATEESH N

Output :

Enter source file name: D://sateesh_inputfile.txtEnter target file name: D://sammm.txtCopied

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

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

out.println(str); //write into out, i.e, into file }

stdin.close(); out.close(); System.out.println("File Created.."); }

catch(Exception ex) { System.out.println("error:"+ex); } }}

Example: CopyFi le_PW.java

/ / t o copy data f rom the 1st f i l e to 2nd 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 filenameSystem.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 modeBufferedReader in = new BufferedReader(new InputStreamReader(new

FileInputStream(sourcefname)));

// open the target file in output modePrintWriter out = new PrintWriter(new FileOutputStream(targetfname));

// start reading from source and copy each line to the targerString str = in.readLine(); // from the source file

while(str!=null){

out.println(str); // write into targer str = in.readLine();

}in.close();out.close();

Output :

Enter: redEnter: greenEnter: blueEnter: yellowEnter: blackFile Created..

Page 88: Java

SATEESH N

88 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.errobjects 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 PipedWriterto 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.

Page 89: Java

SATEESH N

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

Page 90: Java

SATEESH N

90 SATEESH N

PipedWriter pw = new PipedWriter (); PipedReader pr = new PipedReader (pw);

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

mt1.start ();

try { Thread.sleep (2000); } catch (InterruptedException e) { }

mt2.start (); }}

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 :

Output :

src A0src A1src A2src A3src A4src A5src A6src A7src A8src A9src A10src A11src A12src A13src A14

Page 91: Java

SATEESH N

91 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 parameterthat 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 DataOutputinterfaces, 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); file.writeChar('j'); file.writeDouble(1234.56); file.seek(1); System.out.println(file.readInt()); System.out.println(file.readChar()); System.out.println(file.readDouble()); file.seek(0); System.out.println(file.readBoolean()); file.close();}}

Output :

123456j1234.56true

Page 92: Java

SATEESH N

92 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 svalcontains 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.

Page 93: Java

SATEESH N

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

Example:

import java.lang.System;import java.io.StreamTokenizer;import java.io.InputStreamReader;import java.io.BufferedReader;import java.io.IOException;

public class StreamTokenizer_Ex1{public static void main(String args[]) throws IOException{ 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);}}

Output :

Word: DOB: encountered.Word: Date- encountered.Number: 3.0Word: Month- encountered.Number: 10.0Word: Year- encountered.Number: 1979.0EOF encountered.

Page 94: Java

SATEESH N

94 SATEESH N

Out put:

E:\Core>javac inteclas.javaE:\Core>java inteclas

Enter a number :10Enter another :20Total is : 30

E:\Core>

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.

Integer c lass :

publ i c sta t i c i n t parseInt (Str i ng st r ) throws Num berForm atEx cept i on

The parseInt f unc t i on av ai l ab le i n the i nteger c l ass takes a st r i ng and conv erts i n to the num er ic f ormat .

/ / f i l e nam e : in teclas. java

/ / t o accept 2 num bers f rom the key board and d i sp lay the to tal .

im por t j av a. i o. * ;im por t j av a. l ang. *;

c l ass i n tec las{ publ i c sta t i c v o id m ain(St r i ng args[ ] ) { t ry { / / key board

Buf f eredReader std i n = new Buf f eredReader ( new InputSt ream Reader (System .i n) );

S t r i ng st r ;

i nt a ,b,c ;

System .out .pr i nt l n( "Enter a num ber : ") ;

st r = std i n . readLine(st r ) ;

a = Integer .parseInt (st r ) ;

System .out .pr i nt l n( "Enter another : " ) ;

st r = std i n . readLine(st r ) ;

b = Integer .parseInt (st r ) ;

c = a + b;

System .out .pr i nt l n( "Total i s : "+c); } catch(Num berForm atExcept i on ex ) { System .out .pr i nt l n( "Conv ersion f i nal " ) ; } catch(IOEx cept i on ex ) { System .out .pr i nt l n( "Er ror : "+ex ); } }}

Page 95: Java

SATEESH N

95 SATEESH N

MULTI THREADING:

One of the m ain adv antage i n j av a programming i s, i t suppor ts m ul t i t hreaded program s.

A m ul t i t hreaded program i s program that conta ins 2 or m ore parts that runs concur rent l y. Each part of a program i s ca l led a thread.

Mul t i t hreading enables us to run m ul t i p l e par ts o f the program at the sam e t ime.

Creat i ng a Thread : I n j av a a thread can be c reated i n 2 ways.

i . usi ng the Thread cl ass i i . Using Runnable i nterf ace

i . Thread c l ass : Thread c l ass i s the m ain c l ass to m anage a l l t he threads i n a j av a program . i .e . , threads that are c reated ei ther by the Thread cl ass or wi th he lp of Runnable i n terf ace can only be cont rol l ed by the Thread c l ass.

Each Thread contains nam e, pr i or i t y , Thread group etc . ,

Const ruc tors:

Thread( St r i ng nam e ) : creates a thread wi th spec i f i ed nam e.

Thread( ) : c reates a thread wi th a def aul t nam e.

Thread( Runnable r , S t r i ng nam e) : Creates a thread using the runnable i n terface.

Thread(Runnable r ) :

Methods:

v oid star t ( ) : star t s the Thread. i . e . , the thread wi l l be added to the thread Queue

St r i ng getNam e( ) : Returns the nam e of the thread.

v oid setNam e(St r i ng newNam e) : changes the nam e of the Thread.

v oid setPri or i t y ( i n t pr i or i t y) : Changes the pr i or i t y of the Thread. Min. pr i or i t y i s: 1 Max.pr i or i t y i s: 2 def aul t i s : 5

i n t getPri or i t y ( ) : Returns the cur rent pr i or i t y of the thread.

boolean i n l iv e( ) : Returns t rue i f t he Thread i s st i l l running, o therwi se f al se.

stat i c Thread cur rentThread( ) : Returns the cur rent thread.

stat i c v oid sl eep( l ong m i l l i seconds ) throws In ter ruptedEx cept i on : Makes the thread to sl eep f or the spec i f i ed t im e.

v oid j oi n( ) throws In ter ruptedEx cept i on : Makes the cur rent thread to wai t unt i l t he spec i f i ed thread f i ni shes.

v oid i n ter rupt ( ) : I n ter rupts a sl eeping thread.

Main Thread : W henev er we run a j av a program the program wi l l be p laced i n an a l ready running thread whi ch i s known as m ain Thread. Al l t hreads that are c reated i n the program wi l l be the ch i l d threads of the m ain Thread. W henev er the m ain Thread stops the program wi l l be terminated.

In the f ol l owing ex am ple a re f erence of the m ain Thread wi l l be obta ined using the cur rent Thread f unc t i on.

Page 96: Java

SATEESH N

96 SATEESH N

Out put:

E:\Core>javac thread.javaE:\Core>java thread

Count is : 0Count is : 1Count is : 2Count is : 3Count is : 4Count is : 5Count is : 6 Count is : 7Count is : 8Count is : 9Count is : 10Finished . . .

E:\Core>

Out put:

E:\Core>javac thread2.javaE:\Core>java thread2

Count is : 0Count is : 1Count is : 2Count is : 3Count is : 4Count is : 5Count is : 6 Count is : 7Count is : 8Count is : 9Count is : 10Finished . . .

E:\Core>

Ex: v oid m ain( ){ Thread r = Thread.cur rentThread( ) ;

r . s l eep(2000) ; - - - - - - -

- - - - - --}

/ / f i l enam e: thread. java

/ / The f ol l owing program pri n ts the v alues f rom 1 to 10, f or each i terat i on the m ain Thread sl eeps f or 1 second.

c l ass thread{ publ i c sta t i c v o id m ain(St r i ng args[ ] ) { Thread r = Thread.cur rentThread( ) ; / / m ain Thread

f or ( i nt i =0; i<=10; i++ ) { System.out .pr i n t l n( "Count i s: "+ i ) ;

t ry { r . s l eep(1000) ; } catch( In ter ruptedExcept i on ex ) { System .out .pr i n t l n( "Main Thread In ter rupted" ) ; } } System.out .pr i n t l n( "Fini shed . . . " ) ; }}

/ / f i l enam e: thread2. java

/ / sam e as abov e program

class thread2{ publ i c sta t i c v o id m ain(St r i ng args[ ] ) { f or ( i nt i =0; i<=10; i++ ) { System.out .pr i n t l n( "Count i s: "+ i ) ; t ry { Thread.sl eep(1000) ; / / Main Thread } catch( In ter ruptedExcept i on ex ) { System .out .pr i n t l n( "Main Thread In ter rupted" ) ; } } System.out .pr i n t l n( "Fini shed . . . " ) ; }}

Page 97: Java

SATEESH N

97 SATEESH N

Out put:

E:\Core>javac multhread.javaE:\Core>java multhread

Second Thread : 30First Thread : 1First Thread : 2

Second Thread : 29First Thread : 3First Thread : 4

Second Thread : 28First Thread : 5First Thread : 6

Second Thread : 27First Thread : 7First Thread : 8

Second Thread : 26First Thread : 9First Thread : 10

E:\Core>

creat ing a Thread us ing th read c lass : The f i rst way of c reat i ng a thread, i s to c reat i ng a c l ass that ex tends the Thread cl ass. W henev er a c l ass ex tends the Thread c l ass the f ol l owing f unc t i on should be ov er r i dden.

publ i c v oid run( ) : W henev er we star t the thread using the star t m ethod the thread wi l l be added to the thread queue and the thread ca l l s the run( ) f unc t i on. i . e, a l l t he statem ents i n the run( ) f unct i on wi l l be ex ecuted i n a separate process.

/ / f i l enam e: multhread.java

/ / I n the f o l l owing ex am ple 2 threads wi l l be c reated, the 1 s t t hread pr i n ts the v alues f rom 1 to 10 wi th t im e of 1 sec . . f or each i terat i on, the 2 n d thread pr i n ts the v alues f rom 30 to 26 wi th the gap of 2 sec . f or each i terat i on, both the threads are using around 10 sec . both the threads wi l l be star t a t the sam e t im e.

c l ass F i rstThread ex tends Thread{ publ i c v oid run( ) { f or ( i n t i=1; i<=10; i++) { System .out .pr i n t l n( "Fi rst Thread: "+ i ) ; t ry { Thread.sl eep(1000) ; } catch( Inter ruptedEx cept i on ex ) { System .out .pr i nt l n("Fi rst Thread In ter rupted" ) ; } }}c l ass SecondThread ex tends Thread{ publ i c v oid run( ) { f or ( i n t i=30; i >=26; i - - ) { System .out .pr i n t l n( " Second Thread: "+ i ) ; t ry { Thread.sl eep(2000) ; } catch( Inter ruptedEx cept i on ex ) { System.out .pr i n t l n( "Second Thread In ter rupted" ) ; } } }}c l ass m ul thread{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { F i rstThread f = new F i rstThread( ) ; SecondThread s = new SecondThread( ) ;

s. star t ( ) ; f . star t ( ) ; }}

Page 98: Java

SATEESH N

98 SATEESH N

Out put:

E:\Core>javac mymulthread.javaE:\Core>java mymulthread

Second : 26First : 1First : 2

Second : 27First : 3First : 4

Second : 28First : 5First : 6

Second : 29First : 7First : 8

Second : 30First : 9First : 10Finished . . .

E:\Core>

/ / f i l enam e: mymul thread. java

/ / t he f ol l owing program i s enhancem ent f or the prev ious program whi ch prov ides onl y one thread c l ass wi th m ul t i pl e i nstances. For th i s purpose the star t v a lue, ending v a lue etc . , wi l l be taken as param eters.

c l ass MyThread ex tends Thread{ i n t star t ,end,delay;

MyThread(St r i ng nam e, i nt star t , i n t end, in t de lay) { setNam e(nam e) ; t hi s.star t = star t ; t hi s.end = end; t hi s.de lay = delay ;

}

publ i c v oid run( ) { / / pr i n t the v a lues

f or ( i n t i=star t ; i<=end; i++) { System .out .pr i n t l n(getNam e()+" "+ i ) ;

t ry { Thread.sl eep(delay) ; }

catch(In ter ruptedEx cept i on ex) { System.out .pr i n t l n(getNam e()+ " Interupted" ) ; } } }}c l ass m ym ul thread{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { MyThread f = new MyThread( "Fi rst " ,1 ,10,1000) ; MyThread s = new MyThread( " second" ,26,30,2000) ;

s. star t ( ) ; f . star t ( ) ; }}

Creat ing a Thread us ing Runnab le in ter face : The second m ethod f or c reat i ng a Thread i s to c reate a c l ass that im plem ents the runnable i n terf ace. W henev er a cl ass im plem ents the runnable i n terf ace the c lass should ov err i de the f ol l owing f unc t i on publ i c v o id run( ) .

Because Jav a doesn’ t suppor t m ul t i p l e Inher i tence for cl asses we can use the runnable i n terf ace f or creat i ng a thread in the f ol l owing condi t i on. W hen we want a c l ass to ex tend another c l ass and we want th i s c l ass to work as a Thread then runnable i n terface should be used.

Page 99: Java

SATEESH N

99 SATEESH N

Out put:

E:\Core>javac runintrface.javaE:\Core>java runintrface

Second : 30First : 1First : 2

Second : 29First : 3First : 4

Second : 28First : 5First : 6

Second : 27First : 7First : 8

Second : 26First : 9First : 10

E:\Core>

/ / f i l e nam e: run intr face. java

im por t j av a. l ang. *;

c l ass f i rst im plem ents Runnable{ publ i c v oid run( ) { f or ( i n t i=1; i<=10; i++) { System .out .pr i n t l n( "Fi rst : "+ i ) ;

t ry { Thread.sl eep(1000) ; } catch(In ter ruptedEx cept i on ex) { System .out .pr i nt l n("Fi rst In ter rupted" ) ; } } }}c l ass second im plem ents Runnable{ publ i c v oid run( ) { f or ( i n t i=30; i >=26; i - - ) { System .out .pr i n t l n( " Second: "+ i ) ;

t ry { Thread.sl eep(2000) ; } catch( Inter ruptedEx cept i on ex ) { System .out .pr i nt l n("Second In terrupted" ) ; } } }}c l ass run int r f ace{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { f i r st f = new f i rst ( ) ; second s = new second( ) ;

/ / Thread t1 = new Thread( f ) ;/ / Thread t2 = new Thread(s) ;

new Thread(s) . star t ( ) ; new Thread( f ) . star t ( ) ;

/ / t 2 .star t ( ) ;/ / t 1 .star t ( ) ; }}

Page 100: Java

SATEESH N

100 SATEESH N

Out put:

E:\Core>javac synchprinterfun.javaE:\Core>java synchprinterfun

[ 1 2 3 4 5 6 7 8 9 10][ 41 42 43 44 45][ 26 27 28 29 30]

E:\Core>

Synchronization :

Synchroni zat i on i s the process of appl yi ng queue m echani sm on threads.

W hen two or m ore threads are t ry i ng to access the sam e shared dev i ce and i f t he dev i ce can’ t be shared then we should appl y synchroni zat i on.

Synchroni zat i on can be achiev ed i n two ways.

i . Synchroni zed f unct i ons i i . Synchroni zed statem ents

i . Synchron ized funct ions : Synchronizat i on can be achiev ed by pref ix i ng the f unct i on wi th the key word synchroni zed.

/ / f i l e nam e: synchprinterfun. java

c lass pr i n ter{ synchroni zed v oid pr i n t ( i n t star t , i n t end, in t de lay) { System .out .pr i nt l n( " [ " ) ;

f or ( i n t i=star t ; i<=end; i++) { System .out .pr i n t l n( " "+ i ) ;

t ry { Thread.sl eep(delay) ; } catch(In ter ruptedEx cept i on ex) { System .out .pr i nt l n("Thread Inter rupted" ) ; } }

System .out .pr i nt l n( " ] " ) ; }}c l ass user ex tends Thread{ pr i n ter p ;

i n t star t ,end,delay;

user (pr i n ter p , i n t star t , i n t end, i n t de lay) { t h i s.p = p; t h i s.star t = star t ; t h i s.end = end; t h i s.de lay = delay; }

publ i c v oid run( ) { synchroni zed(p) { p.pr i n t(star t ,end,delay); } }

}

Page 101: Java

SATEESH N

101 SATEESH N

Out put:

E:\Core>javac synchprinterstm.javaE:\Core>java synchprinterstm

[ 1 2 3 4 5 6 7

8 9 10][ 26 27 28 29 30][ 41 42 43 44 45]

E:\Core>

c lass synchpr i n ter f un{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { pr i nter p = new pr i n ter ( ) ;

user u1 = new user (p,1,10,1000) ; user u2 = new user (p,26,30,2000) ; user u3 = new user (p,41,45,1500) ;

u1.star t ( ) ; u2.star t ( ) ; u3.star t ( ) ; }}

i i . Synchron ized sta tements : Suppose i f t he f unc t i on on whi ch we wan to achiev e synchroni zat i on i s a th i rd par ty product and i f we cannot m odi f y the source code then to achiev e the synchroni zat i on we should appl y the synchroni zed statem ents.

I f t he pr i n t( ) f unc t i on i s not synchroni zed, ca l l t he pr i n t ( ) f unc t i on i s a synchroni zed b lock f or the objec t p .

/ / f i l e nam e: synchprinterstm. java

c lass pr i n ter{ synchroni zed v oid pr i n t ( i n t star t , i n t end, in t de lay) { System .out .pr i nt l n( " [ " ) ;

f or ( i n t i=star t ; i<=end; i++) { System .out .pr i n t l n( " "+ i ) ;

t ry { Thread.sl eep(delay) ; } catch( Inter ruptedEx cept i on ex ) { System .out .pr i nt l n("Thread Inter rupted" ) ; } }

System .out .pr i nt l n( " ] " ) ; }}c l ass user ex tends Thread{ pr i n ter p ;

i n t star t ,end,delay;

user (pr i n ter p , i n t star t , i n t end, i n t de lay) { t h i s.p = p;

Page 102: Java

SATEESH N

102 SATEESH N

t h i s.star t = star t ; t h i s.end = end; t h i s.de lay = delay; }

publ i c v oid run( ) { p .pr i n t (star t ,end,delay); }

}

c l ass synchpr i n terstm{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { pr i nter p = new pr i n ter ( ) ;

user u1 = new user (p,1,10,1000) ; user u2 = new user (p,26,30,2000) ; user u3 = new user (p,41,45,1500) ;

u1.star t ( ) ; u2.star t ( ) ; u3.star t ( ) ; }}

In ter Thread Communicat ion : Som e t imes the output o f one Thread wi l l be the i nput o f another Thread i .e . , i n som e cases a Thread enters i n to wai t i ng state t i l l i t rece iv es i nput f rom another Thread. Simi l ar l y, a Thread should not i f y the wai t i ng Thread, once the i nput i s ready .

The f ol l owing three f unc t i ons of the objec t c l ass are used f or comm unicat i on between the Threads.

1. publ i c v oid wai t ( ) throws In teruptedEx cept i on : Makes the cur rent thread t o wai t .

2 . publ i c v oid not i f y( ) throws In ter ruptedEx cept i on : Not i f i es the wai t i ng thread, so that the wai t i ng thread resum es.

3. publ i c v oid not i f yAl l ( ) throws In ter ruptedExcept i on : Not i f i es a l l t he wai t i ng Threads, the Thread wi th the h ighest pr i or i ty wi l l resum ef i rst .

/ / f i l e nam e : in terthread.java

/ / F l ag becom es t rue, i f t he suppl i er pass the v alue. F l ag becom es f al se, i f t he / / consum er consum es the v alue, i . e. , the queue Q was em pty .

c l ass Q{ i n t n; boolean f l ag = fa l se;

synchroni zed v oid put ( i n t n) {

Page 103: Java

SATEESH N

103 SATEESH N

Out put:

E:\Core>javac interthread.javaE:\Core>java interthread

Supplied : 1Consumed: 1Supplied : 2Consumed: 2Supplied : 3Consumed: 3Supplied : 4Consumed: 4Supplied : 5Consumed: 5Supplied : 6Consumed: 6Supplied : 7Consumed: 7Supplied : 7Consumed: 7Supplied : 8Consumed: 8Supplied : 9Consumed: 9Supplied : 10Consumed: 10

E:\Core>

t ry { i f ( f l ag == t rue) / / not at consum ed wai t ( ) ;

t hi s.n = n;

System .out .pr i nt l n( "Suppl i ed: "+n) ;

f l ag = t rue; / / j ust suppl i ed

not i f y ( ) ; / / i nf orm the custom er } catch(In ter ruptedEx cept i on ex ) { System.out .pr i n t l n( "Thread In ter rupted" ) ; } }

synchroni zed v oid get ( ) { t ry { i f ( f l ag == fa l se) wai t ( ) ; / / not suppl i ed

System.out .pr i n t l n( "Consum ed: "+n); f l ag = fa l se; / / Q was em pty

not i f y( ) ; / / not i f y the suppl i er } catch( In ter ruptedEx cept i on ex ) { System .out .pr i n t l n( "Thread In terrupted" ) ; } }}

c l ass producer ex tends Thread{ Q q;

producer (Q q) { t hi s.q = q; }

publ i c v oid run( ) { f or ( i nt i =1; i<=20; i++ ) { q .put ( i ) ; / / suppl y 20 v alues } }}c l ass consum er ex tends Thread{ Q q;

consum er(Q q) { t h i s.q = q; }

Page 104: Java

SATEESH N

104 SATEESH N

publ i c v oid run( ) { f or ( i nt i =1; i<=20; i++ ) { q.get ( ) ; / / rece iv e 20 v a lues f rom the que } }} c l ass i n ter thread{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { Q q = new Q() ;

producer p = new producer (q) ;

consum er c = new consum er(q) ;

c. star t ( ) ; p .star t ( ) ; }}

Page 105: Java

SATEESH N

105 SATEESH N

java.util.package :

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 delimitercharacters. 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 inthis 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 kumarsateeshkumar

Page 106: Java

SATEESH N

106 SATEESH N

More than one Delimiter Works :

Tokens can be separated by more than one delimiter. There are several spaces separating thetokens in the example.

Some methods of the class:

StringTokenizer Methods :

int countTokens( ) : Return the number of tokens remaining. , The countTokens() method starts with thetotal 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 nam e : StrTok2.java

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

}}

output :

Enter a string:c = a + bcab

Page 107: Java

SATEESH N

107 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 nam e : StrTok3. java

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

public class StrTok3{ 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, " =+-", true ); // note the space before =

while ( tok.hasMoreTokens() ) System.out.println( tok.nextToken() );

}}

Date, Calendar and 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.Calendarjava.util.GregorianCalendar extends java.util.Calendar

Interpretation and manipulation of Dates.

Abstract java.util.TimeZonejava.util.SimpleTimeZone extends java.util.TimeZone

Representation of an arbitrary offset from Greenwich Mean Time (GMT), including information about applicable daylight savings rules.

Abstract java.text.DateFormat extends java.text.Formatjava.text.SimpleDateFormat extends java.text.DateFormat

Transformation into well-formatted, printable String and vice versa.

java.text.DateFormatSymbolsTranslation of the names of months, weekdays, etc., as an alternative to using the information from Locale.

java.sql.Date extends java.util.Datejava.sql.Time extends java.util.Datejava.sql.Timestamp extends java.util.Date

Represent points in time, and also include proper formatting for use in SQL statements.

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.

output :Enter a string:c = a + b

c

=

a

+

b

Page 108: Java

SATEESH N

108 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 theCalendar, and a get() method you can use to retrieve the value of a field. If you look at the java.util.Calendarclass, you'll notice it defines a bunch of integer class constants, with names like DAY_OF_MONTH andMONTH. 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

Page 109: Java

SATEESH N

109 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 ADtry { //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;

Page 110: Java

SATEESH N

110 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/2005Present Year : 2005No. of Days in current Month is : 28No. of Days in current Month is : 28Day of Week is : 7Day of Month is : 19Week of Month is: 3Day of year is : 50Day 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){

e.printStackTrace(); return "";

} }}

output :

1989-10-17 was a TuesdayToday is a Saturday

Page 111: Java

SATEESH N

111 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)){

System.out.println("After");}else{

System.out.println("Equal");}

}}

// File name: ValidateDate.java

// Validate a dateimport 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 IllegalArgumentExceptiontry{ DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); df.setLenient(false); // this is important!

output :

Tue Jan 04 00:01:00 IST 2005Sat Feb 19 02:15:09 IST 2005-1Before

Page 112: Java

SATEESH N

112 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 SimpleDateFormatString 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 thisgc.set(GregorianCalendar.YEAR, 2004);gc.set(GregorianCalendar.MONTH, 11); // 12 is invalid monthgc.set(GregorianCalendar.DATE, 24);

System.out.println(gc.getTime()); // exception thrown here}catch (Exception e){

e.printStackTrace();}

}}

output :

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

Page 113: Java

SATEESH N

113 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 concreteclasses. 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.

Page 114: Java

SATEESH N

114 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

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

Page 115: Java

SATEESH N

115 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( );myList.add("Hello");myList.add(new Date());myList.add(new BankAccount());System.out.println(myList.size());

ArrayList myList = new ArrayList( );myList.add("Hello");myList.add(new Date());myList.add(new BankAccount());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);

Page 116: Java

SATEESH N

116 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 vectorfor(int i=0; i< mv.size(); i++)

System.out.println(mv.elementAt(i));

}//End of amethod}

Page 117: Java

SATEESH N

117 SATEESH N

out put :

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

}}

Page 118: Java

SATEESH N

118 SATEESH N

out put:

SateeshTharniSrinuRavi

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. Element1 one2 two3 three4 five5 six6 seven7 nine8 tenAfter Vector: [one, two, four, five, six, eight, nine, ten]

Page 119: Java

SATEESH N

119 SATEESH N

Notice that the Enumeration did NOT produce all the items. Also, the Vector, after removing, is not correctsince 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); }}

Page 120: Java

SATEESH N

120 SATEESH N

out put:

Before Vector: [one, two, three, four, five, six, seven, eight, nine, ten]Element NO. Element1 one2 two3 three4 four5 five6 six7 seven8 eight9 nine10 tenAfter 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

Page 121: Java

SATEESH N

121 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 againSystem.out.println (hash.get(new Integer(5)));

// Get value out againSystem.out.println (hash.get(new Integer(21)));

// Get all valuesEnumeration 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 : 5Number : 21Displaying all values of Hashtable.. (Hashtable is unordered )Number : 20Number : 41Number : 62Number : 83Number : 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 :

Page 122: Java

SATEESH N

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

Page 123: Java

SATEESH N

123 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: SUppercase: AUppercase: TUppercase: IUppercase: 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);

Page 124: Java

SATEESH N

124 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: -30bits: {1, 5, 6, 7}bit pattern: 0100011100000000000000000000000000000000000000000000000000000000short value: -14048bits: {5, 8, 11, 14, 15}bit pattern: 0000010010010011000000000000000000000000000000000000000000000000int value: -1916419530bits: {1, 2, 4, 5, 9, 14, 15, 16, 18, 22, 23, 24, 26, 27, 31}bit pattern: 0110110001000011101000111011000100000000000000000000000000000000

Page 125: Java

SATEESH N

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

Page 126: Java

SATEESH N

126 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 lineDecember November October September August July June May April March February January

Lang Package

Page 127: Java

SATEESH N

127 SATEESH N

Applets & AWT ( Abstract Window Toolkit ) :

Applet : An Applet i s a program designed i n j av a and wi l l be placed on the serv er. The applet wi l l be downloaded f rom the serv er to the cl i ent a l ong wi th “HTML” docum ents and runs i n the c l i ents web browser ( i . e . , an Applet wi l l run as a par t of the web docum ent ) . An applet can contain com ponents l i ke but tons, checkbox es etc . , An applet can open connect i on wi th the network serv ers, database serv ers etc. ,

AWT : AW T i s a co l l ec t i on of c l asses wh i ch prov ides graphi ca l com ponents such as but tons, tex tbox es etc . , whi ch wi l l be used i n the graphi cal i n terf ace programming.

Creat i ng an Applet : To c reate an Applet create a cl ass that ex tends the Applet c l ass.

/ / f i l e nam e : applet1. java

im por t j av a.awt . * ;im por t j av a.applet . * ;

publ i c c l ass applet1 ex tends Applet{ publ i c v oid i n i t ( ) { setBackground(Color .orange) ; }

publ i c v oid pa int (Graphi cs g) { g .setFont (new Font ( "Garam ound" ,Font.BOLD,20) ) ;

g .setColor (Color.b l ue) ; g .drawSt r i ng( "SATEESH" ,100,50) ;

g .setColor (Color. red) ; g .drawSt r i ng( "Test i ng the Applet i n Java" ,100,150) ; }}

<! - - HTML code f or applet1. j av a sav e f i l e nam e as applet1.html - - >

<html><applet code = “applet1.cl ass” width=400 height=300>< /applet>< /html>

W henev er an Applet i s be ing l oaded i n a W EB browser , the W EB browser ca l l s the f ol l owing m ethods of the Applet . W e can ov er r i de the f ol l owing m ethods depending on the requi rem ent.

1 . publ i c v o id i ni t ( ) : Thi s m ethod wi l l be ca l led whenev er the applet i s be ing l oaded i n to the W EB browser f or the f i rst t ime.

2. publ i c v oid star t ( ) : Cal l ed af ter i ni t , t his m ethod wi l l a l so be ca l l ed ev ery t im e whenev er the docum ent contain i ng the applet i s re di sp layed on the W EB browser .

3. publ i c v oid stop( ) : W henev er the use goes to the nex t docum ent.

4. publ i c v oid dest roy( ) : W henev er the Applet i s be ing rem ov ed f rom the W EB browse r For ex , the user c l oses the W EB browser .

Out put :

E:\Core> javac applet1.java

E:\Core>appletviewer applet1.html

Page 128: Java

SATEESH N

128 SATEESH N

The Applet c l ass m ust be publ i c, because the applet i s be ing ex ecuted i n another program i .e. , the Applet i s be ing ex ecuted in a W EB browser .

5. publ i c v oid pa int( Graphics g ) : Th i s m ethod wi l l be ca l l ed whenev er the output m ust be redrawn. Thi s m ethod al so receives a param eter of the graphi cs cl ass whi ch conta ins the graphi cs contex t detai l s. The graphi cs c l ass av ai l ab le i n the j av a.awt . * .

Applet c lass methods :

Applet i s the super c l ass f or a l l t he applets.

The abov e 5 m ethods can be ov er r i dden and wi l l be ca l l ed by the W EB browse r depending on the user nav igat i on on the HTML docum ents. The f ol l owing m ethods ar e a l so av ai l ab le i n the Applet cl ass whi ch can be ca l l ed i n the program depending on the requi rem ent .

v oid showStatus( S t r i ng m sg ) : D i sp lays the m essage i n the status bar o f the W EB browser .

URL getDocum entBase( ) : Returns the URL of the HTML docum ent.

URL getCodeBase( ) : Returns the URL of the Applet .

S t r i ng getParam eter (St r i ng param Nam e) : Returns the v alue of the spec i f ied param eter. I t returns nul l i f t he param eter is not av ai l able.

v oid repaint ( ) : Redraws the Applet .

v oid setBackground( co lor newcolor ) :

v oid setForeground( co lor newcolor ) :

co lor . red color .whi te color .m agenta color . l i ghtgraycolor .green color .bl ack color . yel l ow color .graycolor .bl ue color . cyan color .orange color .darkgray co lor .pi nk

color ( i n t redv alue, i nt greenv alue, i n t bl uev alue ) :

Graphics Class Methods : The Graphi c c l ass conta ins the Graphi cs contex t detai ls whi ch i s conta ini ng the fo l l owing m ethods.

1. v oid drawst r i ng( S t r i ng st r , i nt x , i n t y ) : Draws the st r i ng at (x ,y ) l ocat i ons.

2. v oid drawLine( i n t x 1, i n t y1, i nt x 2, i nt y2 ) : Draws a l i ne f rom (x 1,y1) to (x 2,y2)

3. v oid drawRect ( i nt x , i nt y, i n t width, i n t he ight ) : Draws a rec tangle at x ,y l ocat i ons wi th the g iv en width and height .

4 . v oid drawOv al ( i n t x , i n t y, i n t width, i nt he ight ) : Draws a ov al a t (x ,y) l ocat i ons wi th the g iv en width and height .

5 . v oid drawRoundRect ( i n t x , i nt y , i n t width, i n t he ight , i nt n1, i n t n2 ) : Draws a rounded rec tangle. Here n1,n2 spec i f i es the curv e detai l s.

Page 129: Java

SATEESH N

129 SATEESH N

Ex:

n1

n2

6. v oid f i l lRec t ( i nt x , i n t y , i n t width, i nt he ight ) : F i l l s the spec i f i ed l ocat i on .

7 . v oid f i l lOv al ( i nt x , i n t y , i n t width, i nt he ight ) : F i l l s the spec i f i es l ocat i on .

8 . v oid f i l lRoundRect ( i n t x , i n t y , i nt width, in t he ight , i n t n1, i nt n2 ) : F i l l s the spec i f i ed l ocat i on .

9 . v oid SetColor ( Color new color ) : Sets the drawing co lor .

10. v oid drawPolygon( Pol ygon pol y ) : Draws a pol ygon. Pol ygon i s a c l ass whi ch conta ins (x 1,y1) , (x 2,y2) , . . . , (x n,yn).

11. v oid f i l lPol ygon( Pol ygon poly ) : F i l l s the pol ygon.

Com ponent Class : Com ponent i s the super c l ass f or a l l t he c l asses, whi ch i s conta in i ng the f ol l owing m ethods.

Dim ension getSi ze( ) : Returns the si ze of the com ponent .

Ex : Publ i c Class Dim ension {

publ i c i nt width; publ i c i nt height ; }

/ / F i l e nam e: appshapes. java

im por t j av a.awt . * ;im por t j av a.applet . * ;

publ i c c l ass appshapes ex tends Applet{ publ i c v oid i ni t ( ) { setBackground(Color .b l ack) ; } publ i c v oid paint (Graphi cs g) { D im ension d = getSi ze( ) ; i nt w = d.width; i nt h = d.he ight ; cont….

/ / set t i ng a po lygon

i nt x [ ] = {0 ,w/2,w,0,w} ; i nt y[ ] = {h ,0,h,h/2,h/2};

Polygon pol y = new Pol ygon(x ,y ,5);

/ / 5 co-ordinat tes

Out Put :

E:\Core> javac appshapes.java

E:\Core> appletviewer appshapes.html

Page 130: Java

SATEESH N

130 SATEESH N

g .setColor (Color. l i ghtGray); g . f i l lPo lygon(pol y ) ;

g .setColor (Color.cyan) ; g .drawLine(0,0,w,h) ;

g .setColor (Color.yel l ow) ; g .drawRect (4,4,w-8,h-8) ; g .drawOv al (8,8,w-16,h-16) ;

g .setColor (Color.green) ; g . f i l lRoundRect (25,125,150,75,15,15) ;

g .setFont (new Font ( "T imes new Rom an" ,Font .BOLD,14) ) ; g .setColor (Color.b l ack) ; g .drawSt r i ng( "Sam ple Shapes" ,30,150) ; }}

Sending Parameters : W e can send param eters to an Applet using the param tag i n the HTML docum ent . Each param eter conta ins a nam e and a v a lue. A j av a applet can ret r i ev e the v alues of the param eters using the f ol l owing f unct i on.

St r i ng getParam eter ( S t r i ng param Nam e ) : Returns the v alue whi ch i s assigned to param Nam e i n html code.

/ / HT ML Code

< ! – appsendpara.html - - ><html> <body> <applet code = "appsendpara.c l ass" width=300 height=400> <param nam e = "em pno" v alue="101"> <param nam e = "enam e" v alue="Sateesh ra j "> <param nam e = " j ob" v alue="MGR"> < /applet> < /body>< /html>

/ / F i l e nam e : appsendpara. java

im por t j av a.awt . * ;im por t j av a.applet . * ;

publ i c c l ass appsendpara ex tends Applet{ S tr i ng p1,p2,p3;

publ i c v oid i ni t ( ) { setBackground(Color .cyan) ;

/ / Ret r i ev e the v alues of the param eters

p1 = getParam eter ( "em pno" ); p2 = getParam eter ( "enam e"); p3 = getParam eter ( " j ob" ) ; }

Out Put :

E:\Core> javac appshapes.java

E:\Core> appletviewer appshapes.html

Page 131: Java

SATEESH N

131 SATEESH N

publ i c v oid paint (Graphi cs g) { g .setColor (Color . red); g .setFont(new Font ( "Com ic Sans" ,Font .BOLD,14) ) ;

/ / di sp lays the param eter v alues

g .drawSt r i ng(p1,50,50) ; g .drawSt r i ng(p2,50,100) ; g .drawSt r i ng(p3,50,150) ; }}

Drawing Images on the Applet : To present an im age on the applet , the im age should be l oaded i n to m emory using one of the f ol l owing f unct i ons.

Im age get Im age( URL codebase, S t r i ng image ) :

Im age get Im age( URL ur l _of _im age ) :

To draw the im age the graphi cs cl ass prov id i ng the f ol l owing f unc t i ons.

v oid drawIm age( Im age im g, i n t x , i nt y , ImageObserv er ob ) : Draw the im age at x ,y v alues on the g iv en Im age observ er .

v oid drawIm age( Im age im g, i n t x , i n t y , i n t width, i nt he ight , Im ageObserv er ob ) :

/ / HT ML Code

< ! – appimg.html - - ><applet code = 'appim g.cl ass' width=300 height=400>< /applet>

/ / F i l e nam e : appimg.java

im por t j av a.awt . * ;im por t j av a.applet . * ;

publ i c c l ass appim g ex tends Applet{ Im age im g;

publ i c v oid i n i t ( ) { / / l oading the im age im g=get Im age(getCodeBase( ) , "k&h. j pg" ); }

publ i c v oid pa int (Graphi cs g) { g .drawIm age(im g,0,0, thi s) ; / / g.drawIm age( img,0,0,200,200, th i s) ; }}

Out Put :

E:\Core> javac appimg.java

E:\Core> appletviewer appimg.html

Page 132: Java

SATEESH N

132 SATEESH N

AbstractWindowToolKit

Placing components on the Applet : “ j av a.awt “ package i s prov idi ng the f ol l owing com ponent c l asses, whi ch a l l ows us to p l ace com ponents l i ke but tons, checkbox es, do on the applet .

(a) com ponent cl ass : Com ponent i s a super c l ass f or a l l t he com ponents. I t i s prov id i ng a set of m ethods whi ch are av ai l ab le i n a l l t he sub c l asses.

Component :

i . But ton

i i . Tex t com ponent

Tex t f i el d Tex t area

i i i . Label

iv . Check box

v . Scro l l bar

v i . Choi ce

v i i . L i st

v i i i . Canv as

ix . Conta iner

Panel window

F ram e Dia l ogCom ponent i s an abst rac t c l ass, but i t i s not conta ini ng any abst rac t m ethods i .e . ,

we cannot c reate any i nstances of the com ponent c l ass, but the m ethods of the com ponent cl ass can be used i n the sub c l asses.

Component c lass Methods :

v oid setBackground( Color co lor ) : Sets the background co lor .

v o id setForeground( Color color ) : Sets the f oreground co lor .

v oid setEnabled( Boolean enables ) : Enables or d i sables the com ponent .

v o id setV i si bl e( Boolean v i si bl e ) : Shows the com ponent to the spec i f i ed l ocat i on.

v oid setLocat i on( i n t x , i n t y ) : Mov es the com ponent to the spec i f i ed l ocat i on.

po int getLocat i on( ) : Returns the l ocat ion of the com ponent.

Ex : publ i c cl ass point { publ i c i n t x ; publ i c i n t y; }

v oid setS ize( i n t width, i n t height ) : Sets width and height of the com ponent.

Page 133: Java

SATEESH N

133 SATEESH N

v oid getSi ze( ) :

Ex : publ i c cl ass Dim ension { publ i c i n t width; publ i c i n t he ight ; }

v oid setBounds( i n t x , i n t y , i nt width, i nt height ) :

Rectangle getBounds( ) :

Ex : publ i c cl ass Rectangle { publ i c i nt x ; publ i c i nt y; publ i c i nt width; publ i c i nt height ; }

Button : For c reat i ng a push but ton.

Syntax : But ton( ) : c reates b lank but ton, i . e no l abel

But ton( St r i ng Label ) : c reates Button wi th spec i f i ed l abel .

Ex : But t ton( “SUBMIT” );

v oid setLabel ( St r i ng newlabel ) : Changes the l abel of the but ton.

v oid getLabel ( ) : Returns the l abel of the but ton./ / F i l e nam e : buttontest . java

im por t j av a.applet . * ;im por t j av a.awt . * ;

publ i c c l ass but tontest ex tends Applet{ But ton b1,b2;

publ i c v oid i ni t ( ) { b1 = new But ton( "Fi rst But ton" ) ; b2 = new But ton( "Second But ton" );

/ / shows the com ponents on the applet

add(b1) ; add(b2) ; }}

SUBMIT

Out Put :

E:\Core> javac buttontest.java

E:\Core> appletviewer buttontest.html

Page 134: Java

SATEESH N

134 SATEESH N

Handl ing Components : To handle any com ponent a l i stener i s requi red. A l i stener wai t s f or an ev ent to occur . Once the corresponding ev ent occurs the l i steners ca l l s the spec i f i es m ethod.

j av a.awt .ev ent package i s prov id i ng the l i stener i n terf aces f or handl i ng v ari ous t ypes of com ponents.

In terf aces :

Ac t i onLi stener : For handl i ng but tons, l i st box es, m enu i tem s etc. ,

I tem Listener : For handl i ng check box es etc . ,

Adjustm entL i stener : For handl i ng scro l l bars.

W indowListener : For handl i ng f ocus ev ents.

KeyLi stener : For handl i ng key ev ents.

MouseLi stener : For handl i ng m ouse ev ents.

Ac t i onLi stener : Ac t i onLi stener i s contain ing the f ol l owing m ethod.

A l i stener i s a program that wi l l be at tached to a com ponent . The l i stener cont i nuousl y m oni tors the com ponents f or spec i f ic ev ents such as keypress, m ousec l i ck etc. , whenev er the ev ent occurs the l i stener ca l l t he cor responding f unct i on.

publ i c v oid ac t i onPerf ormed( Ac t i onEv ent e ) : To handle a but ton c reate a c l ass that im plem ents the Ac t i onLi stener i n terf ace and ov er r i de the ac t i onPerf orm ed m ethod. Add the l i stener to the requi red but ton. W henever the user c l i cks on the but ton the l i stener receiv es the ev ent and ex ecutes the ac t i onPerf orm ed m ethod.

/ / F i l e nam e: buttontest2. java

im por t j av a.applet . * ;im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;

publ i c c l ass but tontest2 ex tends Applet{ But ton b1,b2;

publ i c v oid i ni t ( ) { b1 = new But ton( "Fi rst But ton" ) ; b2 = new But ton( "Second But ton" );

/ / shows the com ponents on the applet

add(b1) ; add(b2) ;

b1.addAct i onLi stener (new F i rstHandler () ) ; b2.addAct i onLi stener (new SecondHandler ( ) ) ; }

/ / Handlers

Out Put :

E:\Core> javac buttontest2.java

E:\Core> appletviewer buttontest2.html

F i r s t B u t t o n C l i c k e d

Page 135: Java

SATEESH N

135 SATEESH N

c l ass F i rstHandler im plem ents Ac t i onLi stener { publ i c v oid act i onPerform ed(Act i onEv ent e) { showStatus( "F i rst But ton Cl icked" ) ; } }

c l ass SecondHandler im plem ents Act i onListener { publ i c v oid act i onPerform ed(Act i onEv ent e) { showStatus( "Cl i cked on Second Button" ) ; } }}

/ / F i l e nam e : buttontest3. java

im por t j av a.applet . * ;im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;

publ i c c l ass but tontest3 ex tends Applet{ But ton b1,b2;

publ i c v oid i ni t ( ) { b1 = new But ton( "Fi rst But ton" ) ; b2 = new But ton( "Second But ton" ); cont… / / shows the com ponents on the applet

add(b1) ; add(b2) ;

b1.addAct i onLi stener (new Comm onHandler ( ) ) ; b2.addAct i onLi stener (new Comm onHandler ( ) ) ; }

/ / Comm onHandler

c l ass Comm onHandler im plem ents Ac t i onLi stener { publ i c v oid act i onPerform ed(Act i onEv ent e) { i f ( e .getSource( ) == b1 ) showStatus( "F i rst But ton Cl i cked" ) ;

e l se i f ( e .getSource( ) == b2 ) showStatus( "Cl i cked on Second But ton" ) ; } }

}

Out Put :

E:\Core> javac buttontest3.java

E:\Core> appletviewer buttontest3.html

C l i c k e d o n S ec o n d B u t t o n

Page 136: Java

SATEESH N

136 SATEESH N

/ / F i l e nam e : buttontest4. java

im por t j av a.applet . * ;im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;

publ i c c l ass but tontest4 ex tends Applet im plem ents Ac t i onLi stener{ But ton b1,b2;

publ i c v oid i ni t ( ) { b1 = new But ton( "Fi rst But ton" ) ; b2 = new But ton( "Second But ton" );

/ / shows the com ponents on the applet

add(b1) ; add(b2) ;

b1.addAct i onLi stener ( th i s) ; b2.addAct i onLi stener ( th i s) ; }

publ i c v oid act i onPerf orm ed(Act i onEv ent e) { i f ( e .getSource( ) == b1 ) showStatus( "F i rst But ton Cl i cked" ) ;

e l se i f ( e .getSource( ) == b2 ) showStatus( "Cl i cked on Second But ton" ) ; }

}

T extF ield ( ) : A tex t f i el d i s used f or tex t f rom the user . There are 4 im por tant const ruc tors are there f or Tex tF iel d .

Tex tF iel d( ) Tex tF iel d( i n t l ength )

Tex tF iel d( S t r i ng st r ) Tex tF iel d( St r i ng st r , i n t l ength )

There are 2 im por tant m ethods “

St r i ng getTex t ( ) : Returns the tex t i n the tex t box .

v oid setTex t( St r i ng tex t ) : Places the g iv en tex t i nto the tex t box .

v oid setEdi tab le( Boolean edi tab le ) : Makes the tex t read onl y or read and wr i te .

T extArea( ) : For accept i ng m ul t i p l e l i nes of tex t .

Const ruc tors :

Tex tArea( ) , Tex tArea( i n t rows, i n t co l s ) , Tex tArea( St r i ng st r , i n t rows, i n t col s )

Methods :

S t r i ng getTex t ( ) v oid setTex t( St r i ng tex t )

v oid setEdi tab le( boolean edi table ) v oid append( St r i ng tex t )

Out Put :

E:\Core> javac buttontest4.java

E:\Core> appletviewer buttontest4.html

F i r s t B u t t o n C l i c k e d

Page 137: Java

SATEESH N

137 SATEESH N

/ / F i l e nam e : text test . java

im por t j av a.awt . * ;im por t j av a.applet . * ;im por t j av a.awt .ev ent . * ;

publ i c c l ass tex t test ex tends Applet im plements Ac t i onLi stener{ Tex tFiel d t1, t2 ; But ton b1,b2;

publ i c v oid i ni t ( ) { t 1= new Tex tFie l d(35); t 2= new Tex tFie l d(35);

b1 = new But ton( "Copy Down") ; b2 = new But ton( "Copy Up" );

add( t1); add( t2); add(b1) ; add(b2) ;

b1.addAct i onLi stener ( th i s) ; b2.addAct i onLi stener ( th i s) ; } publ i c v oid act i onPerf orm ed(Act i onEv ent e) { i f ( e .getSource( ) == b1 ) { t 2 .setTex t ( t1 .getTex t( ) ) ; t 1 .setTex t ( " " ) ; }

el se i f ( e.getSource( ) == b2 ) { t 1.setTex t (t2 .getTex t ( ) ) ; t 2.setTex t ( "" ) ; } }

}

Checkbox : The checkbox i s used f or accept i ng Boolean types of v alues.

Const ruc tors :

Checkbox ( ) Checkbox ( St r i ng Label )

Methods :

S t r i ng getLabel ( ) v oid setLabel ( St r i ng newlabel )

v oid setLabel ( S t r i ng newlabel ) : Changes the Label .

boolean getState( ) : Returns t rue i f t he check box i s checked on otherwi se f a l se.

Out Put :

E:\Core> javac texttest.java

E:\Core> appletviewer texttest.html

Page 138: Java

SATEESH N

138 SATEESH N

v oid setState( Boolean state ) : Changes the state of the check box .

A check box should be handled using I tem Listener i n terf ace, whi ch i s conta in i ng the f ol l owing m ethods.

Publ ic v oid i tem StateChanged( I temEv ent e ) :

/ / F i l e nam e : chkboxtest. java

im por t j av a.awt . * ;im por t j av a.applet . * ;im por t j av a.awt .ev ent . * ;

publ i c c l ass chkboxtest ex tends Applet im plem ents Act i onLi stener , I tem Listener{ Checkbox cb1,cb2; But ton b1;

publ i c v oid i ni t ( ) { setFont (new Font ( "comicSans" ,Font .BOLD,18) ) ;

cb1 = new Checkbox ( "F i rst Check Box ") ; cb2 = new Checkbox ( "Second Check Box" ) ;

b1 = new But ton( "Show Both Detai l s" ) ;

add(cb1) ; add(cb2) ;

add(b1) ;

cb1.addI tem Listener ( th i s) ; cb2.addI tem Listener ( th i s) ;

b1.addAct i onLi stener ( th i s) ; }

publ i c v oid i tem StateChanged( I temEv ent e) { S t r i ng m sg = "" ;

i f ( e.getSource( ) == cb1 ) { m sg = "F i rst Check Box : " ;

m sg = m sg + (cb1.getState( ) == t rue ? "CHECKED ON" : "CHECKED OFF"); } e l se i f ( e .getSource( ) == cb2 ) { m sg = "Second Check Box : " ;

m sg = m sg + ( cb2.getState() == t rue ? "CHECKED ON" : "CHECKED OFF"); } showStatus(m sg) ; }

Out Put :

E:\Core> javac chkboxtest.java

E:\Core> appletviewer chkboxtest.html

F i r s t c h ec k b o x O N S ec o n d c h e c k b o x O F F

Page 139: Java

SATEESH N

139 SATEESH N

publ i c v oid act i onPerf orm ed(Act i onEv ent e) { i f ( e .getSource( ) == b1 ) { S tr i ng m sg = " " ;

m sg = "Fi rst Check Box ";

m sg = m sg + (cb1.getState( ) == t rue ? "ON" : "OFF") ;

m sg = m sg + "Second Check Box" ;

m sg = m sg + (cb2.getState( ) == t rue ? "ON" : "OFF") ;

showStatus(m sg) ; } }

}

checkbox groups : I f check box es are added to check box groups, Jav a conv er ts them to “ Radio But ton “ .

Checkbox getSelectedcheckbox ( ) : Returns the ref erence of the se lec ted checkbox f rom the spec i f i ed group.

/ / F i l e nam e: rad io test . java

im por t j av a.awt . * ;im por t j av a.applet . * ;im por t j av a.awt .ev ent . * ;

publ i c c l ass rad iotest ex tends Applet im plem ents I tem Listener{ Checkbox Group l ang = new Checkbox Group( ) ; Checkbox Group pack = new Checkbox Group( ) ;

Checkbox opt1 = new Checkbox ("C Languag" , l ang, t rue) ; Checkbox opt2 = new Checkbox ("C++ Languag" , l ang, t rue) ; Checkbox opt3 = new Checkbox ("Jav a" , l ang, t rue) ;

Checkbox opt4 = new Checkbox ("Vi sual Basi c " ,pack , t rue) ; Checkbox opt5 = new Checkbox ("Power Bui l der ",pack , t rue) ;

publ i c v oid i ni t ( ) { setFont (new Font ( "Ari alBlack" ,Font .BOLD,14) ) ;

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

opt1.addI tem Listener ( th i s) ; opt2.addI tem Listener ( th i s) ; opt3.addI tem Listener ( th i s) ; opt4.addI tem Listener ( th i s) ; opt5.addI tem Listener ( th i s) ; }

Out Put :

E:\Core> javac radiotest.java

E:\Core> appletviewer radiotest.html

C + + L a n g u a g e P o w e r B u i l d e r

Page 140: Java

SATEESH N

140 SATEESH N

publ i c v oid i tem StateChanged( I temEv ent e) { Checkbox c1 = l ang.getSelectedCheckbox ( ); Checkbox c2 = pack .getSelectedCheckbox ( );

St r i ng m sg = c1.getLabel ( ) + " "+c2.getLabel ( ) ;

showStatus(m sg) ; }

}

Scro l lbar : A scrol l bar i s used f or se lec t i ng a v a lue wi thi n a g iv en range.

scro l l bar ( ) : Creates v er t i cal sc ro l l bar .

scro l l bar ( i n t sty l e ) : The styl e m ay be scro l l bar.VERTICAL or scro l l bar .HORIZONTAL

scro l l bar ( i nt styl e , i n t i n i t i al v alue, i nt thumbsi ze, i nt min, i n t m ax ) :

const ructors :

v oid setValues( i n t i ni t i alv a lue, i n t thum bsi ze, i nt min, i nt m ax ) : Changes the range f or the scro l l bar .

i n t getValue( ) : Returns the se lec ted v a lue.

v oid setValue( i n t v al ) : Mov es the thum b to the spec i f i ed v alue.

A scro l l bar should be handled using the Adjustm entL i stener i n terf ace. Thi s conta in i ng the f ol l owing m ethod.

publ i c v o id ad justm entValueChanged( Adjustm entEv ent e ) :

/ / F i l e nam e: scrolbarrgb . java

im por t j av a.awt . * ;im por t j av a.applet . * ;im por t j av a.awt .ev ent . * ;

publ i c c l ass scro lbar rgb ex tends Applet im plem ents Adjustm entLi stener{ Scrol l bar red = new Scro l l bar (Scrol l bar .HORIZONTAL,0,100,0,355); Scrol l bar green = new Scro l l bar (Scrol l bar.HORIZONTAL,0,100,0,355) ; Scrol l bar b l ue = new Scro l l bar (Scrol l bar .HORIZONTAL,0,100,0,355);

Label l 1 = new Label ( ) ;

publ i c v oid i ni t ( ) { setLayout (new Gr idLayout (4,1) ) ;

add( l 1) ; add( red) ; add(green) ; add(b lue) ;

Page 141: Java

SATEESH N

141 SATEESH N

Out Put :

E:\Core> javac scrollbarrgb.java

E:\Core> appletviewer scrollbarrgb.html

red.addAdjustm entLi stener ( th i s) ; green.addAdjustm entL i stener ( thi s) ; b l ue.addAdjustm entLi stener ( th i s) ; }

publ i c v oid adjustm entValueChanged (AdjustmentEv ent e) { i nt r = red.getValue( ) ; i nt g = green.getValue( ); i nt b = bl ue.getValue( ) ;

/ / get the new color

Color nc = new Color ( r ,g,b) ;

l 1.setBackground(nc) ;

showStatus( "Red: "+ r+ "Green: "+g+"Blue: "+b) ; }

}

Choice : For c reat i ng a com bo box or dropdown l i st box .

Const ruc tors :

Choi ce( ) : Creates a choi ce com ponent .

Methods :

v oid add( St r i ng i tem ) : Add an i tem to the choi ce box .

St r i ng getSelectedI tem( ) : Returns the tex t of the se lec ted i tem.

i n t getSelec tedIndex ( ) : Returns the Index of the se lec ted i tem star t i ng f rom zero. I t re turns minus one ( -1 ) on no se lec t i on.

St r i ng get I tem ( i n t i ndex ) : Returns the tex t of the spec i f i ed i tem.

i n t get I tem Count ( ) : Returns the num ber of i t em s i n the choi ce com ponent.

v oid se lec t ( i nt i ndex ) : Selec ts the spec i f ied i tem.

v oid rem ov e( i nt i ndex ) : Rem ov es the spec i f i ed i tem.

v oid rem ov e( St r i ng i tem ) : Rem ov es the spec i f i ed i tem.

v oid rem ov eAl l ( ) : Rem ov es a l l i t em s. A choi ce com ponent can be handled using I tem Listener i n terf ace.

List : For creat i ng a l i st box .

L i st ( ) : def aul t s i ze .

L i st ( i nt rows, boolean m ul t i se lec t ) :

A l l t he f unc t i ons of the choi ce box suppor ted i n the l i st box .

Page 142: Java

SATEESH N

142 SATEESH N

Out Put :

E:\Core> javac flowlay.java

E:\Core> appletviewer flowlay.html

St r i ng[ ] getSelectedI tem s( ) : Returns a l l t he se lec ted i tem s.

i n t [ ] getSelec tedIndex s( ) : Returns a l l the se lec ted i tem s.

A l i st box should be handle using Ac t i onLi stener i n terf ace.

Layout Management :

A layout spec i f i es how the com ponents are a l i gned, si zed and posi t i oned i n the run t im e of an applet .

Jav a.awt package suppor ts the f o l l owing f iv e l ayout cl asses f or v ar i ous a l i gnm ent o f the com ponents.

F lowLayout BorderLayout Gri dLayout CardLayout Gr i dBagLayout

FlowLayout : I n the FlowLayout whenev er a com ponent i s add i t wi l l be added i n the cur rent row. I f t here i s no space i n the cur rent row, the com ponent wi l l be placed i n the nex t row.

Thi s i s the def aul t l ayout f or applet and panel s.

F lowLayout ( ) :

F l owLayout ( i nt al i gn ) :

F l owLayout ( i nt al i gn, i n t v space, i n t hspac e ) :

a l i gn : F l owLayout .CENTER ( defaul t )F l owLayout .LEFTF lowLayout .RIGHT

v space and hspace are the spaced between com ponents v er t i cal l y and hori zontal ly .

/ / F i l e nam e : f lowlay. java

im por t j av a.awt . * ;im por t j av a.applet . * ;

publ i c c l ass f l owlay ex tends Applet{ publ i c v oid i ni t ( ) { setBackground(Color .pi nk) ; setFont (new Font ( "BookAnt i qua" ,Font .BOLD,16) ) ; setLayout (new F lowLayout (F lowLayout .RIGHT,5,10) ) ; f or ( i nt i =1; i<=25; i++ ) { add(new But ton( "Button"+ i ) ) ; } }}

Page 143: Java

SATEESH N

143 SATEESH N

Out Put :

E:\Core> javac borderlay.java

E:\Core> appletviewer borderlay.html

BorderLayout : I n the BorderLayout whenev er we add a com ponent we should a l so spec i f y the di rec t i on of that com ponent .

The f ol l owing di rec t i ons are suppor ted:

BorderLayout .EASTBorderLayout .W ESTBorderLayout .NORTHBorderLayout .SOUTHBorderLayout .CENTER ( def aul t )

Zero argum ent const ruc tor , BorderLayout ( ) :

Th i s i s the def aul t l ayout f or f ram es and d ia l ogs

/ / F i l e nam e : borderlay. java

im por t j av a.awt . * ;im por t j av a.applet . * ;

publ i c c l ass border l ay ex tends Applet{ Scrol l bar s1 = new Scrol l bar (Scro l l bar .VERTICAL) ; Scrol l bar s2 = new Scrol l bar (Scro l l bar .VERTICAL) ;

Choi ce course = new Choi ce( ) ;

L i st l 1 = new L i st ( ) ;

But ton b1 = new But ton( "Sam ple But ton" ) ;

publ i c v oid i ni t ( ) { setFont (new Font ( "Ari alNar row" ,Font .BOLD,14) ) ;

setLayout (new BorderLayout ( ) ) ;

add(s1,BorderLayout .EAST); add(s2,BorderLayout .W EST) ;

add( l 1 ,BorderLayout .CENTER) ;

course.add( "C Language" ) ; course.add( "C++ " ) ; course.add( "Jav a" );

course.se lec t (1) ; / / 2nd i tem

l 1.add( "Vi sual Basi c " ) ; l 1.add( "Power Bui l der ") ; l 1.add( "Delphi " ) ; }

}

Page 144: Java

SATEESH N

144 SATEESH N

Out Put :

E:\Core> javac gridlay.java

E:\Core> appletviewer gridlay.html

Out Put :

E:\Core> javac panellay.java

E:\Core> appletviewer panellay.html

GridLayout : I n the Gr i dLayout the to ta l area i s d iv ided i n to rows and co lum ns. W henev er we add a com ponent each com ponent wi l l be added i n each ce l l .

Gr i dl ayout ( i n t rows, i n t co l s) :

Gr i dl ayout ( i n t rows, i n t co l s, i n t v space, i n t hspase) :

/ / F i l e nam e : grid lay. java

im por t j av a.awt . * ;im por t j av a.applet . * ;

publ i c c l ass gr i d l ay ex tends Applet{ publ i c v oid i ni t ( ) { setBackground(Color .p i nk) ; setLayout (new Gr idLayout (6,3,10,10) ) ;

/ / add 18 com ponents

f or ( i n t i=1; i<=18; i++ ) { add(new But ton( "But ton "+ i ) ) ; } }}

Panel Layout : A panel i s a conta iner o f com ponents that i s we are able to p l ace com ponents l i ke But tons, checkbox es etc . , on the panel . A panel can hav e a separate background co lor , foreground co lor , l ayout e tc . ,

A panel can conta in another panel al so.

/ / F i l e nam e : panellay. java

im por t j av a.awt . * ;im por t j av a.applet . * ;

publ i c c l ass panel l ay ex tends Applet{ Panel p1 = new Panel ( ) ; Panel p2 = new Panel ( ) ;

publ i c v oid i ni t ( ) { setLayout (new BorderLayout ( ) ) ; / / f or the applet

add(p1,BorderLayout .CENTER) ; add(p2,BorderLayout .SOUTH) ;

p1.setBackground(Color .orange) ; p2.setBackground(Color .p i nk) ;

p1.setLayout (new Gr idLayout (2,2,5,5) ); p1.add(new Tex tArea( ) ); p1.add(new Tex tArea( ) );

Page 145: Java

SATEESH N

145 SATEESH N

Out Put :

E:\Core> javac cardlay.java

E:\Core> appletviewer cardlay.html

p1.add(new Tex tArea( ) ) ; p1.add(new Tex tArea( ) ) ;

p2.setLayout (new F lowLayout ( ) ) ;

p2.add(new But ton( "Fi rst " ) ) ; p2.add(new But ton( "Second" ) ) ; p2.add(new But ton( "Thi rd" ) ) ; }

}

Card Layout : I n the card l ayout a set o f cards wi l l be added to the l ayout . Each card can conta in any num ber of com ponents. To c reate a card a panel wi l l be used. W henev er a card i s se lec ted by the user , the com ponents of that card wi l l be shown on the applet .

W hi l e adding a card, to the card l ayout we should prov ide a nam e f or each card. Thi s nam e should be used to br i ng that card to the f ront .

/ / F i l e nam e : card lay. java

im por t j av a.awt . * ;im por t j av a.applet . * ;im por t j av a.awt .ev ent . * ;

/ / Design ing cards

c lass f i rstcard ex tends Panel{ f i rst card( ) { setBackground(Color .p i nk) ; setLayout (new F lowLayout ( ) ) ;

add(new Tex tFie l d(25) ) ; add(new Tex tFie l d(25) ) ; add(new Tex tFie l d(25) ) ; }}

c l ass secondcard ex tends Panel{ secondcard( ) { setBackground(Color .orange) ;

setLayout (new Gr idLayout (2,2,10,10) ) ;

add(new TextArea( ) ); add(new TextArea( ) ); add(new TextArea( ) ); add(new TextArea( ) ); }}c l ass th i rdcard ex tends Panel{ t h i rdcard( ) {

Page 146: Java

SATEESH N

146 SATEESH N

setBackground(Color . red) ; setLayout (new BorderLayout ( ) ) ;

Scrol l bar s1 = new Scro l l bar (Scrol l bar .HORIZONTAL) ; Scrol l bar s2 = new Scro l l bar (Scrol l bar .VERTICAL);

add(s1,BorderLayout .SOUTH); add(s2,BorderLayout .EAST); }}

publ i c c l ass card lay ex tends Applet im plements Ac t i onLi stener{ Panel p1 = new Panel ( ) ; Panel p2 = new Panel ( ) ;

f i r st card f c = new f i rstcard( ) ; secondcard sc = new secondcard( ) ; t h i rdcard t c = new th i rdcard( ) ;

But ton b1 = new But ton( "Show f i rst " ) ; But ton b2 = new But ton( "Show second" ) ; But ton b3 = new But ton( "Show th i rd" ) ;

CardLayout myLayout = new CardLayout ( ) ;

publ i c v oid i n i t ( ) { setLayout (new BorderLayout ( ) ) ; setFont (new Font ( "Sansser i f " ,Font .BOLD,14) ) ;

add(p2,BorderLayout .CENTER) ; add(p1,BorderLayout .SOUTH);

p1.setLayout (new Gr idLayout (1,3) );

p1.add(b1) ; p1.add(b2) ; p1.add(b3) ;

b1.addAct i onLi stener ( th i s) ; b2.addAct i onLi stener ( th i s) ; b3.addAct i onLi stener ( th i s) ;

p2.setLayout (m yLayout );

p2.add(f c, "card one" ); / / nam e f or the card p2.add(sc , "card two" ) ; p2.add( tc, "card three" ) ; }

publ i c v oid ac t i onPerf orm ed(Act i onEv ent e) { i f ( e .getSource( ) == b1 ) { myLayout .show(p2, "card one" ) ; } el se i f ( e.getSource( ) == b2 ) { m yLayout .show(p2, "card two" ) ; }

Page 147: Java

SATEESH N

147 SATEESH N

e l se i f ( e.getSource( ) == b3) { myLayout .show(p2, "card three" ) ; } } }

GridBag Layout : Gr i dBagLayout i s the m ost power f u l l ayout to pl ace the com ponents at the requi red l ocat i ons. The l ayout uses a he lper c l ass ( that i s Gr i dBag const ra i n ts ) f or pl acing the com ponents.

Gr i dBag const ra i n t i s contain i ng som e v ari ab les.

They are i . i n t grdix ; i i . i n t gr i dy ;

i i i . i n t gr i dwidth; iv . i n t gr i dheight ;

In the Gr i dBag Layout the to ta l area i s d iv ided i n to rows and co lum ns. W henev er we want to add a com ponent , the l ocat ion and the d im ensions of that com ponent should be spec i f i ed using the gr i dbag const ra i n ts and then the com ponent should be added. Each com ponent can occupy more than one ce l l .

0 1 2 3 4 5

0

1

2

3

/ / F i l e nam e : gridbag.java

im por t j av a.awt . * ;im por t j av a.applet . * ;im por t j av a.awt .ev ent . * ;

publ i c c l ass gr i dbag ex tends Applet{ Label l sno = new Label ( "Sno" ); Label l snam e = new Label ( "Snam e"); Label l address = new Label ( "Address" ) ;

Sno Sname

Address

Tfee fpaid

Course savesave

Sno Sname

Address

Tfee fpaid

Course savesave

Page 148: Java

SATEESH N

148 SATEESH N

Out Put :

E:\Core> javac gridbag.java

E:\Core> appletviewer gridbag.html

Label l t f ee = new Label ( "Tot Fee" ); Label l f paid = new Label ( "Fee paid" ) ; Label l course = new Label ( "Course" ) ;

Tex tFiel d sno = new Tex tFie l d(10) ; Tex tFiel d snam e = new Tex tFie l d(30) ; Tex tFiel d address = new Tex tFie l d(50) ; Tex tFiel d t fee = new Tex tF iel d(20) ; Tex tFiel d f paid = new Tex tF iel d(20) ;

Choi ce course = new Choi ce( ) ;

But ton b1 = new But ton( "Sav e" );

Gr i dBagLayout gb = new Gr idBagLayout ( ) ;

Gr i dBagConst ra i n ts gc = new GridBagConst ra i n ts( ) ;

publ i c v oid i ni t ( ) { setLayout (gb) ;

gc . f i l l = Gri dBagConst ra i n ts.BOTH;

/ / adding l sno

gc .gr i dx = 0; gc .gr i dy = 0; gc .gr i dwidth = 1; gc .gr i dheight = 1; gb.setConst ra i n ts( l sno,gc) ; add( l sno) ;

/ / adding sno

gc .gr i dx = 1; gb.setConst ra i n ts(sno,gc) ; add(sno) ;

/ / adding l snam e

gc .gr i dx = 2; gb.setConst ra i n ts( l snam e,gc) ; add( l snam e);

/ / f or snam e

gc .gr i dx = 3; gc .gr i dwidth = 3; gb.setConst ra i n ts(snam e,gc); add(snam e) ;

/ / adding l address

gc .gr i dx = 0; gc .gr i dy = 1; gc .gr i dwidth = 1; gb.setConst ra i n ts( l address,gc) ; add( l address) ;

Page 149: Java

SATEESH N

149 SATEESH N

/ / f or address

gc .gr i dx = 1; gc .gr i dwidth = 5; gb.setConst ra i n ts(address,gc) ; add(address) ;

/ / adding l t fee

gc .gr i dx = 0; gc .gr i dy = 2; gc .gr i dwidth = 1; gb.setConst ra i n ts( l t f ee,gc); add( l t f ee) ;

/ / f or t f ee

gc .gr i dx = 1; gc .gr i dwidth = 2; gb.setConst ra i n ts( t f ee,gc) ; add( t f ee) ;

/ / adding l f paid gc .gr i dx = 3; gc .gr i dwidth = 1; gb.setConst ra i n ts( l f pa id,gc) ; add( l f paid) ;

/ / f or f paid

gc .gr i dx = 4; gc .gr i dwidth = 2; gb.setConst ra i n ts( f pa id,gc) ; add(f pa id);

/ / adding l course

gc .gr i dx = 0; gc .gr i dy = 3; gc .gr i dwidth = 1; gb.setConst ra i n ts( l course,gc) ; add( l course) ; / / f or course

gc .gr i dx = 1; gc .gr i dwidth = 3; gb.setConst ra i n ts(course,gc) ; add(course) ;

/ / f or b1

gc .gr i dx = 4; gc .gr i dwidth = 2; gb.setConst ra i n ts(b1,gc) ; add(b1) ;

course.add( "V i sual Basi c " ); course.add( "Jav a" ); course.add( "Power Bui l der " ) ; }}

Page 150: Java

SATEESH N

150 SATEESH N

Out Put :

E:\Core> javac nulltest.java

E:\Core> appletviewer nulltest.html

NULL Layout : I f t he l ayout i s sa id to nu l l we should spec i f y the l ocat i on and the d im ension of the com ponents whi l e adding.

/ / F i l e nam e : nul l test . java

im por t j av a.awt . * ;im por t j av a.applet . * ;

publ i c c l ass nul l test ex tends Applet{ But ton b1,b2;

publ i c v oid i n i t ( ) { b1 = new But ton( "Fi rst But ton" ) ; b2 = new But ton( "Second But ton" );

setLayout (nu l l ) ; / / Rem ov e the cur rent Layout

b1.setLocat i on(50,50); / /x , y

b1.setSi ze(150,40) ; / / width,he ight

add(b1) ;

b2.setBounds(210,75,150,40) ; / / x , y ,width,he ight

add(b2) ; }}

Frames : A f ram e i s a container whi ch i s used f or d i sp laying the com ponents i n a separate window.

A f ram e conta ini ng the f ol l owing f eatures :

i . The f ram e conta ins t i t l e bar, minimize, m ax im um, but tons.i i . Conta ins resi zable borders.i i i . Conta ins a m enu bar .

To c reate a f ram e, c reate a cl ass that ex tends the f ram e class.

Const ruc tors :

f ram e ( ) : Creates a f ram e.

f ram e ( S t r i ng t i t l e ) :

Methods :

v oid setTi t l e( S t r i ng newT i t l e ) :

S t r i ng getTi t l e( ) :

Page 151: Java

SATEESH N

151 SATEESH N

Out Put :

E:\Core> javac frametest1.java

E:\Core> appletviewer frametest1.html

/ / F i l e nam e : f rametest1. java

im por t j av a.awt . * ;im por t j av a.applet . * ;im por t j av a.awt .ev ent . * ;

c l ass MyFram e ex tends F ram e{ MyFram e() { setTi t l e( "Sam ple F ram e"); setSi ze(200,150) ; setBackground(Color .pi nk) ; }}

publ i c c l ass f ram etest1 ex tends Applet im plem ents Act i onLi stener{ But ton b1,b2;

MyFram e f ;

publ i c v oid i n i t ( ) { setBackground(Color .cyan) ;

b1 = new But ton( "Show Fram e"); b2 = new But ton( "Hide F ram e") ;

add(b1) ; add(b2) ; f = new MyFram e() ;

b1.addAct i onLi stener ( th i s) ; b2.addAct i onLi stener ( th i s) ; }

publ i c v oid ac t i onPerf orm ed(Act i onEv ent e) { i f ( e .getSource( ) == b1 ) f . setV i si bl e( t rue) ;

el se i f ( e.getSource( ) == b2 ) f . setVi si b l e(f al se) ; }}

/ / F i l e nam e : f rametest2. java

im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;im por t j av a.applet . * ;

c l ass MyFram e ex tends F ram e implem ents Ac t i onLi stener{ But ton b1 = new But ton( "Ex i t Program ") ;

MyFram e() { setTi t l e( "Sam ple F ram e 2") ; setSi ze(300,200) ;

Page 152: Java

SATEESH N

152 SATEESH N

Out Put :

E:\Core> javac frametest2.java

E:\Core> java frametest2

setBackground(Color .pi nk) ; setLayout (new F lowLayout ( ) ) ; add(b1) ; b1.addAct i onLi stener ( th i s) ; }

publ i c v oid ac t i onPerf orm ed(Act i onEv ent e) { i f ( e.getSource( ) == b1 ) { setVi si b l e(fa l se) ; System .ex i t (0); } }}

publ i c c l ass f ram etest2 ex tends Applet{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { MyFram e f = new MyFram e() ; f . setV i si bl e( t rue) ; / / show the f ram e }}

Handling a Frame : To handle a f ram e the W indowListener wi l l be used. W hich i s conta in i ng the f ol l owing 7 m ethods.

1. publ i c v o id windowClosing( W indowEv ent e ) : Th i s ev ent wi l l be ca l l ed when ev er the user c l i cks on the c l ose Button of the window.

2. publ i c v o id windowClosed( W indowEv ent e ) : Af ter the window was c l osed.

3. publ i c v o id windowOpened( W indowEv ent e ) : Af ter the window was opened.

4. publ i c v o id windowAct iv ated( W indowEv ent e ) :

5 . publ i c v o id windowDeact iv ated( W indowEv ent e ) :

6 . publ i c v o id windowIconi f i ed(W indowEv ent e) :W henev er the window i s min imized.

7. publ i c v o id windowDeiconi f i ed(W indowEv ent e) : Af ter the window was restored.

/ / F i l e nam e : f rametest3. java

/ / ov er r i de al l t he methods of W indowListener

im por t j av a. i o. * ;im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;

c l ass MyFram e ex tends F ram e implem ents W indowListener{ MyFram e() { setT i t l e("Sam ple F ram e3") ; setS i ze(300,200) ; setBackground(Color .p i nk);

Page 153: Java

SATEESH N

153 SATEESH N

Out Put :

E:\Core> javac frametest3.java

E:\Core> java frametest3

addW indowListener ( th i s) ; }

/ / ov er r i d i ng al l t he 7 m ethods of W indowListener

publ i c v o id windowClosed(W indowEv ent e){

}

publ i c v o id windowClosing(W indowEv ent e){ setV i si bl e(f al se) ; System .ex i t (0) ;}

publ i c v o id windowOpened(W indowEv ent e){

}

publ i c v o id windowAct iv ated(W indowEv ent e){

}

publ i c v o id windowDeact iv ated(W indowEv ent e){

}

publ i c v o id windowIconi f i ed(W indowEv ent e){

}

publ i c v o id windowDeiconi f i ed(W indowEv ent e){

}

}

c l ass f ram etest3{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { MyFram e f = new MyFram e() ; f . setBounds(100,100,300,200) ; f . setV i si bl e( t rue); }}

windowAdapter : windowAdapter i s a c l ass av ai l ab le i n the j av a.awt package whi ch im plem ents the windowListener i n ter f ace and ov er r i des a l l i t s m ethods wi thout any statem ents. W hen we create a c l ass that ex tends the window adapter c l ass we can ov er r i de only the requi red m ethods.

Thi s f eature i s im plem ents f rom j dk1.2 onwards.

Page 154: Java

SATEESH N

154 SATEESH N

Out Put :

E:\Core> javac frametest4.java

E:\Core> java frametest4

/ / F i l e nam e : f rametest4. java

im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;im por t j av a.applet . * ;

c l ass MyFram e ex tends F ram e {

MyFram e() { setTi t l e( "Sam ple F ram e 4") ; setSi ze(300,200) ; setBackground(Color .pi nk) ; addW indowListener (new MyW indowAdap ter ( ) ) ; }

c l ass MyW indowAdapter ex tends W indowAdapter / / i nner

{ publ i c v o id windowClosing(W indowEv ent e) { setVi si b l e(fa l se) ; System .ex i t (0); } }}

c l ass f ram etest4{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { MyFram e f = new MyFram e() ; f . setV i si bl e( t rue) ; / / show the f ram e }}

S imi l ar ly the i nterf aces l i ke FocusLi stener , MouseLi stener , KeyLi stener etc . , whi ch are conta in i ng m ore than one m ethods the cor responding adapter c l asses a l so av ai l able.

Anonymous c lasses : An anonym ous c l ass i s a c l ass whi ch a l l ows us to ov er r i de a m ethod of a c l ass at the t im e of c reat i ng an i nstance of the cl ass.

Act ionListener : This i s a cl ass whi ch a l lows us to ov er r i de the m ethods of the cl ass , a t the t ime of c reat i ng the i n terface of the cl ass.

/ / F i l e nam e : f rametest5. java

im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;

c l ass MyFram e ex tends F ram e{ MyFram e() {

Page 155: Java

SATEESH N

155 SATEESH N

Out Put :

E:\Core> javac frametest5.java

E:\Core> java frametest5

Out Put :

E:\Core> javac buttonchkbox.java

E:\Core> appletviewer buttonchkbox.html

setBounds(50,50,300,200) ; setT i t l e("Sam ple F ram e 5" ) ; setBackground(Color .p i nk);

addW indowListener ( new W indowAdapter ( ) { publ i c v o id windowClosing(W indowEv ent e) { setVi si b l e(f al se) ; System.ex i t (0) ; } } ) ; }} c l ass f ram etest5{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { MyFram e f = new MyFram e(); f . setVi si b l e(t rue) ; }}

/ / F i l e nam e : buttonchkbox. java

im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;im por t j av a.applet . * ;

publ i c c l ass but tonchkbox ex tends Applet{ But ton b1 = new But ton( "Fi rst But ton" ); Checkbox cb1 = new Checkbox ( "Sam ple Checkbox " );

publ i c v oid i ni t ( ) { setFont (new Font ( "Sansser i f " ,Font .BOLD,14) ) ; add(b1) ; add(cb1) ;

b1.addAct i onLi stener ( new Act i onLi stener ( ) { publ i c v oid act i onPerform ed(Act i onEv ent e) { showStatus( "F i rst But ton Cl icked" ) ; } } ) ; cb1.addI tem Listener ( new I tem Listener ( ) { publ ic v oid i tem StateChanged( I tem Ev ent e) { showStatus( "Checkbox State Changed" ) ; } } ) ;

}}

C h ec k b o x s t a t e c h a n g e d

Page 156: Java

SATEESH N

156 SATEESH N

Out Put :

E:\Core> javac getfontlist.java

E:\Core> java getfontlist

Supported font names DialogSansSerifSerifMonospacedDialogInput

/ / F i l e nam e : get font l ist . java

/ / t o v iew the av ai l ab le f onts i n j av a

im por t j av a. i o. * ;im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;

c l ass MyFram e ex tends F ram e{ MyFram e() { setT i t l e(" f ont dem o") ; System .out .pr i nt l n( "Suppor ted f ont names " ) ; Tool k i t t k = getToolk i t ( ) ;

/ / ToolKi t i s av ai l able i n containers

S t r i ng ar r[ ] = t k.getFontLi st ( ) ;

f or ( i n t i=0; i<ar r. l ength; i++ ) { System .out .pr i n t l n(ar r [ i ] ) ; } }}

class getfontlist{

public static void main(String args[ ] ){

MyFrame f = new MyFrame( ) ;f . setVisible(true) ;

}}

Menus : A f ram e contains m enu bar .

The f ol l owing cl asses wi l l be used by design ing m enus.

Menu BarMenuMenu I temCheckbox MenuItemPopupMenuMenuShor tcut

A m enu can contain the f ol l owing i tem s.

MenuI tem sChecbox Menui tem sSeparatorsMenus ( subm enus )

A MenuI tem should be handled using the Ac t i onLi stener i n terf ace and a Checkbox MenuI tem should be using the I tem Listener i n terf ace.

Page 157: Java

SATEESH N

157 SATEESH N

Out Put :

E:\Core> javac menutest.java

E:\Core> java menutest

/ / f i l e nam e : menutest. java

im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;im por t j av a.applet . * ;

publ i c c l ass m enutest ex tends Applet{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { MyFram e f = new MyFram e(); f . setBounds(100,100,300,200) ; f . setVi si b l e(t rue) ; }}

c l ass MyFram e ex tends F ram e implem ents Ac t i onLi stener , I tem Listener{ Tex tArea t1 = new Tex tArea( ) ;

MenuBar m bar = new MenuBar ( ) ;

Menu f i l e = new Menu("F i l e" ); Menu window = new Menu("W indow") ; Menu t i l e = new Menu("T i l e" );

MenuI tem optnew,optopen,optsav e,optex i t ,optcascade, opthorz ,optv ert ;

Checkbox MenuItem optautosav e = new Checkbox MenuI tem("Auto Sav e" ) ;

MyFram e() { setFont (new Font ( "Sanser i f " ,Font .BOLD,14) ) ; add( t1) ; optnew = new MenuI tem ("new" ,new MenuShor tcut ( 'N ' , f al se) ) ;

/ / f al se: ct r l +N

optopen = new MenuI tem ("open" ,new MenuShor tcut ( 'O ', t rue) );

/ / t rue: c t r l +sh i f t+O

optsav e = new MenuI tem ("sav e" ) ; optex i t = new MenuI tem ("ex i t " ) ; optcascade = new MenuI tem ("cascade" ) ; opthorz = new MenuI tem ("Hori zontal " ) ; optv er t = new MenuI tem ("Ver t i cal " ) ;

/ / add the m enu bar

setMenuBar (m bar ); m bar .add(f i l e) ; m bar .add(window) ;

f i l e.add(optnew) ; f i l e.add(optopen) ; f i l e.add(optsav e) ; f i l e.add(optautosav e) ; f i l e.addSeparator ( ) ; f i l e.add(optex i t ) ; window.add(optcascade) ; window.add( t i l e) ;

Page 158: Java

SATEESH N

158 SATEESH N

t i l e.add(opthorz) ; t i l e.add(optv er t ) ;

optnew.addAct i onLi stener ( th i s) ; optsav e.addAct i onLi stener ( thi s) ; optopen.addAct i onLi stener ( th i s) ; optex i t .addAct i onLi stener ( th i s) ; optcascade.addAct i onLi stener ( thi s) ; opthorz .addAct i onLi stener ( thi s) ; optv er t .addAct i onLi stener ( th i s) ;

optautosav e.addI tem Listener ( th i s) ; }

publ i c v oid ac t i onPerf orm ed(Act i onEv ent e) { i f ( e .getSource( ) == optnew ) t 1.setTex t ( "New I tem Selec ted" ) ; el se i f ( e.getSource( ) == optopen ) t 1 .setTex t( "Open opt i on se lec ted" ) ; e l se i f ( e.getSource( ) == optex i t ) { setV i si b l e(fa l se) ; System .ex i t (0); }

e l se { t 1 .setTex t (e.getAct i onComm and( ) + "se lec ted" ); } }

publ i c v oid i tem StateChanged( I tem Ev ent e) { i f (optautosav e.getState( ) == t rue ) t 1 .setTex t ( "Auto Sav e: CHECKED ON") ; el se t 1 .setTex t ( "Auto Sav e: CHECKED OFF") ; }}

KeyListener : KeyLi stener i s used f or handl i ng keyev ents.

publ i c v o id KeyPressed ( KeyEv ent e ) : Whenev er the key i s down.

publ i c v o id KeyReleased ( KeyEv ent e ) : Whenev er the key i s down.

publ i c v o id KeyTyped ( KeyEv ent e ) : Both down and up.

KeyEv ent :

Char getKeyChar ( ) : Returns the character t yped by the user .

MouseListener : I t i s used f or handl i ng Mouse ev ents.

publ i c v o id MousePressed( MouseEv ent e ) : whenev er the mouse but ton i s down.

publ i c v o id MouseReleased( MouseEv ent e ) : whenev er the m ouse but ton i s up.

Page 159: Java

SATEESH N

159 SATEESH N

Out Put :

E:\Core> javac popuptest.java

E:\Core> java popuptest

publ i c v o id MouseCl i cked( MouseEv ent e ) : whenev er the m ouse but ton i s down+up.

publ i c v o id MouseEntered( MouseEv ent e ) : Mouse i s entered on a com ponent i . e . , Mouse i s ov er a com ponent .

publ i c v o id MouseEx i ted( MouseEv ent e ) : Mouse i s out of a com ponent .

MouseEv ent :

i n t getx ( ) : Returns the co-ord inates of the mouse pointer .

i n t gety ( ) :

i n t getModi f i ers : Returns the b i t pat tern of the m ouse keys and sh i f t keys. Ex : sh i f t al t c t r l enter . . . o n m l . . .

I f ct r l key i s pressed v alue 1 wi l l be stored otherwi se 0 wi l l be stored.

BUTTON1 : l ef t BUTTON2 : m iddle BUTTON3 : r i ght

PopupMenu : A norm al m enu should a l way s be at tached to the m enu bar whi l e a popup m enu can be di sp layed any where on the com ponent .

/ / F i l enam e : popuptest . java

im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;im por t j av a.applet . * ;

c l ass MyFram e ex tends F ram e{ Tex tArea t1 = new Tex tArea( ) ;

PopupMenu popup = new PopupMenu( ) ;

MyFram e() { add( t1); add(popup) ;

popup.add(new MenuI tem ("Fi rst opt i on" )) ; popup.add(new MenuI tem ("Second opt i on" ) ) ; popup.add(new MenuI tem ("Thi rd opt i on") ) ; popup.add(new MenuI tem ("Four th opt i on" ) ) ; popup.addSeparator ( ) ; popup.add(new MenuI tem ("Fi f th opt i on" )) ;

t 1 .addMouseLi stener (new MyMouseAdapter ( ) ) ; } c l ass MyMouseAdapter ex tends MouseAdapter { publ i c v oid m ousePressed(MouseEv ent e) { i n t x = e.getX( ) ; i n t y = e.getY( ) ;

to close the applet goto command promptand click ctrl+c

Page 160: Java

SATEESH N

160 SATEESH N

Out Put :

E:\Core> javac filetest.java

E:\Core> java filetest

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 { popup.show( t1,x ,y ) ; } } }} / / end of MyFram e

publ i c c l ass popuptest ex tends Applet{ publ i c sta t i c v o id m ain(St r i ng args[ ] ) { MyFram e f = new MyFram e() ;

f . setBounds(100,100,300,200) ;

f . setV i si b l e(t rue) ; }}

Dialog : A dia l og i s simi l ar to a f ram e used f or d i sp lay ing i nf orm at i on i n a separate window. A d ial og when com pared wi th the f ram e i s contain i ng the f ol l owing di f f erence.

1. A d ial og cannot contain a m enubar .2. A d ial og should a lways be c reated f rom a f ram e or a f ram e another di a l og.3. A d ial og can be m odular or m odeless.

Constructor : Dialog( F ram e parent ) D ial og( F ram e Parent , S t r i ng t i t l e ) D ial og( F ram e parent , St r i ng t i t l e , Boolean m odal )

F i l eDia log : I t d i sp lays the open or sav e d ia l og box es.

Constructor : Fi l eDialog( F ram e parent , S t r i ng t i t l e , i nt type )

Type:

F i l eDia log.LOAD : f or open Dialog.F i l eDia log.SAVE : For sav e d ial og.

Funct i ons :

S t r i ng getFi l e( ) :S t r i ng getDi rectory ( ) :/ / F i l e nam e : Filetest . java

im por t j av a.awt . * ;im por t j av a.awt .ev ent . * ;im por t j av a. i o. * ;

c l ass f i l etest{ publ i c sta t ic v oid m ain(St r i ng args[ ] ) { MyFram e f = new MyFram e();

Page 161: Java

SATEESH N

161 SATEESH N

f . setBounds(100,100,400,300) ; f . setVi si b l e(t rue) ; }}

c l ass MyFram e ex tends F ram e implem ents Ac t i onLi stener{ Tex tArea t1 = new Tex tArea( );

Panel p1 = new Panel ( ) ;

But ton b1 = new But ton( "Open Fi l e" ) ; But ton b2 = new But ton( "Ex i t Program ") ;

F i l eDialog f d = new F i l eDialog( thi s, "Select Fi l e" ,Fi l eDialog.LOAD );

MyFram e() {

setFont (new Font ( "Ari alNar row" ,Font .BOLD,14) ) ;

add( t1 ,BorderLayout .CENTER); add(p1,BorderLayout .SOUTH) ;

p1.setLayout (new Gr idLayout (1,2) ) ; p1.add(b1) ; p1.add(b2) ;

b1.addAct i onLi stener ( th i s) ; b2.addAct i onLi stener ( th i s) ; }

publ i c v oid act i onPerf orm ed(Act i onEv ent e) { i f ( e.getSource( ) == b1 ) openf i l e( ) ; e l se i f ( e .getSource( ) == b2 ) { setV i si b l e(fa l se) ; System .ex i t (0); } }

v oid openf i l e( ) { t ry { f d.setV i si bl e( t rue) ; / / di pl ay the f i l e d ia l og

St r i ng d i rNam e = f d .getDi rectory ( ) ;

i f ( d i rNam e ! = nu l l ) { S tr i ng f i l enam e = d i rNam e + f d .getFi le( ) ;

F i l e f = new F i l e(f i l enam e) ;

i n t f i l esi ze = ( i nt ) f . l ength( ) ; / / no. of charac ters

i n t star t = 0; / / star t i ng post i on

Page 162: Java

SATEESH N

162 SATEESH N

/ / open the f i l e

F i l e InputSt ream f i n = new F i l e InputStream (f i l enam e) ;

/ / Read al l t he character i n to the buf fer

by te ar r [ ] = new by te[ f i l esi ze] ;

f i n . read(ar r, star t , f i l esi ze) ; / / read al l t he

/ / put the read data, t1

t 1.setTex t (new St r i ng(ar r ) ) ;

setTi t l e(f i l enam e);

f i n .cl ose( ) ; } / / end of i f }

catch(Ex cept i on ex ) { t 1.setTex t ( "Er ror : "+ex ) ; setTi t l e( " " ) ; } }} / / end of MyFram e c lass

Page 163: Java

SATEESH N

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

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

Data BaseJava Program Driver

Data BaseJdbcOdbcBridge Driver

Microsoft ODBC

Java Application

Page 164: Java

SATEESH N

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

Page 165: Java

SATEESH N

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

Page 166: Java

SATEESH N

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

Page 167: Java

SATEESH N

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

Page 168: Java

SATEESH N

168 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

Page 169: Java

SATEESH N

169 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 ResultSetobject. 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.

Page 170: Java

SATEESH N

170 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() {

Page 171: Java

SATEESH N

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

Page 172: Java

SATEESH N

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

Page 173: Java

SATEESH N

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

Page 174: Java

SATEESH N

174 SATEESH N

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

rs.moveToInsertRow( );

rs.updateInt("EMPNO", 111);

rs.updateString("ENAME", “Sateesh”); [ OR ]

rs.updateString("JOB", “Analyst”);

rs.updateFloat("SAL",7500);

rs.updateInt("DEPTNO", 20);

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

rs.moveToInsertRow( );

rs.updateInt(1,111);

rs.updateString(2, “Sateesh”);

rs.updateString(3, “Analyst”);

rs.updateFloat(4,7500);

rs.updateInt(5, 20);

rs.insertRow( );

Page 175: Java

SATEESH N

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

Page 176: Java

SATEESH N

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

Page 177: Java

SATEESH N

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

}

Page 178: Java

SATEESH N

178 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 Functiongetnetamt(qty in Number,rate in Number)return NumberIs 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( );

Page 179: Java

SATEESH N

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

Page 180: Java

SATEESH N

180 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 :BlobClobConnectionPooling:RowSets:

Page 181: Java

SATEESH N

181 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() { b1 = new JButton("First Button"); 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>

E:\adv\swings>javac buttontest.java

E:\adv\swings>appleviewer buttontest.html

Page 182: Java

SATEESH N

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

t1 = new JTextField(25); 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);

E:\adv\swings>javac frametest.java

E:\adv\swings>java frametest

Page 183: Java

SATEESH N

183 SATEESH N

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

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 Policyhsp : Horizontal Scrollbar Policy

E:\adv\swings>javac frametest.java

E:\adv\swings>java frametest

Page 184: Java

SATEESH N

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

Page 185: Java

SATEESH N

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

Page 186: Java

SATEESH N

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

Page 187: Java

SATEESH N

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

Page 188: Java

SATEESH N

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

Page 189: Java

SATEESH N

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

Page 190: Java

SATEESH N

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

Page 191: Java

SATEESH N

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

Page 192: Java

SATEESH N

192 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

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 ASPPWS ( Personal WEB Server ) MircroSoft supports ASPApache Apache only for HTMLTomcat Jakarta supports servlets,,jsp, tomcat doesn’t supports for EJB. http://apache.jakarta.orgJava Web Server J2EE Weblogic BEAWebsphere IBMJRun 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.

GETPOSTHEAD

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 StreamsHEAD Commandline arguments

ServerSideProgram

Page 193: Java

SATEESH N

193 SATEESH N

GET Environment variables

POST Streams

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

request

response

www.yahoo.com

user name :password :

LoginWEB Server Server Side Program

www.yahoo.com

user name :password :

Login

WEB Server Server Side Program

Page 194: Java

SATEESH N

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

Page 195: Java

SATEESH N

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

Page 196: Java

SATEESH N

196 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

Page 197: Java

SATEESH N

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

Page 198: Java

SATEESH N

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

Page 199: Java

SATEESH N

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

Page 200: Java

SATEESH N

200 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’tstore 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 Variables2. Cookies3. 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();

Page 201: Java

SATEESH N

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

Page 202: Java

SATEESH N

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

Page 203: Java

SATEESH N

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

Page 204: Java

SATEESH N

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

}}

Page 205: Java

SATEESH N

205 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

Page 206: Java

SATEESH N

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

Page 207: Java

SATEESH N

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

Page 208: Java

SATEESH N

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

Page 209: Java

SATEESH N

209 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 classii. The bean must be placed in a packageiii. The bean should contain a zero argument constructoriv. 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.

Page 210: Java

SATEESH N

210 SATEESH N

Page : Request :

Application : Session :

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

Bean

Bean

ex2.jsp

server

User1 User2 User n

ex1.jsp

Bean

ex2.jsp

server

User1 User2 User n

ex1.jsp

In page and Request whenever user connects, the new bean is created, the old bean will be destroyed. When the connection is braked.

Bean ex1.jsp

server

User1 User2 User n

Bean

server

User1 User2 User n

Beanex1.jsp

Page 211: Java

SATEESH N

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

Page 212: Java

SATEESH N

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

Page 213: Java

SATEESH N

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

Page 214: Java

SATEESH N

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

<% }

Page 215: Java

SATEESH N

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

Page 216: Java

SATEESH N

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

Page 217: Java

SATEESH N

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

Page 218: Java

SATEESH N

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

Page 219: Java

SATEESH N

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

Page 220: Java

SATEESH N

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

Page 221: Java

SATEESH N

221 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.jsp3. SaveName.jsp4. 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; }

Page 222: Java

SATEESH N

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

Page 223: Java

SATEESH N

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

Page 224: Java

SATEESH N

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

Page 225: Java

SATEESH N

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

Page 226: Java

SATEESH N

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

Page 227: Java

SATEESH N

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

Page 228: Java

SATEESH N

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

Page 229: Java

SATEESH N

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

Page 230: Java

SATEESH N

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

Page 231: Java

SATEESH N

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

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

Java & RMI System

C

Stub

Java & RMI System

S

Skeleton

NetWork

Page 232: Java

SATEESH N

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

Page 233: Java

SATEESH N

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

Page 234: Java

SATEESH N

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

Page 235: Java

SATEESH N

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

Page 236: Java

SATEESH N

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

Page 237: Java

SATEESH N

237 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"); Naming.bind("101",acc1); Naming.bind("102",acc2); Naming.bind("103",acc3);

System.out.println("Finished ...."); System.out.println(); System.out.println("Press Enter to close: "); 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[]) {

D:\adv\rmi>java accountserver

starting server…..

Account: 101 createdAccount: 102 createdAccount: 103 createdBinding AccountsFinished….

Page 238: Java

SATEESH N

238 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"); System.out.print("Enter u r choice: "); ch = Integer.parseInt(stdin.readLine()); // Accept choice

switch(ch) { case 1: // opens the given account System.out.print("Enter an Account Number to open: "); int accno = Integer.parseInt(stdin.readLine()); String url = "rmi://"+host+"/"+accno; System.out.println("Finding: "+url); r = (account)Naming.lookup(url); System.out.println("Account Found");

case 2: System.out.println(); System.out.println(" DETAILS "); System.out.println("------------------------------"); System.out.println("Account Number : "+r.getAccno()); System.out.println("Account Name : "+r.getAccname()); System.out.println("Current Balance: "+r.getBalance()); break;

case 3: System.out.print("Enter Deposit Amount: "); amt = Double.parseDouble(stdin.readLine()); r.deposit(amt); System.out.println("Done"); break;

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

D:\adv\rmi>java accountclient

MENU1.Open2.Details3.Deposit4.Withdraw5.Exit

Enter u r choice: 1Enter an account number to open: 1Finding: rmi://localhost/101Account Found

DETAILS

Account Number: 101Account Name : SateeshCurrent Balance: 25000.0

MENU1.Open2.Details3.Deposit4.Withdraw5.Exit

Enter u r choice:

Page 239: Java

SATEESH N

239 SATEESH N

} // end of while } catch(Exception ex) { System.out.println("Error: "+ex); } } // end of main} // end of client