SATEESH N

INDEX
Introduction First Java Program Data Types in Java Arrays Class & Object Constructors Static Variables & Static Functions Static Blocks Garbaze Collection Method Overloading Access Specifiers Call by Value and Call by Reference Inner Classes Inheritance Overridden Functions Abstract Functions and Abstract Classes Interfaces Packages Object Class Exception Handling String Class Input & Output Streams Integer Class Multi Threading Synchronization util package Collections
APPLETS & AWT

3 4 9 10 13 14 16 18 19 22 23 24 29 34 37 42 47 51 53 59 64 68 94 95 100 105 113 127 128 128 130 131

JDBC SWINGS Servlets JSP JSTL Java Beans XML RMI EJB CORBA Java Mail JMS Struts JSF JNDI LDAP Web Services ANT Log4J JUnit

163 181 192 205 223

231

:: Applets :: Applet Class Graphic Class Sending Parameters to Applet Drawing Images on the Applet :: AWT :: Placing Components on the Applet Handling Components Layout Management Frames Menus 132 134 142 150 156
2 SATEESH N

SATEESH N

INTRODUCTION
About the Java Technology : Java technology is both a n O b j e c t O r i e nt e d programming language and a platform u se d f o r d ev el o pi n g a p p l i c a t i o n s f o r t h e i n t e r n et . J av a wa s st a r t e d b y t h e f ol l o wi n g 5 p e o p l e : J a m e s G o sl i n g , P a t ri c k N a u g h t o n , Mi k e S h er i d a n , C h ri s W r at h , E d F r a n k T h e se p e o p l e d e si g n e d a l a n g u a g e c a l l e d O A K i n 1 9 7 0 ’ s f o r c o n su m e r e l e c t r o ni c s. B u t O AK wa s f a i l u r e . T h e l a n g u a g e O A K wa s e n h a n c e d wi t h i n t e r ne t su p p o r t a n d r e l e a se d i n t h e m a r k e t i n 1 9 9 5 wi t h t h e n e w n a m e J AV A . I m p o r t an t F e a t u r e s o f J AV A :     O b j e ct O r i e nt e d P r o g r am m i n g l a n g u a g e . P r o g r a m m i n g su p p o r t f o r i nt e r n e t . R o b u st p r o g r a m m i n g l a n g u a g e . Strongly typed language : W e c a n ’ t a s si g n a v a ri a b l e t o a n o t h e r v a ri a b l e , i f t h e r a n g e f o r t h e ri g h t si d e v a ri a b l e i s l a r g e r t h a n t h e l ef t si d e v a ri a bl e . Ex : i n t i ; char ch; ch = i; / / e rr o r i = ch; // ok A l l o ws u s t o d e si g n a p p l e t s a n d a p p l i c a t i o ns. S u p p o r t n e t wo r k i n g , d i st ri b u t e d p r o g r am m i ng . S u p p o r t s m ul t i m e d i a. P l a t f orm i n d e p e n d e n t . Interpreted Secure Mul ti threaded Dynamic Portable A r c h i t e c t u r e n e u t r al

         

F e a t u r e s R e m o v e d f r o m C a n d C+ +          No No No No No No No No No

:

M o r e T y p e d ef s, D ef i n e s, o r Pr e p r o c e s so r M o r e S t r u ct u r e s o r U n i o n s Enum s M o r e F u n ct i o n s M o r e M ul t i p l e I n h e r i t a n c e M o r e G ot o S t at em e n t s M o r e O p e r a t o r O v e rl o a d i n g M o r e A u t om at i c C o e r ci o n s : a ssi g n i n g i n t t o f l o a t wi t h o u t t y p e c a st i n g . M o r e P o i nt e r s

3

SATEESH N

SATEESH N

P r o g ra mm i n g i n JA V A
I n j av a t h e p r o g r am s a r e g e n e r a l l y d i v i d e d i n t o 2 c a t e g o r i e s. i . Appli cati ons & i i . A p pl e t s

i . A p p l i c a t i o n : A n a p p l i c a t i o n i s n o r m al p r og r a m t h a t r u n s o n a n i n d i v i d u a l sy st e m . i i . A p p l e t : A n a p pl e t i s a p r o g r am d e si g n e d i n J av a a n d wi l l b e p l a c e d o n t h e se rv e r, t h e a p p l e t wi l l b e d o w n l o a d e d f o rm t h e s e rv e r t o t h e c l i e n t a l o n g wi t h t h e H T M L d o c u m e n t a n d r u n s i n t h e c l i e n t s W E B b r ow se r . i . e . , a n a p p l et wi l l r u n a s a p a r t o f W EB d o c u m e nt .   n a p p l e t c a n c o n t a i n c om p o n e n t s l i k e b u t t o n s, c h e c k b o x e s e t c . , A   n a p p l e t c a n o p e n c o n n e c t i o n s wi t h n e t wo r k se rv e r s, d a t a b a se se r v e r s e t c, A Differe between Application and Applet : This question can be answered on many levels. Technically an application is a Java class that has a main() method. An applet is a Java class which extends java.applet.Applet. A class which extends java.applet.Applet and also has a main() method is both an application and an applet. More generally and less technically an application is a stand-alone program, normally launched from the command line, and which has more or less unrestricted access to the host system. An applet is a program which is run in the context of an applet viewer or web browser, and which has strictly limited access to the host system. For instance an applet can normally not read or write files on the host system whereas an application normally can.

F i r s t J a va p ro g r am
Example: First.java ‘First Java Program’ . Out put:

// it displays the text

class First { public static void main(String args[]) { System.out.println("First Java Program"); } }

E:\Core>javac First.java E:\Core>java First
First Java Program

E:\Core>

c o m p il i n g a J A VA p r o gr a m :
D : \ > j av a c F i r st . j av a ( E nt e r )

W h e n ev e r we c o m pi l e a j av a p r o g r am , t h e c o m pi l e r c r e a t e s a n i n t e rm e di a t e f i l e , wh i c h c o n t a i n s t h e b yt e c o d e of t h e p r o g r am .

C r e at e s f i r st . cl a ss Byte code T o r u n , t h e j av a i n t e r p r et e r sh o u l d b e u se d , wh i c h r e a d s t h e i n st r u c t i o n s f r o m t h e b y t e c o d e a n d ex e c u t e s t h em .

D : \ > j av a F i r st

( Enter ) Ex e c u t e s f i r st . cl a ss

4

SATEESH N

which is an array of strings. First. Run the program contained in the bytecode file. will simply display "First Java Program". written in the Java programming language. . A compiler takes a high-level-language program and translates it into an executable machine-language program. If the program is to run on another type of computer it has to be re-translated. establishing a socket connection from a workstation to a remote machine involves an operating system call. javac. JVM is a platform-independent execution environment that converts Java bytecode into machine language and executes it. First. it has to be translated into machine language. Acronym for Java Virtual Machine. you can use an interpreter. into the appropriate machine language. with a kind of fetch-and-execute cycle. Since different operating systems handle sockets in different ways. There is an alternative to compiling a high-level language program. The Java interpreter installed on your computer implements the Java VM.  Java Virtual Machine : A program written in a high-level language cannot be run directly on any computer. as necessary. which translates it instruction-by-instruction. or virtual machine. the interpreter runs in a loop in which it repeatedly reads one instruction from the program. A source file contains text.a machine within a machine -. 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.mimics a real Java processor. Compile the source file into a bytecode file. Once the translation is done. To create this program. For example. that you and other programmers can understand. In order to execute a program. Instead of using a compiler. the machine-language program can be run any number of times. A Java Virtual Machine starts execution by invoking the method main of some specified class. 5 SATEESH N . passing it a single argument. The compiler. An interpreter is a program that acts much like a CPU. you will:   Create a source file. which translates the program all at once. This translation can be done by a program called a compiler.SATEESH N Your first program. An abstract computing machine. A JVM -. You can use any text editor to create and edit source files. This interpreter takes your bytecode file and carries out the instructions by translating them into instructions that your computer can understand.java. but of course it can only be run on one type of computer (since each type of computer has its own individual machine language). such as Windows or UNIX. enabling Java bytecode to be executed as actions or operating system calls on any processor regardless of the operating system. and then performs the appropriate machinelanguage commands to do so. the JVM translates the programming code so that the two machines that may be on different platforms are able to connect. Most programming languages compile source code directly into machine code that is designed to run on a specific microprocessor architecture or operating system. decides what is necessary to carry out that instruction. using a different compiler.

these libraries are known as packages. We've already mentioned some of the most popular platforms like Windows 2000. Most platforms can be described as a combination of the operating system and hardware. o r t o g e n e r a t e A PI d o c um e n t a t i o n . a n d d o c c om m e n t s. Ex: / / A V e r y Si m pl e Ex am p l e cl a ss C .st y l e c om m e nt s* / D o c C o m m e n t s : T o g e n e r a t e d o c um e n t a t i o n f o r y o u r p r o g r am . D o u b l e S l a sh e s : D o u b l e sl a sh e s ( / / ) a r e u se d i n t h e C + + p r o g r a m m i n g l a n g u a g e . C . Linux. u se t h e d o c c o m m e n t s ( / * * * / ) t o e n c l o se l i n e s o f t ex t f o r t h e j av a do c t o o l t o f i n d . 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. T h e j av a d o c t o o l l o c a t e s t h e d o c c o m m e n t s e m b e d d e d i n so u r c e f i l e s a n d u se s t h o se c o m m e n t s t o g e n e r a t e A PI docum entati on. y o u c a n u s e C .st y l e . Solaris. 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. a n d t e l l t h e c om p i l e r t o t r e a t ev e ry t hi n g f r om t h e sl a sh e s t o t h e e n d of t h e l i n e a s t ex t . The Java API is grouped into libraries of related classes and interfaces. Ex: / * * T hi s c l a ss d i sp l a y s st u d e n t d e t a i l s a t * t h e c o n so l e .o u t l i n e s o f c o d e t o i so l a t e t h e so u r c e o f a p r o b l em f o r d e b u g g i n g p u r p o se s. t h e J av a l a n g u a g e su p p o r t s t h r e e k i n d s of c om m e n t s: d o u b l e sl a sh e s. It's the base for the Java platform and is ported onto various hardware-based platforms.SATEESH N The Java Platform A platform is the hardware or software environment in which a program runs. and MacOS. Ex: / * T h e se a r e C . T o t h e se e n d s. Your Computer System C o m me n t s i n Ja v a C o d e C o d e c o m m e n t s a r e pl a c e d i n so u r c e f i l e s t o d e sc r i b e wh a t i s h a p p e n i n g i n t h e c o d e t o so m e o n e wh o m i g h t b e r e a d i n g t h e f i l e . Java APIs are libraries of compiled code that you can use in your programs. t o c om m e nt . They let you add ready-made and customizable functionality to save you programming time. */ 6 SATEESH N .st y l e c o m m e nt s ( / * * / ) t o e n c l o se o n e o r m o r e l i n e s of c o d e t o b e t r e a t e d a s t e x t .S t yl e C o m m e n t s : I n st e a d o f d o u b l e sl a s h e s.

-=. >>=. %= &=. /=. |=. (dot) Array Element Access [] () Other Operators ?: Conditional Operator (primitive type) Type Cast 7 SATEESH N . *=. >>>= Arithmetic operation and then assignment: Bitwise operation and then assignment: Shift operations and then assignment: Arithmetic Operators : Addition Division : : + / Subtraction Modulo : : % ++ Post-increment Pre-increment Logical Operators : Logical AND && Boolean Operators : Boolean AND & Comparison Operators : Lessthan < Greaterthan > Lessthan or equalto <= Greaterthan or equalto >= equal to == not equal to != Logical OR || Boolean OR | Multiplication Unary minus and and and Logical NOT ! Boolean NOT ^ : : * .(negation of the value) -Post-decrement Pre-decrement Increment & Decrement Operators : Bitwise Operators : Compliment ~ AND & OR | XOR ^ ShiftLeft << ShiftRight-Signed >> ShiftRight-unsigned >>> Class and Object Operators : Class Test Operator instanceOf Object Cast (X) Class Instantiation new String Concatenation + Class Member Access method invocation . ^= <<=.SATEESH N Operators in Java : Assignment Operators : Assignment operator : = +=.

println("This won't execute").out."). System. // break out of second block if(t) break second. 8 SATEESH N . Use labeled breaks instead. j a v a public class Goto_break { public static void main(String[] args) { boolean t = true. Note: Although goto is a reserved word.out. } } } o u tp u t : } Before break. } System.println("Before break. currently the Java language does not support the goto statement. G o to _ b r e a k .out.C o n t ro l St a te me n t s : S e l e c t i o n St a t em e n t s: if L o o p S t a t em e n t s: while J u m p S t a t em e nt s: break continue return do – while for switch SATEESH N u si n g b r e a k a s a f o rm of g o t o : S y n t ax : Example : break label. first: { second: { third: { System.println("This is after second block.").

+ / -i n fi n i t y . b e c a u se i i s n o t a B o o l e a n d a t at y p e ok i f (i ! = 0 )  KeyWords abstract catch do final implements native public switch true assert char double finally import new return synchronized try boolean class else float instanceof null short this void break const enum for int package static throw volatile byte continue extends goto interface private strictfp throws while case default false if long protected super transient Notes: -. + / . Java is case sensitive so in principle you could use these words if you change any character to uppercase. or b = f al se .0 0. 4 0 2 8 2 3 5 E + 3 8 .0 .enum is a new keyword added with Java 5.3 2 4 t o +/-1. + / -i n fi n i t y .0.7976931348623157E+308. -.0 \u0000 false Size 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits 16 bits 1 bit used in 32 bit integer Range -128 to 127 . But that's not recommended! 9 SATEESH N .32768 to 32767 -2147483648 to 2147483647 ( .4 -. N AN + / .) -.const is also not used.4 . such jumping between lines of code is considered very bad programming practice.1 .D a t a ty p e s i n J a va SATEESH N Java Primitive Data Types Type byte short int long float double char boolean Values signed integers signed integers signed integers signed integers IEEE 754 floating point IEEE 754 floating point Unicode character true. false Default 0 0 0 0 0. 4E . + / .3 . N a N \u0000 to \uFFFF NA Ex: boolean b. i f (i )  i nv al i d . (In modern language design.2 t o 2 – 1 ) + / . b = true. if(b==true) i f ( b = = f a l se ) if (b)  checks f or if(b==true) int i = 1. 9E .0 .assert is a new keyword added with Java 1.The goto keyword is not used.4 5 t o + / .2 31 to2 31 –1) -9223372036854775808 to 63 63 9223372036854775807 ( .

l e n g t h ).i. p ri n t l n ( a r r .i++) System. wh i c h c o n t a i n s t h e n o .out. length property : E a c h a r r a y c o n t a i n s t he l e n g t h p r o p e r t y .40. for(i=0. arr[0] = 10. 5 f o r t h e a b ov e ex .i<a. o f e l em e n t s i n t h e a r r a y . o u t . value of a[0] is: value of a[1] is: value of a[2] is: value of a[3] is: value of a[4] is: 10 20 30 40 50 20 1 2 3 4 10 SATEESH N . I n j av a a r r a y i n d ex i n g st a r t s f r om 0 .30. I n t h e a b ov e st a t em e n t t h e a r r a y wi l l b e c re a t e d wi t h o u t a n y si z e . j a v a // initializing the array and display the elements Out put: class OneDArrIni { public static void main(String args[]) { int a[]={10.50}.20. / / E x a mp l e : O n e D Ar r I n i . e. S y n t ax : Ex: data type int arr[ ]. I n i t i al i z i n g a n a r r a y : W h e n we i n i t i a l i z e an a r r a y a t t h e t i m e of c r e a t i n g t h e a r r a y t h e n e w o p e r a t o r sh o u l d n o t b e g i v e n . i f we d o n ’ t a ssi g n o r r e a d t h e v al u e s f o r r e m ai n i n g l o c a t i o n s.Arrays SATEESH N A n a r r a y i s a c o l l e c t i o n of v al u e s a l l a r e b e l o n g i n g t o t h e sa m e d a t a t y p e a n d r e f e r r e d wi t h t h e sa m e n a m e t o a c c e ss a n y e l e m e n t of a n a r r a y i t s p o si t i o n sh o u l d b e g i v e n wh i c h i s k n o wn a s i n d e x . b y d ef a u l t t h e y wi l l b e f i l l e d wi t h 0 ’ s. arr = new i nt[5]. E x : Sy st e m . / / d i sp l a ys t h e n o . arr[1] = 20. of l o c a t i o n i . i nt [ ]arr = new i nt[5].println("value of a["+i+"] is: } } "+a[i]). W e sh o u l d a l l o c at e m em o r y u si n g t h e n e w o p e r a t o r b ef o r e a c c e ssi n g t h e a r r a y . v a ri a bl e n am e [ ] . .length. P i ct o r i al r e p r e se n t a t i o n : arr 10 0 i n t a rr [ ] = n e w i n t [ 5 ] .

i n t [ ] [ ] a = n e w i n t [ 3] [ 5 ] .SATEESH N / / E x a mp l e : O n e D Ar r . for(i=0.i. a[1]=20. 2. a[0]=10.0 1. P i ct o r i al r e p r e se n t a t i o n : a 0 1 2 0. 4.2 2. { 1. / / 3 r o ws / / f or 1 s t r o w 4 c o l s nd // f or 2 row 3 cols rd // f or 3 row 5 cols Out put: value of a[0] is: value of a[1] is: value of a[2] is: value of a[3] is: value of a[4] is: 10 20 0 0 0 "+a[i]).d a r r a y a l l t h e r o w s n e e d n o t a = new i nt [3] [ ]. { 1. of c o l um n s. 4}. 2. 3}.3 2.i++) { System. 5} 11 } . j a v a // initialize the 2-d array and display the elements in matrix format class TwoDAarrIni { public static void main(String args[]) { int a [ ] [ ] = { { 1. int a[ ] [ ] . 2. I n i t i al i z i n g a 2 – D A r r a y : / / E x a mp l e : T w o D Aa r r I n i .1 0.out.1 1. 3.0 2.length.4 0 1 2 3 4 i n t a[ ] [ ] = n e w i n t [ 3 ] [ 5 ] . a[0][0] = 10. a=new int[5].0 0. SATEESH N . i n a 2 . 3.3 2.1 2. a[0] = new i nt [4].2 1. a[1] = new i nt [3]. I n J av a .println("value of a["+i+"] is: } } } T w o – D i m e n s io n a l A r r a y s : c o n t a i n t h e sa m e n o . a[0][1] = 20.2 0. j a v a // assigning elements into the array and display the elements class OneDArr { public static void main(String args[]) { int a[]. a[2] = new i nt [5].i<a.

12 "+args.length).println().length.out.println().print("\t a["+i+"]["+j+"] : "+a[i][j]).i<a. SATEESH N .out.j<a[i]. } a[0][0] : 1 a[0][1] : 2 a[0][2] : 3 a[0][3] : 4 a[1][0] : 1 a[1][1] : 2 a[2][0] : 1 a[2][1] : 2 a[2][2] : 3 / / E x a mp l e : T w o D Ar r . } System.SATEESH N } } for(int i=0. for(i=0.length.k=1. j a v a // assigning elements into the array and display the elements class TwoDArr { public static void main(String args[]) { int a[][]. } } Out put: a[0][0] : 1 a[0][1] : 2 a[0][2] : 3 a[0][3] : 4 a[1][0] : 5 a[1][1] : 6 a[2][0] : 7 a[2][1] : 8 a[2][2] : 9 for(i=0.println("Total no.j<a[i]. j a v a //Give the command ling arguments at the time executing the program and display them class CommArgs { public static void main(String args[]) { System. of Argument(s): System.j++) { System. a[1]=new int[2].length.out.out.i<a.j<a[i]. } } } a r g s a rr a y : / / E x a mp l e : T h e a r g s a r r a y wh i c h wa s g i v e n i n t h e m ai n ( ) c o n t ai n s a l l t he a r g u m e n t s g i v e n b y t h e u se r a t t h e c om m a nd l i n e .length.i.j++) { a[i][j]=k.j++) { System. a[2]=new int[3].i++) { for(j=0.out. k++. C o m m Ar g s .out. a[0]=new int[4].length.j.print("\t a["+i+"]["+j+"] : "+a[i][j]).i++) { for(int j=0.length.println().i++) { for(j=0. } Out put: System. a=new int[3][].i<a.

out. It does not allocate memory for any objects of that type! That is done by operator new.println("Insufficient Arguments return. : "+sno+"\n Student name: "+sname). Out put: Total no. sname="Sateesh". .assign(). s.i<args. Student no. } for(int i=0.length. String sname. } } Student no.println("\n Student no. j a v a // Define a class and create an instance for the class.assign(). and access the member data and member functions of the class through the instance. The definition of a class creates a user-defined data type and names the members of the class.out.out.SATEESH N if(args.t i m e e n t i t y . O n c e a c l a s s i s c r e a t e d . } } } should give min. // Example: Cl a s s a n d O b j . : 10 s= new Student(). Student name: Sateesh s.println("args["+i+"]: "+args[i]). class Student { int sno. void assign() { sno=10.display(). a n y n o . 1 arg").display().i++) { System. } void display() { System.length<1) { System. o f i n st a n c e s o f t h e c l a ss c a n b e c r e a t e d i n t h e p r o g r a m . of Argument(s): 3 args[0]: red args[1]: green args[2]: blue Defining Classes and Creating Objects C l a s s : A cl a ss i s a c o l l e c t i o n of D a t a m e m b e r s (v a r i a bl e s) t h a t c o n t ai n i nf o rm at i o n n e c e s sa r y t o r e p r e se n t t h e c l a ss a n d M e t h o d s ( f u n c t i o n s) t h a t p e rf o rm o p e r a t i o n s o n t h e d a t a m em b e r s o f t h e c l a ss. Student t= new Student(). } } class ClassandObj { public static void main(String args[]) Out put: { Student s. t. t. : 10 Student name: Sateesh 13 SATEESH N . O b j e c t : O bj e c t i s a n i n st a n c e of t h e cl a s s o r a n o b j e c t i s t h e b a si c r u n .

dispx(). * Calling default constructor when user-defined constructor exists results in compiler error. b u t a c o n st r u c t o r wi l l n o t r e t u r n a n y v al u e . • One constructor can be invoked from another via the this or super keyword. A c o n st r u c t o r m ay o r m a y n o t t a k e a n y a r g um e n t s. y=q. t o c al l a c o n st r u c t o r f r om a n o t h e r c o n st r u c t o r . the default is ignored.y. t o r ef e r t o t h e v ar i a bl e s o f t h e c u r r e n t cl a s s.dispyx(). • Default constructor has no argument. / / E x a mp l e : // C o n s t r u c to r 1 . i . Ex : i i i . this. • Call to other constructor MUST be first line in method.println("\n val of X: "+x). d i sp l a y ( ) . dispy(). } // Constructor void dispx() { System. Ex : i i . class Vals { int x. t h is : t h i s k e y wo r d . I t c a n b e a p p l i e d i n 3 c a t e g o r i e s.C O N S TR U C T O R S SATEESH N A c o n st r u c t o r i s a sp e c i a l m em b e r f u nc t i o n wh i c h i s c a l l e d a u t om at i c a l l y wh e n e v e r a n i n st a n c e o f t h e c l a ss i s c r e a t e d . sn o t h i s( ). i.display( ). Ex : t hi s. t hi s.int q) { x=p. t o r ef e r t o t h e f u n ct i o n s o f t h e c u r r e n t cl a s s. 14 SATEESH N . • Once class has a user-defined constructor.out.out.println("\n val of Y: "+y). Vals(int p. * Initializes all nonstatic members to their defaults. C o n st r u c t o r s c a n b e ov e r l o a d e d . T h e n a m e o f t h e c o n st r u c t o r sh o u l d b e e q u a l t o t h e n a m e o f t h e c l a ss. } } // // or or dispx(). t h e t hi s r ef e r e n c e v a r i a b l e al wa y s r e f e r s t o t h e c u r r e n t cl a ss. to refer to the functions of the current class. C o n st r u c t o r s a r e g e n e r a l l y u se d f o r i n i t i a l i zi n g t h e v a ri a b l e s of t h e cl a ss. j a v a Ex: this. } void dispy() { System. } void dispxy() { this. • If a class doesn’t have a constructor defined. Java provides a default constructor.

: 33 Student name: Sateesh 15 SATEESH N Student t= new Student(22. s. & constructor over loading.String stname) //2nd constructor.dispxy().used when arguments specified { this. } void display() { System. } void accept(int stno.out.display().println("\n Student no.sname=stname. sname="Raj". used when no arguments specified { sno=11.20). to refer to the variables of the current class. } } class Constructor2 { public static void main(String args[]) { Student s = new Student(). : 11 Student name: Raj Student no. } } .sno=stno.SATEESH N class Constructor1 { public static void main(String args[]) { Vals s = new Vals(10. s. } Student(int stno.display(). String sname. this.sno=stno. Ex: this. s. String stname) { this.display(). this.sname=stname.accept(33. s. Student() // 1st constructor . 1st constructor doesn’t contain arguments and 2nd constructor contain two arguments. } } Out put: val of x : 10 val of y : 20 // Example : Co n s t ru c t o r 2 ."Sateesh"). j a v a // ii. //calls the 1st constructor //calls the 2nd constructor Out put: Student no."Sanju"). : 22 Student name: Sanju Student no. t.sno Overloading Constructors class Student { int sno. : "+sno+"\n Student name: "+sname).

out. } void display() { System.SATEESH N / / E x a mp l e : C o n s t r u c to r t t o Co n s t ru c t o r . t. Vals(int p. } class StaticMember { public static void main(String args[]) { System. j a v a // iii. s.60).out.z : 99 Val of t. this. Out put: Val of x : 10 Val of y : 20 Val of x : 50 Val of y : 60 //calls 2nd constructor which calls 1st constructor //calls 1st constructor Vals t = new Vals(50.z : 99 Val of z : 99 SATEESH N . class Vals { int x.y.20).x : 10 Val of s. 16 Val of z : 99 Val of s.display(). Out put: / / E x a m p l e : S t a t i cM e m b e r . j a v a Val of z : 77 class Vals { int x. calling a constructor form another constructor : To call a constructor from another constructor the this keyword should be applied in a function type.int q) { this.y. } } class ConstructortoConstructor { public static void main(String args[ ]) { Vals s = new Vals( ). } Vals() { this(10.z).x : 50 Val of t.println("\n Val of Z: "+Vals. } } S t a t i c me m be r s & S t a ti c me t ho d s S t a t i c m e m b e r s : W h e n ev e r a v a ri a b l e i s sp e c i f i e d a s st a t i c su c h v a ri a bl e wi l l be c r e a t e d o n l y o n c e i n t h e m e m o r y f o r a l l t h e i n st a n c e s o f t h e c l a ss. A l l t h e i n st a n c e s o f t h e c l a ss wi l l sh a r e t h e sa m e v al u e of t h e st a t i c v a ri a b l e. static int z=77.display().x=p.y=q.y : 60 Val of t. A st a t i c v a ri a b l e of a cl a ss c a n a l so b e a c c e ssi b l e u si n g t h e n am e of t he c l a ss.y : 20 Val of s.println("\n Val of X: "+x+"\n Val of Y: "+y).

out. s.out. s.out.y.z).out.y=20.y : "+s.z).y=60.x+"\n Val of s.display(). s. } } 17 SATEESH N . Vals t = new Vals(). Vals.out. s. } static void print() { System. System.print().y : "+t. t.x+"\n Val of t.print(). t.println("\n Val of Z: "+Vals. vals Vals s = new Vals(). t.z=99. j a v a class Vals { int x. s.y+"\n Val of t. void display() { System.y=20.x=10.print().println("\n Val of s.out. t. } } S t a t i c m e t h o d s : A st a t i c f u n c t i o n of a c l as s c a n b e a c c e s si b l e u si n g t h e n a m e o f t h e c l a ss a l so .y=60. Out put: Value is : 77 Values are : 10 20 Values are : 50 60 Value is : 99 Value is : 99 Value is : 99 99 99 : "+z). s. s.z=99. System. System. //calling static function using class name i.x=50.display(). t.y+"\n Val of s.z : "+s.x : "+t.println("\n Val of Z: "+Vals.SATEESH N Vals s = new Vals(). static int z=77.z : "+t. s.println("\n Values are: "+x+"\t"+y+"\t"+z). / / E x a m p l e : StaticMethod.e.z). t..println("\n Val of t. System.x : "+s. A st a t i c f u n c t i o n c a n a c c e ss o n l y o t h e r st a t i c m em b e r of t h e cl a ss.print().x=10.println("\n Value is } } class StaticMethod { public static void main(String args[]) { Vals.z).x=50. Vals t = new Vals().

out.out.java class StaticBlocks { static { System.out. } } Class2.out. } static { System.println("First Static Block").println("Second Static Block").java and Class2. } } o u tp u t : U r in Static block U r in Constructor ---------------------U r in Constructor 18 SATEESH N .println("In the main program").java public class Class1 { public static void main(String[] args) { Class2 class2obj1 = new Class2(). // Example : StaticBlocks.java Class1. Static initializer blocks are also typically used to initialize static fields.println("----------------------"). } static { System.java public class Class2 { Class2() { System. System.out. } } Out put: First Static Block Second Static Block In the main program Static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class.println("U r in Constructor"). Class2 class2obj2 = new Class2().out. Example: Class1. } public static void main(String args[]) { System.println("U r in Static block").SATEESH N S t a t i c B lo c k s I f a cl a ss c o n t a i n s st a t i c b l o ck s a l l su c h b l o c k s wi l l b e e x e c ut e d f i r st wh e n e v e r t h e c l a ss i s l o a d e d .

Garbage Collection    SATEESH N When an object no longer has any valid references to it. . 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.out. • F i n al i z e r n o t al l o we d t o h av e a r g um e n t s.println("Finalizing TestClassB object"). v oi d f i n al i z e ( ) { . you can explicitly drop an object reference by setting the variable to the special value null. returning an object's memory to the system for future use. } } 19 SATEESH N . it can no longer be accessed by the program it is useless. • M o st J av a c l a sse s d o n ’ t r e q u i r e a f i n al i z e m et h o d .println("Finalizing TestClassA object"). Or. This process is called garbage collection. J av a r u n t i m e wi l l c a l l f i n al i z e ( ) .java class TestClassA { protected void finalize() // override finalization method { System. } } class TestClassB { protected void finalize() // override finalization method { System. F i n al i ze r s • J av a al l o ws y o u t o d e f i n e a m e t h o d t ha t i s a u t o m at i c al l y c al l e d b ef o r e o b j e ct i s returned to heap. * J av a ’ s g a r b a g e c o l l e c t i o n m e c h a n i sm t a k es c a r e o f m em o r y l e a k s. References that are held in a variable are usually dropped when the variable goes out of scope. and therefore called garbage. • F i n al i z e r sh o u l d b e u se d o n l y a s a l a st . } • M u st b e c al l e d f i n a l i z e ( ). * Finalizer is Not a Destructor Example: Finalizer_Ex1. • F i n a l i z e r: M e t h o d t h a t al l o ws r e so u r c e s t o b e f r e e d b e f o r e o bj e c t i s g a r b a g e c o l l e ct e d . • I m m e d i at e l y b ef o r e o b j e ct i s g a r b a g e c o l l e c t e d . In other languages. Java performs automatic garbage collection periodically. .d i t c h ef f o r t t o r e c ov e r a sse t s b e f o r e t h e y a r e l o st f o r ev e r . all references to an object must be dropped before the object is eligible for garbage collection. Remember that a program can have multiple references to the same object.out.

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.. for example.gc(). Output : //Instantiate two objects to be finalized TestClassA objA = new TestClassA().. Your program should only run the garbage collector when doing so will have no performance impact on your program. Note that the garbage collector requires time to complete its task.SATEESH N class Finalizer_Ex1 { //controlling class public static void main(String[] args) { //Guarantee finalization of all objects on exit System. that is. the object is finalized and is then garbage collected. Finalizing Objects : Before an object is garbage collected. 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. Finalizing TestClassB object Finalizing TestClassA object Forcing Finalization and Garbage Collection : The Java runtime system performs memory management tasks for you. This method calls the finalize methods on all objects that are waiting to be garbage collected. However. You can force object finalization to occur by calling System's runFinalization method. These tasks happen asynchronously in the background. This step is known as finalization and is achieved through a call to the object's finalize method.println("Terminating... 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.").runFinalizersOnExit(true). } } Terminating.. System. Running the Garbage Collector : You can ask the garbage collector to run at any time by calling System's gc method: System..runFinalization(). TestClassB objB = new TestClassB(). you can force object finalization and garbage collection using the appropriate method in the System class. When your program has finished using an object. when there are no more references to an object. 20 SATEESH N . System. the Java runtime system gives the object a chance to clean up after itself. For example.out.

println("GC1 object " + id + " has been finalized. GC1 object 5535 has been finalized. this. int id.freeMemory()). GC1 object 5533 has been finalized.freeMemory()). i<10000. " + rt. GC1(int i) { this. i++ ) { GC1 x = new GC1(i).gc(). } } Output : Available Free Memory: 1911256 GC1 object 5531 has been finalized.freeMemory()). Free Memory before call to gc(): 1222864 GC1 object 9259 has been finalized."). " + rt.getRuntime().runFinalization().out. System.out. for(int i=0. Note that the finalize() method of object GC1 runs without being specifically called and that the id's of garbage collected objects are not always sequential. 21 SATEESH N .println("Available Free Memory: " + rt. . GC1 object 9260 has been finalized.SATEESH N E x a m p l e : GC_Finalizer_Ex. . } System. */ class GC_Finalizer_Ex { public static void main(String[] args) { Runtime rt = Runtime. System.str = new String("abcdefghijklmnopqrstuvwxyz").out. .out. So on. System.println("Free Memory after call to gc(): } } class GC1 { String str. } protected void finalize() { System.j a v a /** Example shows garbage collector in action. GC1 object 5534 has been finalized.println("Free Memory before call to gc(): System. GC1 object 5532 has been finalized.id = i.

} // method get_fullname (0 arguments) // fullname: arbitrary # of spaces between first and last names public String get_fullname(int spaces) { String fn = "Sateesh". .get_fullname(2)).println("Test1: " + pn. return fn+" "+middle+" "+ln. String ln = "Natchireddy". } // method get_fullname (1 argument) // fullname: insert middle name public String get_fullname(String middle) { String fn = "Sateesh". g. String ln = "Natchireddy". return fn+space+ln. String space = "".println("Test2: " + pn.out.out. s++) space = space + " ". for(int s = 1.get_fullname("Kumar")). s <= spaces. } } 22 SATEESH N . return fn+space+ln. System.get_fullname()). s++) space = space + " ".Overloading Methods • • • • D i f f e r e n t m e t h o d s c a n h av e t h e sam e n a m e SATEESH N T h e si g n a t u r e of a m et h o d i s t h e m e t h o d’ s n a m e a n d t h e p a r am e t e r t y p e s ( i n cl u d i n g t h e o r d e r of t h e p a r am et e r s) I n a cl a ss. t h e a b s m e t h o d i n t h e M a t h cl a ss class Person_name { /* Overloaded Methods */ // fullname: 1 space between first and last names: public String get_fullname() { String fn = "Sateesh". String ln = "Natchireddy".println("Test3: " + pn.out. } // method get_fullname (1 argument) } public class MethodOverloading_Ex1 { public static void main(String[] args) { Person_name pn = new Person_name(). s <= spaces. Output : Test1: Sateesh Natchireddy Test2: Sateesh Natchireddy Test3: Sateesh Kumar Natchireddy // Determine fullname by three differebnt (and overloaded) methods System. a l l m et h o d s m u st h av e di f f er e n t si g n a t u r e s E . String space = "". int spaces=1. for(int s = 1. System.

  Data declared within a method is called local data. Data Scope :    The scope of data is the area in a program in which that data can be used (referenced). Data declared within a method can only be used in that method. a s si g n m e n t c o p i e s t he m em o r y l o c a t i o n : b = a. Data declared at the class level can be used by all methods in that class. C l a ss b . Before a b a After b 23 SATEESH N . R e fe re n ce s : A n o b j e c t r ef e r e n c e h ol d s t h e m em o r y a d d r e s s o f a n o bj e c t . p r i v a te wh e n o n l y m et h o d s i n t h e sam e cl a s s a r e p e r m i t t e d t o u se t hi s m et h o d . A m e t h o d c r e a t e d si m p l y t o a ssi st a se r v i c e m et h o d i s c a l l e d a su p p o r t m et h o d ) . A c c e ss sp e c i f i e r s c a n b e : p u b l i c wh e n a n y o n e c a n c a l l t hi s m e t h o d ( p u b l i c m e t h o d s a r e a l so c a l l e d se rv i c e m et h o d s.A c c e s s S pe c i fie r s SATEESH N I n J av a. A n a c c e ss sp e c i f i e r (v i si b i l i t y m o d i f i e r s) d ef i n e wh o i s a b l e t o u se t h i s m e t h o d . F o r o b j e ct r ef er e n c e s. p r o t e ct e d wh e n m e t h o d s i n t h i s c l a s s a n d m e t h o d s i n a n y su b c l a s se s m a y u se t h i s m et h o d . C l a ssA a = n e w C l a ssA ( ) . T wo o r m o r e r ef e r e n c e s t h a t r ef er t o t h e sa m e o b j e c t a r e c al l e d a l i a se s o f e a c h o t h e r. ( n o th i n g ) wh e n a n y c l a sse s i n t h i s p a r t i cu l a r p a c k a g e o r di r e c t o r y m a y a cc e ss t h i s m et h o d . we a c c o m p l i sh e n c a p su l a t i o n t h ro u g h t h e a p p r o p r i a t e u se o f v i si bi l i t y m o di f i e r s ( a m o di f i e r i s a J av a r e se rv e d wo r d t h a t sp e c i f i e s p a r t i c ul a r c h a r a c t e ri st i c s o f a m e t h o d o r d a t a v al u e ) .

W h e r e as o b j e c t s a r e p a ss e d b y r ef e r e n c e .println("After : } } 10 20 20 40 24 SATEESH N . Out put: Before : 10 Before : 10 After : After : 20 20 "+x+" "+y).x+" "+a.f1(a). B.y=20. a. c al v a l c a l r e f .out. y = y+20.x+" "+a.y = a.out.SATEESH N c a l l b y v al ue a n d c a ll b y r e fere n ce : W hi l e se n d i n g a r g u m e n t s t o a f u n ct i o n si m pl e d a t a t y p e s su c h a s i n t .y).x=10. A a = new A().out.y. will effect the original object in main i.x + 10. // } } class calvalcalref { public static void main(String args[]) { int x=10.e. // doesn't effect the original values } public static void f1(A a) { // a will be received by reference a.y=20. System. a.y). "+a.out. ' a ' System.x = a. a..println("Before : System. } class B { public static void f1(int x. // // sending by values sending by reference "+x+" "+y).y).int y) { // x and y will be received by values x = x+10. f l oa t e t c .println("After : System. "+a.f1(x. wi l l b e p a sse d b y v a l u e s.println(). .println("Before : System.out. j a v a Example : class A { int x.y + 20. B.

Reference variable b refers to a button object. by reference. it is simply a reference to an object (hence the term reference variable). So what is the consequence of this ? It means that within methodX you can update the button object via variable y e. So what happens when we call a method and "pass in an object" ? Well.we are not passing in an object. but it is being referenced by two different variables. Is it by value. However. Figure 1 illustrates this.setLabel("new text"). Two different reference variables refer to the one button object.g. 25 SATEESH N .g. then the value of the variable b is passed by value.   For primitives. Consider a method declared as public void methodX(Button y) If we call this method passing in a reference to a button object e. y. the variable b is not an object. In this example. Object b button object y Figure 2. You will typically come across a statement that "primitive types are passed by value. what does it mean to say that two reference variables have the same value ? It means that both variables refer to the same object. b Object button object Figure 1. and the variable y within methodX receives a copy of this value. you pass a copy of the actual value. rather we are passing in a reference to an object. methodX(b). In a Java statement such as Button b = new Button( ). Button b = new Button( ). and the calling routine will see the changes (as variable b refers to the same object). Variables b and y now have the same value. This is illustrated in Figure 2. and it is the reference to an object that gets passed by value. let's be clear about one thing . As figure 2 illustrates. parameters are always passed by value. Many people will read such a statement and end up with completely the wrong understanding of what happens. then the value of variable b within the calling method remains unchanged. you first need to be clear about the distinction between a reference variable and an object.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.SATEESH N The topic of parameter passing in Java seems to cause much confusion. but . and variable b will still refer to the same button object that it always did. you pass a copy of the reference To understand what this means. an object can have multiple references to it. we still have just the one object. but objects are passed by reference". For references to objects. Let me state clearly that: In Java. or both ? Search the Internet or read a few Java books and you will probably get even more confused. Even references to objects are passed by value. Java is pass-by-value.

out.getLabel()).out.out.println("The value of b's label is " + b.out. we get the situation shown in Figure 3. b Object button object y Object button object Figure 3. System.getLabel()).*. System. The example code below demonstrates how Java parameter passing works.println("The value of y's label is " + y.println("The value of i is " + i). The two different variables now reference different objects. if methodX now updates the button which y now refers to e.out.out. System. 26 SATEESH N .println("In main"). //the reference to an object is passed by value Button b = new Button("AAA"). System.out. methodX(b).println("Back in main"). System. System.out.println(""). y.awt. 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. System.out.println("In methodX"). then the original button object to which b refers to is unaffected by any such changes.g. System.getLabel()). With the two variables now referencing different objects. Example : PassByValue. } //the reference to an object is passed by value public static void methodX(Button y) { System.println("Back in main"). System. public class PassByValue { //Demonstrates that Java parameters are always passed by value public static void main(String[] args) { System. //primitives are passed by value as well int i = 5.println("The value of i is " + i). methodZ(i).SATEESH N For example. if in methodX we had y = new Button("another button").println("The value of b's label is " + b.out.setLabel("xxx").exit(0).java import java.

println("In methodZ"). System.out.out. //updating button that y now references has no affect on button referenced by b y. //make y reference a different object .out. } //primitives are passed by value as well public static void methodZ(int j) { System.getLabel()).println("The value of y's label is " + y.println("The value of y's label is " + y. System.println("The value of y's label is " + y.out. System. } } Output : In main The value of In methodX The value of The value of The value of The value of Back in main The value of The value of In methodZ The value of The value of Back in main The value of b's label is AAA y's y's y's y's label label label label is is is is AAA BBB CCC DDD b's label is BBB i is 5 j is 5 j is 6 i is 5 27 SATEESH N .getLabel()).doesn't affect variable i within main j = 6.println("The value of j is " + j).out.setLabel("BBB"). System.getLabel()).SATEESH N //update the button object that both y and b refer to y.out.doesn't affect variable b y = new Button("CCC"). System. //change value of j .setLabel("DDD").println("The value of j is " + j).

max = y. t4 = a.print("Test1: ").6] // test1 Interval t1. t3.println(mesg+" ["+min+".tempmax)). } // constructor that assigns instance variables public Interval addint(Interval b) { double tempmin = min + b.print("Test5: "). double tempmax = max + b.0] 28 SATEESH N . } // method main } // class returning_interval Output : Test1: Test2: Test3: Test4: Test5: [4.0.0] [4. t4. double max. t2.6.double y) { min = x.print("Test3: ").0. // test4 Interval t4 = new Interval(0.addint(b). } // method addint (add intervals) public void print(String mesg) { System. t1.print("Test2: ").max. // test3 Interval t3 = new Interval().6. // a = [1.SATEESH N U s i n g O b j ec t s a s P a r a m e te r a n d Re tu r n i n g O b je c t s Example: Use_Obj_as_Param_and_Returning_Obj.2).java class Interval { // instance variables double min.out. Interval() { } // empty constructor Interval(double x.print("Test4: ").0] [4.addint(b).4).0.0.0] [4. // test2 Interval t2 = a.0.4] // add a+b 5 different ways // all 5 tests give the same result = [4.0] [4. t1 = a. } // 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. // test5 a. // b = [3.6. t3 = a.addint(b).6."+max+"]").2] Interval b = new Interval(3.min.0).6. return (new Interval(tempmin.addint(b).addint(b).

Because local classes are not members. Nested top-level classes.Member inner classes are just like other member methods and member variables and access to the member class is restricted. Their visibility is only within the block of their declaration. This means a public member class acts similarly to a nested top-level class. Anonymous classes . Member classes . Local classes . private. Top-level inner classes implicitly have access only to static variables. outer. the modifiers public.If you declare a class within a class and specify the static modifier.Anonymous inner classes extend local inner classes one level further. specific to a block of code. just like methods and variables. and static are not usable. you cannot provide a constructor. protected. In order for the class to be useful beyond the declaration block. eg.There can also be inner interfaces. the compiler treats the class just like any other top-level class.inner. As anonymous classes have no name. class Base { void method1() { } void method2() { } } class A // normal class { static class B // static nested class { } class C // inner class { } void f() { class D { } } // local inner class void g() { // anonymous class Base bref = new Base() { void method1() { } }. } } 29 SATEESH N . All of these are of the nested top-level variety.Local classes are like local variables. The primary difference between member classes and nested toplevel classes is that member classes have access to the specific instance of the enclosing class. it would need to implement a more publicly available interface. you might have realized that it's possible to declare classes that are nested within other classes.I n n e r C l a s se s SATEESH N If you've done much Java programming. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package.

An inner class instantiation always remembers who it's parent object is and if anything changes in the parent object (e. In the example code.out.println("Inner2 class method").inner1_method(). autonomous object. it retains the scoping to its creator.println("Accessing outer_var1: "+outer_var1).java class class1 { // this value can access in inner classes and sub classes int outer_var1 = 10. Inner classes are very useful in factory pattern situations. void { inner1_method( ) System.out. Example : InnerClass_Ex1. inner1obj1. Inner2 inner2obj1 = new Inner2(). that change is reflected in all its inner class instantiations. Named Inner Classes An inner class is a class defined inside another class. Even if the inner class object is removed from the outer class object that instantiated it.println("Inner1 class method"). void outer_method() { Inner1 inner1obj1 = new Inner1(). } } } 30 SATEESH N . but in fact. System.g. An inner class object is scoped not to the outer class. but to the instantiating object. If an object has a reference to another object's ("parent object"'s) inner class object. B is a nested class. } class Inner1 { // variables and methods of this class can access within this class only int inner1_var = 100. it still has access to the private variables and methods of its parent object. System. void inner2_method( ) { System.println("Accessing outer_var1: "+outer_var1). while C is a nested class and an inner class.out. the inner class object is dealt with by that object as a separate.out. inner2obj1.inner2_method(). } } class Inner2 { // variables and methods of this class can access within this class only int inner2_var = 200. one of its property's value changes).SATEESH N A nested class that is not declared static is called an inner class.

Two ways to pass initializing parameters to an inner class: Initialize a property that the inner class then uses -.inner1_method(). Usages: Very useful for controlled access to the innards of another class. Anonymous inner classes are scoped inside the private scoping of the outer class. Note that it still retains its scoping. there is a problem with accessing local variables. Accessing outer_var1: 10 obj. Very useful when you only want one instance of a special class. References to an inner class can be passed to other objects. System.class2_method().SATEESH N class class2 extends class1 { void class2_method() { System.properties have the cross-method-call persistence that local variables lack. Disadvantage: the value cannot be changed. Example: actionPerformed events utilize the Observer-Observable pattern -. obj2. } } Anonymous Inner Classes Anonymous inner class: An inner class with no name. /* that inturn calls inner1_method().println("class2 method "). But there are some important differences: Anonymous inner classes must use the no parameter constructor of the superclass. } Output: } class2 method public class InnerClass_Ex2 Accessing outer_var1 of class1: { Inner1 class method public static void main(String[] args) Accessing outer_var1: 10 { Inner2 class method class2 obj = new class2().An instance of the observer is added to the observable. They can access the internal (private) properties and methods of the outer class. inner2_method() methods */ // obj.The method inner1_method is undefined for type class2 */ 10 class1 obj2 = new class1(). // obj.compiler will automatically transfer the value to a more persistent portion of the computer memory. /* Error.out. Anonymous inner classes are very similar to named inner classes: Anonymous inner classes can override methods of the superclass.outer_method().outer_method(). 31 SATEESH N . especially method input paramenters. Make the local variable "final" -.out. JBuilder creates an anonymous inner class to give to the button as its ActionListener.println("Accessing outer_var1 of class1: "+outer_var1). Since an object made from the inner class has a "life" independent of its outer class object.

Because an anonymous class has no name. Neither can an anonymous class be referred to outside its declaring expression. o o o o A local class is a nested class that is not a member of any class and that has a name.SATEESH N One key idea is that an anonymous class has no name. and always final.) An anonymous class is never abstract. (For example.) The definition. For example. each declaration of an anonymous class is unique. It can extend a class or implement an interface but cannot do both at the same time. An anonymous class is always implicitly final. Anonymous classes are never static. never abstract. Each anonymous class is declared within an expression. Base bref2 = new Base( ) { void method1() { } }. Programmer cannot define specific constructor for anonymous class but he/she can pass arguments (to call implicit constructor of its super class. Anonymous inner class does not have name. the following code declares two distinct anonymous classes: Base bref1 = new Base( ) { void method1() { } }. Also. except indirectly through a superclass or interface object reference. An anonymous class is a subclass of an existing class (Base in this example) or an implementation of an interface. Inner class types  Local inner class. o o o o o o . An anonymous class is always an inner class. The scope of a local class declared in a block is within the rest of the block. it cannot have an explicit constructor. it is never static. Local class defined in a method has access to final method variables and also to the outer class's member variables. construction and first use of such class is at same place. an anonymous inner class cannot say extends and implements at the same time. Every local class declaration statement is contained by a block. 32 SATEESH N  Anonymous inner class. Anonymous class defined in a method has access to final method variables and also to the outer class's member variables. Nested Classes Inner Classes An inner class is a type of nested class that is not explicitly or implicitly declared static.

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

j a v a class common { int no. qty=2. item="SAMSUNG key board". void accept() { no=10. : "+no+"\n Student Name: "+name+"\n Total Fee :"+tfee).I N H ER I T A N C E SATEESH N I n h e r i t a n c e i s t h e p r o c e s s o f c r e a t i n g n e w c l a s se s f r om ex i st i n g c l a sse s.totbil. float price. T h e c l a ss wh i c h i s b e i n g i n h e ri t e d i s k n o wn a s ‘ su p e r c l a s s ‘ a n d t h e c l a s s w h i c h i n h e ri t s t h e o t h e r c l a s s i s k n o wn a s ‘ su b c l a ss ‘ . totbil=price*qty. tfee=5000.println("\n Student No. name="Raj". .out. } class student extends common { int tfee. } } class customer extends common { int qty. A B C E x a m p l e : I n h e r i t en c e . name="Sateesh". c l a ss A { } c l a ss B ex t e n d s A { } J av a su p p o r t s m ul t i l ev e l I n h e ri t a n c e b u t d o e s n o t su p p o r t m u l t i pl e I n h e r i t a n c e . price=150. T o i n h e r i t a c l a ss i n t o a n o t h e r c l a s s. void accept() { no=101. } void display() { System. } 34 SATEESH N A  su p e r c l a s s B  su b c l a ss A M ul t i l ev el I n h e r i t a n c e su p p o r t e d b y J av a C B M u l t i pl e I n h e ri t a n c e n o t su p p o r t e d b y J av a String item. String name. t h e k e y wo r d ‘ e x t e n d s ‘ sh o u l d b e u se d .

SATEESH N void display() { System. T o r ef e r t o t h e v a ri a b l e s of t h e su p e r c l a ss.0 C o n s t r u c to r s i n th e c a s e o f I n h e r i t a n c e : W h e n ev e r a su b c l a ss o b j e c t i s c r e a t e d t h e su p e r c l a s s c o n st r u c t o r wi l l b e c a l l e d f i r st a n d t h e n t h e su b c l a s s c o n st r u c t o r .0 300. Ex: c l a ss A { } c l a ss B ex t e n d s A { Ex ec u t i o n t a k e s p l a c e f r om b ot t om t o t o p } c l a ss C e x t e n d s B { } S u p er k e y wo r d : T h e ‘ t h i s ‘ r e f e r e n c e v a ri a b l e al wa y s r e f e r s t o t h e c u r r e n t c l a ss .accept(). i.out. : 10 Student Name: Sateesh Total Fee :5000 Customer No. Item purchased: "+item+"\n Quantity Total Bill : "+totbil). : Customer name : Item purchased: Quantity : Price : Total Bill : 101 Raj SAMSUNG key board 2 150. customer c = new customer(). I f t h e r e a r e m o r e t h a n o n e su p e r c l a s se s c o n st r u c t o r s wi l l b e c al l e d i n t h e o r d e r of I n h e r i t a n c e . c. 35 SATEESH N .display(). T h e ‘ su p e r ‘ k e y wo r d c a n b e a p p l i e d i n 3 c a t e go r i e s. iii. s. s.println("\n Customer No. ii. T o r ef e r t o t h e m e t h o d s of t h e su p e r c l a ss. c. A n d t h e ‘ su p e r ‘ r e f e r e n c e v a r i a bl e a l wa y s r e f e r s t o t h e i m m e di a t e su p e r c l a s s.display().accept(). } } : "+no+"\n Customer name : "+name+"\n : "+qty+"\n Price : "+price+"\n Out put: Student No. } } class Inheritence { public static void main(String args[]) { student s = new student(). T o c al l a su p e r c l a ss c o n st r u c t o r f r om t h e su b c l a ss c o n st r u c t o r s.

} } class B extends A { int x.display().x=b. } } Out put: ’x’ Value of Class A is: 10 ’x’ Value of Class B is: 20 Example : Co n s t r u c t o rT O Co n s t ru c t o r _ I n h e r i t e n c e . } } class C o n st r c t o r s_ I n h e r i t e n c e { public static void main(String args[]) { B b = new B(10. class A { int x.20). } 36 SATEESH N // constructor of class A . } } class B extends A { int z.out.b). T o r ef e r t o t h e m et h o d s o f t he su p e r c l a ss.x=x. T o r ef e r t o t h e v a r i a bl e s o f t h e su p e r cl a ss. j a v a / / Pr o g r am f o r i i i . this. // sends the 1st 2 arguments to the super class constructor this. //calls display() of class A System.out.println("’x’ Value of Class B is: "+x).int y) { this.z=c. b.display(). A(int x.int b) { super. } void display() { super.y=y. T o c al l a su p e r c l a ss c o n st r u c t o r f r om t h e su b c l a ss c o n st r u c t o r s.int b. j a v a / / Pr o g r am f o r i . i i .println("’x’ Value of Class A is: "+x). B(int a. class A { int x.x=a.int c) // constructor of class B { super(a. B(int a.SATEESH N E x a m p l e : C o n s t r c t o r s _ I n h e r i t e n c e.y. // variable void display() // method { System. this.

} O v e r ri d d e n Me t ho d s W h e n ev e r a f u n ct i o n of su p e r c l a ss a l so d e f i n e d i n t h e su b c l a s s. Ex: c l a ss A { void f 1( ) { } } c l a ss B ex t e n d s A { v oi d f 1 ( ) / / ov e r ri d d e n { } } I n J av a a r e f e r e n c e v a r i a bl e of ‘ su p e r c l a s s ‘ c a n r e f e r t o a n i n st a n c e o f c l a ss ‘ a n d i s a b l e t o c al l t h e ‘ ov e r ri d d e n ‘ f u n ct i o n. f 1 ( ). f 1 ( ). } } NOTE: C a l l i n g a ‘ s u p e r c l a s s ‘ c o n st r u c t o r f r om t h e ‘ su b c l a s s ‘ c o n st r u c t o r u si n g t h e ‘ su p e r ‘ i n a f u n ct i o n st yl e m u st b e t h e f i r st st a t e m e nt i n t h e ‘ su b c l a ss ‘ c o n st r u c t o r . B b = new B( ). z= c . A r.30).println("Values are: "+x+" } } class C o n st r u c t o r T O C o n st r u c t o r _ I n h e r e i t e nc e { "+y+" "+z). Ex : B ( ) { su p e r ( ) .display(). Ex: A a = new A( ).out. t h e n t h e f u n ct i o n i s k n o wn a s o v e r ri d d e n . // calls B's constructor which calls A's constructor b. Out put: Values are: 10 20 30 public static void main(String args[]) { B b = new B(10. b .SATEESH N void display() { System. t h i s. / / r i s r ef e r e n c e v a r i a bl e of su p e r c l as s A 37 SATEESH N ‘ su b . a .20.

S y st em .println("Student Details : "+sno+" } } class customer extends common { int cno. i f t h e c h o i c e i s ‘ 2 ’ a c c e p t a n d di sp l a y c u st o m e r d e t a i l s. r r . f 1 ( ). } "+sname). E x a m p l e : D y n a mi c M e t h o d Di s p a t c h . i n . void accept() { cno=20. / / c al l s a . int qty. product = "Mouse". a . f 1 ( ). Ex: i n t c h = S y st em . r e a d ( ) : R e a d s a c h a r a c t e r f ro m t h e k e y b o a r d a n d r e t u r n s t h e “ A S C I I v al u e “ of t h a t c h a r a c t e r.out. String sname. b D y n a mi c M e th o d D i s p a t ch : S y s t e m . r = b. / / c al l s b. rate=150. o u t . int tfee. f 1 ( ). tfee=1500.SATEESH N a r = a. qty=2.product. r e a d ( ). String cname. class common { void accept() { } void display() { } } class student extends common { int sno. p t o a c c e p t a c h oi c e f r om t h e u se r . function // over ridden 38 SATEESH N . } void display() // over ridden function { System. r r . void accept() // over ridden function { sno=10. i n . sname="Sateesh". p ri n t l n ( c h ) . i f t h e c h o i c e i s ‘ 1 ’ a c c e p t a n d d i sp l a y st u d e n t d e t a i l s.rate. j a v a / / w. cname="Raj". f 1 ( ) .

accept(). //r2.println("Customer Details: "+cno+" "+cname+" "+product+" "+qty+" "+rate).out.out. method accept() in abstract class common student obj = new student(). r. System. \"r2\"").out.accept(). r.out.println("Enter 1: Student ch = (char) System.display().println("Throgh object r2 = new student(). obj. System. the method display() is undefined for type common } } 39 SATEESH N . } } public class Inheritence_Ex1 Output : { Throgh object "r" public static void main(String[] args) method accept() in class common { Throgh object "obj" common r = new common().display(). } } 2: Customer\n ").read().println("method accept() in class common"). common r2. Out put: Enter 1: Student 2: Customer 1 Student Details : 10 Sateesh Out put: Enter 1: Student 2: Customer 2 Customer Details: 20 Raj Mouse 2 150 Example : Inheritence_Ex1. method accept() in class common System.out.accept().accept(). if(ch=='1') r = new student(). \"obj\""). } } class student extends common { void display() { System. else r = new customer(). common r. } } class D y n a m i c M et h o d D i sp a t c h { public static void main(String args[]) throws Exception { char ch.java class common { void accept( ) { System.println("Throgh object obj.display().println("Throgh object \"r\""). method display() in class student Throgh object "r2" r.in.SATEESH N void display() // over ridden function { System. r2. System.println("method display() in class student").out. // Error.out.

println("method display() in class common").println("Throgh object r2 = new student(). r2. } } class student extends common { void accept( ) { System. \"r2\"").SATEESH N N o t e : I n t h e a b ov e ex am pl e t h e di sp l a y ( ) m e t h o d m u st b e d e c l a r e d i n su p e r c l a ss c o m m o n t o a cc e ss t h e d i sp l a y ( ) m et h o d i n t h e su b c l a s s.println("method accept() in class common"). Example : Inheritence_Ex2.out. obj.out.display().accept(). method display() in class student student obj = new student(). } } \"obj\""). } } Output : public class Inheritence_Ex2 Through object "r" method accept() in class common { method display() in class common public static void main(String[] args) Through object "obj" { method accept() in class studnet common r = new common().display().out. t h r o u g h r ef e r e n c e v a ri a b l e r 2 . } void display() { System. Through object "r2" r.println("Throgh object obj.display().println("Throgh object \"r\""). common r2.println("method display() in class student").out. method accept() in class studnet r.out.println("method accept() in class studnet").java class common { void accept( ) { System. } void display() { System.accept(). 40 SATEESH N . r2. System. System. method display() in class student System.out.accept().out.

Note: A b st r a c t f i n al i s n o t al l o we d . c a n ’ t m o di f y t h e v al u e For the methods : Ex: A f i n a l m e t h o d c a n ’ t b e ov er r i d d e n . MA X = 5 0 . c a n ’ t ov er r i d e ex t e n d f i n a l c l a ss. f i n al c l a ss A { } c l a ss B e x t e n d s A { } / / E r r o r . su c h v a ri a b l e b e c om e s a c o n st a n t . T h e ‘ f i n al ‘ k e y wo r d c a n b e sp e c i f i e d f or t h e v a ri a bl e s.SATEESH N F in a l k e y wo r d : a n d c l a sse s. 41 SATEESH N . // E rr o r . m et h o d s F o r t h e v ar i a bl e s : W h e n ev e r a v a ri a bl e i s sp e c i f i e d a s f i n a l . Ex: f i n al i n t M A X = 1 0 0 . c l a ss A { f i n al v o i d f 1( ) { } } c l a ss B ex t e n d s A { f i n al v o i d f 1( ) { } } / / E r r o r c a n ’ t ov e r ri d e f i n al m et h o d F o r t h e c l a sse s : Ex: A f i n a l cl a ss c a n ’ t b e e x t e n d e d .

T h e r e c a n ’ t b e a n y i n st a n c e s o f a n a b st r a c t c l a ss. Ex: class student extends { void accept( ) { } void display( ) { } } common T h e a b ov e e x am pl e d o e s n o t g e n e r a t e a n y e r r o r s. b e c a u s e a l l t h e f u n ct i o n s o f c l a ss c o m m o n a r e ov e rr i di n g i n cl a ss st u d e n t .A b s t r a c t me t ho d s a n d A b s t ra c t c la s s e s SATEESH N W h e n ev e r a f u n ct i o n of su p e r c l a ss i s u se d o n l y f o r t h e p ol ym o r p h i sm a n d i s n o t c o n t a i n i n g a n y st a t em e n t s t h e n t h a t f u n c t i o n c a n b e sp e c i f i e d a s a b st r a c t b y p r e f i x i ng t h e f u n c t i o n d e cl a r a t i o n wi t h k e y wo r d ‘ a b s t r a c t ‘ . Ex: class student extends { void accept( ) { } } common T h e a b ov e ex am p l e g e n e r a t e s E r r o r i n c om pl e t e ov e r ri di n g . r = new c om m o n ( ) . abstract void f2(). c o m m o n r. // ok / / E r r o r c a n ’ t i n st a n t i a t e a b st r a c t cl a ss / / o k . r = new st u d e n t ( ) . } W h e n ev e r a c l a ss e x t e n d s a n a b st r a c t c l a ss t h e n t h e c l a ss sh o u l d c o m p u l so r i l y ov e r ri d e al l t h e a b st r a c t m e t h o d s o f t h e su p e r c l a ss.java abstract class abstractclass { abstract void f1(). } 42 SATEESH N . st u d e n t i s n o t ab st r a c t E x a m p l e : AbstractClass_Ex1. r ef e r e n c e v a ri a b l e s o f t h e a b st r a c t c l a sse s a r e a l l o we d i n t h e pr o g r a m .out.println("Hi"). H o w ev e r . abstract void d i sp l a y ( ). W h e n ev e r a cl a ss c o n t a i n s a t l e a st o n e a b st r a c t f u n ct i o n t h e n t h e cl a ss sh o u l d a l so b e sp e c i f i e d a s a b st r a c t . Ex: abstract c l a ss c om m o n { abstract void a c c e p t ( ) . } class Hi extends abstractclass { void f1() { System.

obj. obj = new Hi(). obj. r = new student ( ).java common void void accept( ). } } calls non-abstract method f1( ) from the common class 43 SATEESH N . f2( ) // non abstract method class student extends common { void accept( ) { System. } } class AbstractClass_Ex1 { public static void main(String args[]) { Hi h = new Hi().accept( ). h. display( ).println("Hello").out. h.f1(). abstractclass obj.out.f1().SATEESH N void f2() { System. } void display( ) { } } class Abstract_abstmeth_nonabstmeth { public static void main(String args[]) { common r. // abstract method // abstract method Output: Hi Hello Hi Hello abstract class { abstract abstract void { } void { } } f1( ) // non abstract method System.f1( ). } }  A n a b st r a c t cl a ss c a n c o n t a i n a b st r a c t as w e l l a s n o n . // calls // student accept( ).a b st r a c t m e t h o d s. Example: Abstract_abstmeth_nonabstmeth. r.f2().out. Output: Hello HI r.println("HI").f1().println("Hello").

java abstract class common { void accept() { System.println("HI"). it may be convenient sometime to simply redefine the abstract method at the instantiation of its abstract class.println("Hello"). some classes inheriting from MyAbstractClass can be redefined with the 'do' method. E x a m p l e : AbstractClass_nonabstmeth. the type common can not be instantiated common obj = new student().out. } } Output: public class AbstractClass_nonabstmeth Hello { HI public static void main(String[] args) { // common obj = new common().SATEESH N  A cl a ss c a n b e sp e c i f i e d a s a b st r a c t ev e n i t i s n o t c o n t a i ni n g a n y a b st r a c t m e t h o d s we c a n ’ t c r e a t e i n st a n c e s o f i t s su b c l a s se s i f t h e y a r e n o t a b st r a c t . } } 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. This only requires the following lines: MyAbstractClass myClass = new MyAbstractClass( ) { void do( ) { // Redefine here the abstract method } }. obj. obj. 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. } void display() { } } class student extends common { void display() { System. However.out.accept(). // Error. 44 SATEESH N .display().

int b). } // overridden method public void add(int a. this. } // overridden method public void sub(int a. } 45 SATEESH N . } // new method public void sub(int a. } // overridden method public void add(int a.SATEESH N E x a m p l e : AbstractClass_Ex2.out.out.println(a+b).int b) { System.a=0.b. abstclass3() { this. } } class abstclass4 extends abstclass2 { int a.println((a+b)).b=0.out.out.out.println(a-b).int b).println(a-b). } abstract class abstclass2 extends abstclass1 { public abstract void sub(int a. } } public class AbstractClass_Ex2 { public static void main(String[] args) { abstclass1 obj = new abstclass1() { public void add(int a.int b) { System.b.int b) { System. } class abstclass3 extends abstclass1 { int a.b=0.java abstract class abstclass1 { public abstract void add(int a.a=0.int b) { System. this.println(a+b). abstclass4() { this.int b) { System.

30). // can't call sub() method. // calling overridden method st4. // calling newly defined method in abstractclass3 abstclass4 st4 = new abstclass4().30).println((a-b)).35).println((a+b)).30).sub(20. // calling abstractclass2 methods obj1. st4.sub(20.30).add(10.int b) { System. obj1.out.println((a-b)).sub(50.sub(50.out.add(10.30).int b) { System. bcoz not declared in abstract //class abstractclass1 abstclass2 obj1 = new abstclass2() { public void add(int a.add(20. } public void sub(int a.35).SATEESH N // defining a new method public void sub(int a. //obj.add(20. out put : 50 50 -10 45 20 45 20 abstclass3 st3 = new abstclass3(). st3. } }. // calling overridden method } } 46 SATEESH N . } }.int b) { System.out.30). // calling abstractclass1 methods obj. // calling overridden method st3.

else r = new customer().println("Customer Details: "+cno+" "+cname+" "+"product"+qty+" "+rate).java interface common { void accept(). Enter 1: Student 2: Customer } 2 public void display()//overridden function Customer Details: 20 Raj product2 150 { System. Example : Interface_Ex1.I n t e r fa ce s SATEESH N A n i n t e rf a c e i s a c o l l e c t i o n o f si g n a t u r e s o f f u n ct i o n s a n d f i n a l v a ri a b l e s. } } 47 SATEESH N 2: Customer\n ").read(). if(ch=='1') r = new student(). public void accept() // overridden function { cno=20. r. W h e n ev e r a c l a ss i m pl em e n t s t h e i n t e rf a c e. output : Enter 1: Student 2: Customer 1 Student Details : 10 Sateesh 1500 public void accept()//overridden function { sno=10. output : sname="Sateesh".println("Enter 1: Student ch = (char) System.println("Student Details : "+sno+" "+sname+" "+tfee). } } class customer implements common { int cno. qty=2. int qty. String cname. void display(). int tfee.out. } } class I n t e rf a c e _ Ex 1 { public static void main(String args[]) throws Exception { char ch.in. O n c e a n i n t e rf a c e i s c r e a t e d a c l a s s c a n i m p l em e n t t h e i n t e rf a c e.accept().product. rate=150. tfee=1500.rate. } public void display() // overridden function { System. String sname.out.display(). t h e c l a ss sh o u l d ov e r ri d e al l t h e m et h o d s o f i nt e rf a c e . cname="Raj". r. product="Mouse". . System. } class student implements common { int sno.out. common r.

f2(). the type cannot be instantiated //B b = new B( ). } } // OK Output : Hi Hello Hi Hello Extended Interfaces : A n i n t e rf a c e c a n e x t e n d e d a n o t h e r i n t e r f a c e u si n g t h e k e y wo r d “ e x t e n d s “ . } class { C implements A. } interface B { void f2( ). b=c.SATEESH N M u l ti p l e i m p l e m e n t s : A c l a ss c a n i m pl e m e n t a n y n um b e r of i nt e rf a c e s su c h c l a s s sh o u l d ov e r ri d e a l l t h e m e t h o d s i n a l l t h e i n t e rf a c e s. c. } } class Interface_MultipleInheritence { public static void main(String args[]) { //A a = new A( ). } A 48 SATEESH N .B public void f1( ) { System. //Error.println("Hello"). A a. a=c. Ex: interface A { void f1( ).f1( ). B b. a. } public void f2( ) { System.out. // Error. W h e n ev e r a cl a ss i m p l e m e n t s t h e l a st i n t e rf a c e t h e cl a ss sh o u l d ov e r ri d e al l t h e m et h o d s i n t h e i n t e rf a c e c ha i n .out.f1().println("Hi"). the type cannot be instantiated C c = new C( ). b.f2( ). Ex: interface A { void f1( ). c. } interface B extends { void f2( ).

c.out.println("Hello").f2( ).f1( ). //Error. } public void f2( ) { System.println("Hello").f2(). the type cannot be instantiated C c = new C( ).f1(). b.out. b ut d o e s n o t ov e r ri d e a l l t h e m e t h o d s o f t h e i n t e rf a c e su c h c l a ss sh o u l d b e s p e c i f i e d a s a b st r a c t . // Error. } } class Interface_extend_Interface { public static void main(String args[]) { //A a = new A( ). the type cannot be instantiated //B b = new B( ). B b.println("Hi"). W e sh o u l d c r e a t e a n o t h e r c l a ss t h a t e x t e n d s t h e a b st r a c t c l a ss a n d sh o u l d o v e r ri d e t he l ef t ov e r m e t h o d s. A a. c. a=c.out.println("Hi"). } } 49 SATEESH N . } abstract class B implements A { public void f1( ) { System.out. void f2( ). } } // OK Output : Hi Hello Hi Hello P a r t i a l i m p l e m en t s : W h e n ev e r a cl a ss i m p l em e n t s a n i n t e rf a c e . a. b=c.SATEESH N class C implements B { public void f1( ) { System. Ex : interface A { void f1( ). } } class { C extends B public void f2( ) { System.

O n c e t h e c l a ss p a t h i s se we a r e a b l e t o a c c e s s t h e c l a s se s i n t h e su b d i r e c t o r i e s f r om a n y l o c a t i o n i n t he sy st e m . An interface is used to define only the methods and constants that are to be shared by its implementers. In a more general sense. the type cannot be instantiated C c = new C( ).f1( ). Neither an interface nor an abstract class can be directly instantiated. E : \ > sa m p a c kE . D : / > S E T C L A S S PA T H= % cl a ssp a t h % . an interface is an abstract class that defines no implementation.f2(). // Error. 50 SATEESH N . H o w ev e r a c l a ss c a n i m p l em e n t a n y n um b e r o f i n t e rf a c e s.f2( ). c. 1 . } } // OK Output : Hi Hello Hi Hello Interface vs. V e r i f y i n g t h e cl a ssp a t h : D: \ > e c h o % cl as sp a t h % T o a d d i n g a n e w su b d i r e c t o r y t o p r ev i o u s su b d i r e c t o ri e s. A c l a ss c a n e x t e n d s o n l y o n e c l a ss. a=c. Abstract Class difference between an interface and an abstract class : Within the confines of Java syntax. //Error. a. an abstract class may define non-constant members and non-abstract methods. H o wev e r an i n t e rf a c e c o n t a i n s o n l y t h e si g n a t u r e s of t he f u n c t i o n s. you inherit all of the implemented methods and only need to implement those that were left undefined (abstract). C L AS S P AT H : T h e cl a ss p a t h i s a n e nv i ro n m e n t v a ri a bl e se t i n t h e o p e r a t i n g sy st e m wh i c h c o n t a i n s a c o l l e c t i o n of su b d i r e c t o ri e s wh e r e e a c h s u c h d i r e c t o r y c a n c o n t ai n a n y n u m b e r o f cl a ss f i l e s. When you implement an interface. An abstract class is often used to define the common set of features required of its implementing subclasses. A n a b st r a c t c l a ss c a n c o n t a i n a b st r a c t as w e l l a s n o n . When you extend an abstract class. an interface is a type that only defines abstract methods and constant ( finbal ) members. f : \ sam pa c k F . you must provide the code for all of the methods in the interface.SATEESH N class Interface_Abstract { public static void main(String args[]) { //A a = new A( ). D : / > e c h o % c l a ssp a t h % T h e cl a ssp a t h i s a n e nv i r o nm e n t v a ri a b l e wh i c h wi l l b e r em ov e d o n c e t h e c o m m a n d p r om p t i s cl o se d .a b st r a c t m e t h o d s. b. the type cannot be instantiated //B b = new B( ). 2 . A a. c. However. D : \ > S E T C L A S S PA T H= d : \ sam p a c k D . You may implement an interface using the implements keyword and extend an abstract class using the extends keyword. b=c. B b.f1(). including data structures and method implementations.

java . // filename : package p1. B.java // placed in d:\sampackD\p1\A.SATEESH N P A C KA G ES A p a c k a g e i s a c ol l e c t i o n of cl a sse s t h a t c a n b e i m p o rt e d i nt o o t h e r p r o g r a m s. j av a f:\> sa m p a c k F p2 C . f : \ sa m p a c k F . D W e sh o u l d se t t h e cl a ssp a t h b e f o r e c om pi l i n g t h e p a c k a g e s. j av a B . j av a D : \ > S E T C L A S S PA T H= % cl a ssp a t h % . j av a e:\> core p a c k .out. T o m a k e a c l a ss b e l o n g i n g t o a p a c k a g e . public class B { public void display() { System.java // placed in d:\sampackD\p1\B. d : \ sa m p a c k D .out. i m p or t s A . A p a c k a g e wo r k s si m i l a r t o a l i b r a r y wh i c h i s a c o l l e c t i o n of c l a sse s. j av a / / c o n t a i n s m ai n ( ).println("Display } } // filename : package p1. T o c r e a t e a p a c k a g e a s u b d i r e c t o r y i s r e q u i r e d . public class A { public void display() { System. t h e p a c k a g e n a m e sh o u l d b e sp e c i f i e d a s t h e f i r st st a t em e n t i n t h e p r o g r am . Ex: d:\> sa m p a c k D p1 A .java from A"). } } 51 SATEESH N A. T h e n a m e o f t h e p a c k a g e wi l l b e t h e n a m e of t h e su b d i r e c t o r y . B. T h e s e c l a sse s c a n b e i m p o r t e d a n d u se d i n o t h e r J av a p r o g r am s. C .println("Display from B"). j av a D .

B. public class C { public void display() { System.println("Display from D"). a. } } Out put: Display Display Display Display from from from from A B C D 52 SATEESH N .java // placed in f:\sampackF\p2\D. C c = new C(). } } // filename : D.A.println("Display from C"). c.SATEESH N // filename : C.display(). d. b.java // placed in f:\sampackF\p2\C.display().display().out. public class D { public void display() { System.java package p2. import p1.java this class contains the main( ) .java package p2. D d = new D(). import p2. class pack { public static void main(String args[]) { A a = new A(). B b = new B(). this can be placed any where // import the selected class // import all the classes import p1.*.out. } } // // filename : pack.display().

: F o r n et wo r k i n g . o b j ec t c l a ss i s t h e su p e r c l a ss f o r a l l t h e cl a sse s. st r i n g . 3000 t Ex: st u d e n t t = new st u d e n t ( ) . 20 Sanju 3000 s ! = t. sq l  j av a . l a n g p a c k a g e . e . u t i l  j av a . c o l l e ct i o n s e t c .  j av a . K 2000 b o o l e a n e q u a l s( o b j e c t o b j ) : C om p a r e s t h e h a sh c o d e s o f b ot h t h e o bj e c t s a n d r e t u r n s t r u e i f b o t h a r e e q u a l . t h i s pa c k a g e wi l l b e i m p o r t e d i n t o ev e ry j av a p r o g r am b y d ef a ul t . : C o n t ai n s c l a sse s f o r m a n g e i n g d a t e s. c o n t ai n s c l a sse s f o r G UI . : C o n t ai n s c l a sse s f o r m a n a g i n g d a t a b a se t r a n sa c t i o n s. a p p l et : F o r a p p l et m a n a g em e n t . F o r a l l t h e r em a i ni n g cl a sse s t h e O b j e ct cl a ss b e c o m e s t h e su p e r c l a ss. i o  j av a . : AW T st a n d s f o r A b st r a c t W i n d o ws T o o l ki t . i nt e g e r . . I n J av a o n l y t h e O bj e c t c l a ss wi l l n o t h av e a su p e r c l a ss. o bj e c t et c . o t h e r wi se f al se .  j av a . W h e n ev er we c r e a t e a c l a s s wh i c h d o e s n o t i n h e r i t a n y o t h e r cl a ss b y d e f a u l t i n h e r i t s t h e o b j e c t cl a ss i . 2000 S Ex: st u d e n t s = new st u d e n t ( ). a wt  j av a . class O bj e c t { } class A { } class B extends A { } Ex: O b j e ct A B O b j e ct cl a ss i s c o n t a i n i n g t h e f ol l o wi n g m e t h o d s : p u b l i c i n h a sh C o d e ( ) : R e t u r n s t h e u n i q u e i d e n t i f i c a t i o n f o r e a c h i n st a n c e of t h e c l a ss. 10 Sateesh 2000 k = s. n e t  j av a . 53 SATEESH N . : C o n t a i n s cl a sse s f o r I / P an d O / P.SATEESH N T h e f ol l o wi n g a r e t h e l i st of som e p r e d e f i n e d p a c k a g e s wh i c h wi l l b e i n st a l l ed wi t h J D K . l a n g : T h i s p a c k a g e c o n t ai n s t h e i m p o rt a n t cl a sse s l i k e sy st e m . Object Class : I t i s d e f i n e d i n j av a . . .

equals(r)) System.println(t).toString()). if(s. System. } String sname="Sateesh".println("R Hash code: System.out.out.println("S and T are equal"). System.println(s).out. "+r.out.println("S and R are equal").out. System.toString()).toString()). 54 SATEESH N .hashCode()).out.println(s.toString()).out. } } // calls System. System.println().out.println("S Hash code: System.println(). System.out.println(r).hashCode()). System.out.println(t. if(s.out. R e t u r n s t h e h a sh c o d e i n t h e h e x a d e c i m al f o rm a t p r ef i x e d wi t h E x a m p l e : ObjClas_hashcode_equals . j a v a class student { int sno=10.SATEESH N S t ri n g t o S t ri n g ( ) : n a m e of t h e c l a ss.out. S and T are not equal S and R are equal student@360be0 student@45a877 student@360be0 student@360be0 student@45a877 student@360be0 T h e t o St r i n g f u n c t i o n c a n b e ov e r ri d d e n i n a n y c l a ss t o r i d d e n a n y u sef u l i nf o rm at i o n .println("S and T are not equal"). student t = new student(). class ObjClas_hashcode_equals { public static void main(String args[]) { student s = new student().println(r.println("S and R are not equal"). System.equals(t)) System.out.out. System.out. "+t. System.println("T Hash code: System.out.println(s. Out put: S Hash code: T Hash code: R Hash code: 3541984 4565111 3541984 "+s.println(). else System.hashCode()). else System. student r = s.out.

so we need to handle this error.1000).println(t). So we need to type-cast the result. j a v a class student { int sno. this. student t = new student(20. copying of objects is called cloning. In fact.println(r). In JAVA.out."Sateesh". } } // calls s. Thus after editing the object (e. the copy( ) method is called clone( ) in JAVA.println(s). The clone( ) method is declared in Object to throw the CloneNotSupportedException.sno = sno."Raj ". System. we simply have to implement the Cloneable interface in our class: class Student implements Cloneable { . to clone in JAVA means to make a local copy of an object. this. } public String toString() { String str = sno+" return str. file or record) we still be able to cancel and revert back to a saved version. String sname.}   Since clone( ) is a general method..out.1200).tfee = tfee.. There are two basic kinds of copying strategies: shallow copying and deep copying.1500). 55 SATEESH N . student r = new student(30.out. Cloning : Sometimes it is necessary to copy objects so that we can manipulate the data within it without destroying the original object. student(int sno. So.SATEESH N E x a m p l e : Objclass_toString. System. JAVA has a clone( ) method which can be used for copying any object.. int tfee. System.g. Shallow Copying : In order to use this method.sname = sname. } } class Objclass_toString { public static void main(String args[]) { student s = new student(10. it has a return type of Object..toString() Out put: 10 20 30 Sateesh 1500 Sanju 1000 Raj 1200 //overridden "+sname+" "+tfee. String sname. int tfee) { this."Sanju".

the elements of the original are shared with the copy. The basic clone( ) method in Object checks if the class (subclass) is cloneable.e. then you'll get a compile error. } void display() { System. shared with the original). these inner parts are still shared !!! So we may not really have a completely separated copy.out. If you try to clone a noncloneable object (such as an Integer object). If we want to make a publicly available clone( ) method. int net. handle or throw a CloneNotSupportedException Here is what the clone( ) method for Student may look like:: public Object clone() { try { return super.java class Marks { int datacommunications.out. networks = net. This form of cloning is called a shallow copy. } } Example : Shallow_clone_Ex1.println("CryptoGraphy : "+cryptography). the object is cloned but the objects within it are not (i. What does that mean ? Well if the copied object contains inner parts. it throws a CloneNotSupportedException. Hence. we have to write our own (more later). System. } } 56 SATEESH N . A clone( ) method MUST:     have a return type of Object take no parameters call super.clone().println("NetWorks : "+networks).out. If not.println("Marks:: "). cryptography = cryp.SATEESH N The clone( ) method is declared in Object as protected. So by default. It is a little bit like two people having different straws but sharing the same contents of a drink.println("DataCommunications: "+datacommunications). most classes in the standard JAVA library are not Cloneable. void accept(int dc. } catch (CloneNotSupportedException e ) { throw new Error("This should never happen!"). int networks. Here.int cryp) { datacommunications = dc. System. Oddly enough.out. int cryptography. we can only use the clone( ) method in its own class or one of its superclasses.clone(). System.

println("After System. ").out. obj_one. sname = "sateesh".m.out.sname).display().out.44). System.sname).m. obj_one.m. System. System. // Values of Inner Object " m " of class Marks gets change in both objects // obj_one and obj_two. "+obj_one. } } } public class Shallow_clone_Ex1 //implements Cloneable { public static void main(String [] args) { Student obj_one = new Student ().println("Modified obj_two.SATEESH N class Student implements Cloneable { int sno=50.accept(44. System. // copying contents of obj_one into obj_two Student obj_two = (Student)obj_one.display().sno+" "+"Name: clone Contents in obj_two: "+obj_two.out.out.sname). obj_two.println("sno: "+obj_two.m.println("After System.sno+" "+"Name: "+obj_one.sname).44.accept(40.out.println("Modifying obj_two.out. System. "+obj_one.display(). obj_one.display().println("sno: obj_two.out.. "+obj_two.out.clone().46).sno = 200.m.sno+" "+"Name: "+obj_one. } catch (CloneNotSupportedException e ) { throw new Error("This should never happen!").println("sno: obj_one.sname = "Kumar". "). System. System. System.println("Before clone Contents in obj_one: ").m.println("sno: "+obj_one.out.println("sno: obj_one.38.display().sno+" "+"Name: "+obj_two.. } } 57 SATEESH N . obj_two. String sname = "SATEESH". System. obj_one. } public Object clone() { try { return super.out.println("After modified obj_two Contents in obj_one: ").sname).sno+" "+"Name: ").. Marks m = new Marks(). "). System.clone(). { // worked as consturctor sno = 100. because they share same memory locations.println("After modified obj_two Contents in obj_two: "). clone Contents in obj_one: "+obj_one.out..m.

.SATEESH N Output : Before clone Contents in obj_one: sno: 100 Name: sateesh Marks:: DataCommunications : 40 NetWorks : 38 CryptoGraphy : 46 After clone Contents in obj_one: sno: 100 Name: sateesh Marks:: DataCommunications : 40 NetWorks : 38 CryptoGraphy : 46 After clone Contents in obj_two: sno: 100 Name: sateesh Marks:: DataCommunications : 40 NetWorks : 38 CryptoGraphy : 46 cont..java copy constructors and static factory methods provide an alternative to clone. Modified obj_two.. Essentially.. Modifying obj_two. . 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. 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 .. or at least know enough about the classes to be sure that their deep copies are performed properly. Example : Deep_clone_Ex1. and so on . and forward to a regular constructor are unnecessary for immutable objects 58 SATEESH N . .. After modified obj_two Contents in obj_one: sno: 100 Name: sateesh Marks:: DataCommunications : 44 NetWorks : 44 CryptoGraphy : 44 After modified obj_two Contents in obj_two: sno: 200 Name: Kumar Marks:: DataCommunications : 44 NetWorks : 44 CryptoGraphy : 44 Deep Copying : A Deep Copy attempts to make a completely separate copy of an object by copying its internal parts as well. you must control all of the code in all of the classes.

2."). } catch(ArithmeticException ex) { System.20. 4. I n j av a w h e n e v e r a n ex c e p t i o n o c c u r s. } catch(ArrayStoreException ex) { System. } static void display(int n) { try { System. j a v a class TryCatch { static int arr[]={10. All the statements that are to be executed should be given in a ‘ try block ‘. 5 . e r r or s a r e t o b e c h e c k e d m a n u a l l y u si n g e r r or c o d e s a n d e r r o r m e ssa g e s. a n ex c e p t i o n i s a R u n t i m e e r r o r ) . A thrown exception must be caught using ‘ catch block ‘. catch. } catch(ArrayIndexOutOfBoundsException ex) { System. // to display the 3rd element display(1). Value is : 10 SATEESH N . f i n al l y .println("Invalid array"). a n o b j e c t r e p r e se n t i n g t h a t e x c e p t i o n wi l l b e c r e a t e d a n d wi l l b e ‘ t h r o wn ‘ .Ex c e p t io n H an d l in g SATEESH N A n Ex c e p t i o n i s a n e r r o r t h a t o c c u r s i n t h e r u n t i m e of a p r o g r a m (i . t h ro w .out.println("Value is : "+arr[n]).out. 3 . Here's the general form of these statements: try { statement(s) } catch (exceptiontype name) { statement(s) } finally { statement(s) } E x a m p l e : TryCatch. e .30}. I n t h e p r o g r am m i n g l a n g u a g e wh i c h d o e s n o t s u p p o r t e x c e p t i o n h a n d l i n g . } } } 59 Out put: Value is : 30 Value is : 20 Invalid element no. display(5). Whenever an exception occurs an object representing that exception will created and will be thrown. display(0).out. try. . T h e r e a r e 5 k e y wo r d s : 1. th r o w s .println("Arithmetic Error"). public static void main(String args[]) { display(2). A n e x c e p t i o n m u st b e h a n d l e d u si n g t h e j av a ex c e p t i o n h a n d l i n g ke y wo r d s. Each catch can handle one type of exception.println("Invalid element no.out.

4 .g. IOExceptions are checked Exceptions. A r r a y I n d ex O u t O f B o u n d sE x c e p t i o n : T r yi n g t o a c c e ss a n e l e m e n t f r om a n a r r a y b e y on d t h e a r r a y si z e . While exceptions are conditions that occur because of bad input etc. 7 . W e g e n e r al l y t h r o w e x c e p t i o n s wh e n e v e r a c o n d i t i o n i s no t sa t i sf i e d et c . In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc. 5 . Cl a ssC a st E x c e p t i o n : I nv al i d t y p e c a st i n g . Such as OutOfMemory error. W e c a n t h r o w a p r e d e f i n e d ex c e p t i o n o r a n u se r d e f i n e d e x c e pt i o n . A rr a y S t o r e Ex c e p t i o n : I nv al i d a ssi g n m e n t t o a n el em e n t i n a a r r a y . By wrapping the desired code in a try block followed by a catch block to catch the exceptions. There are two ways to handle exceptions.SATEESH N Exceptions are of two types: Compiler-enforced exceptions. FileNotFoundException will be thrown if the specified file does not exist. and 2. e. e. l a n g p a c k a g e . 2 . Or a NullPointerException will take place if you try using a null reference. N ul l P o i n t e rEx c e p t i o n : I nv al i d u se o f NU L L r e f e r e n c e v ar i a bl e . Runtime exceptions. . N um b e r F o rm a t Ex c e p t i o n : I nv al i d c o n v e r si o n f r om st ri n g d a t a t o n um e ri c d a t a . These are not checked by the compiler at compile time. 6 . 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. 3 . List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions. L i s t o f p r e d e fi n ed E x c e p ti o n s : I n j av a a l l t h e e x c e p t i o n n am e s o r c l a s se s t h e f o l l o wi n g a r e t h e g e n e r a l e x c e p t i o n s t h a t a r e av ai l a b l e i n t h e j av a . Ex c e p t i o n : Ex c e p t i o n i s t h e su p e r c l a ss f o r al l t h e ex c e p t i o n s. or checked exceptions : Checked exception are those which the Java compiler forces you to catch. A ri t hm et i c Ex c e p t i o n : T hi s e x c e p t i o n o cc u r s w h e n e v e r a d iv i si o n b y 0 ( z e r o ) o c c u r s i n t h e p r og r a m . These JVM errors and you can not repair them at runtime.g. T h r o w i n g a n E x c e p ti o n : W e c a n a l so t h r o w s a n e x c e p t i o n u si n g t h e ‘ t h r o w ‘ k ey wo r d . 1 . 60 SATEESH N . T hi s c l a ss c a n b e u se d t o h a n d l e a l l t h e u n sp e c i f i e d ex c e p t i o n s i n t h e p r o g r am . 8 . 1. Difference between Error and Excepiton : An error is an irrecoverable condition occurring at runtime.). Cl a ssN o t F o u n d E x c e p t i o n : T h e sp e c i f i ed c l a ss i s n o t av ai l a b l e i n t h e r u n t i m e .

class TryThrowCatch { static void f1(int n) { if(n == 0) throw new ArithmeticException(). } catch(Exception ex) { 61 SATEESH N . else System.out. } public static void main(String args[]) { try Out put: { OK f1(2). OK f1(5). else if( n < 0 ) throw new NegativeArraySizeException(). else if( n < 0 ) throw new NegativeArraySizeException().out.java // T h i s p r o g r a m t h r o ws a p r e d e f i n e d ex c e p t i on a n d su c h e x c e p t i o n wi l l b e h a n d l e d in the m ain( ) . } } } i n s t a n c eo f k e y wo r d : t h e g i v e n o bj e c t .println("Arithmetic Error Occured").out. else System. } catch(NegativeArraySizeException ex) { System. } public static void main(String args[]) { try Out put: { f1(2). Arithmetic Error Occured } catch(ArithmeticException ex) { System.println("Invalid size for Array").out. OK f1(5). j a v a class instanceofKW { static void f1(int n) { if(n == 0) throw new ArithmeticException().println("OK"). T h i s o p e r a t o r i s u se d f o r i d e n t i f yi n g t h e t y p e of t h e cl a ss f o r E x a m p l e : i n s t a n c eo f K W .println("OK").SATEESH N E x a m p l e : TryThrowCatch. OK f1(0). Arithmetic Error Occured f1(0).

the exception should be thrown to the caller of this method instead of crashing the program. T h e ex c ep t i o n cl a ss e x t e n d s t h e t h r o wa b l e c l a ss. I f sp e c i f y t h a t ex c e p t i o n n am e u si n g Ex: a f u n c t i on i s s u p p o se d t o t h r o w a n e x c e p t i o n t h e b l o c k at t h e t i m e of c al l i n g i t a n d we sh o u l d h a n d l e d o e sn ’ t r e q u i r e d t o h a n d l e t h e e x c e p t i o n we c a n t h e t h r ow s k e y w o r d . } } } f i n a l l y bl o c k : T h e f i n al l y b l o ck c a n b e gi v e n i m m e di a t el y af t e r t h e t r y b l o c k o r af t e r a l l t h e c a t c h b l o c k s. 62 SATEESH N . separate the class names with commas.println("Invalid Array size"). Ex: try( ) { } f i n al l y( ) { } try( ) { } catch( ) { } catch( ) { } f i n al l y( ) { } t h r o w s k e y wo r d : W h e n ev e r f u n ct i o n sh o u l d b e p l a c e d i n a t r y t h e c o r r e sp o n d i n g E x c e p t i o n . c r e a t e a c l a ss t h a t ex t e n d s t h e ex c e p t i o n cl a ss. then the program will crash. ---cl a ss d i sp l a y { p u b l i c st a t i c v oi d m ai n ( St ri n g a r g s[ ] ) t h r o ws E x c e p t i o n ---} The throws Clause The throws “ ArrayIndexOutOfBoundsException “ clause in the method header tells the compiler that we know this exception may occur and if it does. The throws clause is placed after the parameter list and before the opening brace of the method. T h r o w i n g a n u s e r d e f i n e d e x c e p t i o n : T o c r e a t e a n u se r e x c e p t i o n . If more than one type of checked exception needs to be declared.println("Arithmetic Error Occured").out.out. T h r o wa b l e Exception U se r D e f i n e d Ex c e p t i o n A n i n st a n c e of t h e u se r e x c e p t i o n c a n b e t hr o wn u si n g t h e ‘ t h r o w ‘ k e y wo r d . else if(ex instanceof NegativeArraySizeException) System. then eventually the exception will propagate all the way back to the main method of the application. T h e f i n al l y b l o c k i s a l wa y s e x e c u t e d wh e t h e r o r n o t a n e x c e p t i on i s t h r o wn i n t h e p r o g r am .SATEESH N if(ex instanceof ArithmeticException) System. If an exception is always handled using the throws clause. If the main method throws the exception and the exception actually occurs while the program is running.

out. } catch(MyException1 ex) { System.toString() } } } 63 SATEESH N . class MyException1 extends Exception { String msg.println(ex). } } class MyException2 extends Exception { String msg. } public static void main(String args[]) { try Out put: { OK f1(3). OK f1(2).SATEESH N Example : UserDefException. // calls ex. } public String toString() { return msg.java / / I n t h e f ol l o wi n g p r o g r a m t h e f u n ct i o n f 1 ( ) t a k e s a n i n t e g e r a r g um e n t a n d t h r o w s e i t h e r m y ex c e p t i o n 1 o r m y ex c e p t i o n 2 d e p e nd i n g o n v a ri o u s c o n d i t i o n s. Second Exception Occured f1(-2).println("OK").toString() } catch(MyException2 ex) { System.out.MyException2 { if(n==0) throw new MyException1(). // calls ex. else if(n<0) throw new MyException2(). MyException1() { msg = "First Exception Occured".out. MyException2() { msg = "Second Exception Occured". } } class UserDefException { static void f1(int n) throws MyException1.println(ex). else System. } public String toString() { return msg.

S y st e m . o u t . s 1 wi l l c om p a r e wi t h s2 a n d r e t u r n s a v al u e f r om t h e f ol l o wi n g t a bl e . c h a r c h a r A t ( i nt i n d e x ) : R e t u r n s t h e c h a r ac t e r a t t h e sp e c i f i e d i n d ex . o u t . Ex: S t ri n g s1 = “ a b c ”. c h a r A t ( 3 ) ) . s1 wi l l b e c o m p a r e d wi t h s2 a n d r e t u r n s t r u e i f b o t h a r e e q u a l . ’ b ’ . String s2 ) : Com pares the st r i n g s wi t h o u t case f al se . arr st r a b c “abc” S t ri n g ( S t ri n g st r ) : C r e a t e s a st ri n g f r om a n o t h e r st r i n g .SATEESH N S t r in g Ha n d l in g String Class : T h e S t r i n g c l a ss i s u se d f o r m a n a g i n g st r i n g d a t a . o t h e r wi se f al se . S t ri n g s3 = s1 . Ex: S t ri n g st r = “T e st i n g ” . p ri n t l n ( st r . i f ( s1 = = s2 ) i f ( s1 = = s3 ) true i f ( s3 = = s1 ) i f ( s1 . S t ri n g t o U p p e r C a se ( ) : R e t u r n s t h e st r i n g t o t h e u p p e r c a se . h a sh c o d e s i n t c om p a r e T o ( S t r i n g s2 ) : I f c u r r e n t st r i n g i s s1 . e q u a l s( s2 )  t r u e i f ( s1 . b e c a u se = = o p e ra t o r c om p a r e s wi t h t h e r ef e r e n c e s i . e .  ‘ t ’ B o o l e a n e q u a l s( S t r i n g s2 ) : I f t h e c u r r e n t st r i n g i s s1 . p ri n t l n ( st r . S t ri n g ( c h a r a r r [ ] ) : C r e a t e s a st r i n g wi t h ch a r a c t e r s i n t h e gi v e n a r r a y. l e n g t h ( ) ). S t ri n g s2 = n e w S t ri n g ( “ a b c ” ) . e q u a l s( s3 ) )  t r u e i f ( s2 .  7 S y st e m . return value < 0 > 0 = 0 if s1 < s1 s1 > s2 s1 . Ex: c h a r a rr [ ] = { ‘ a ’ . e q u a l s( s2 ) = = t r u e c o m p a ri si o n d e p e n d i n g o n A S CI I v al u e s. e q u a l s( s3 ) )  t r u e b o o l e a n e q u a l sI g n o r e C a s e ( se n si t i v e n e ss. St r i n g st r = n e w S t r i n g ( a r r ). I t i s c o n t a i n i n g c o n st r u c t o r s a n d m e t h o d s t o d e a l wi t h t h e st r i n g d a t a. 64 SATEESH N . C o n s t r u c to r s : S t ri n g ( ) : C r e a t e s a st r i n g wi t h o u t a n y d a t a . Methods : i n t l e n g t h ( ) : R e t u r n s t h e l e n g t h of t h e st r i n g . ’ c ’ } .

} } /* When the input is "Hello" six Strings are constructed (including the first. e n d sW i t h ( “T e st ” ) ) Both are true. As the statement starts to execute. } public static void main ( String[] args ) { System. i f ( st .1 .out. S y st e m . empty String) because each time the following statement executes. S t ri n g t ri m ( ) : R em ov e s t h e l e a d i n g a n d t r ai l i n g sp a c e s. t o U p p e r C a se ( ) .  “abc xyz” b o o l e a n st a r t sW i t h ( St ri n g st ) : b o o l e a n e n d sW i t h ( S t ri n g st ) : Ex: C om p a r e s t h e b e g i n n i n g a n d e n d i n g p o r t i o n s of t h e S t ri n g . p ri n t l n ( st 1 ) . j >= 0. Ex: S t ri n g st 1 = “ H e l l o ” .println( reverse( "Hello" ) ). 65 SATEESH N .) rev += data. st a r t sW i t h ( “ T hi s” ) ) i f ( st . i n t i n d ex O f ( ) : Ex : public class ReverseTester { public static String reverse( String data ) { String rev = new String(). S t ri n g su b st r i n g ( i n t st a r t I n d e x . return rev.   H el l o HE L L O   N o c h a n g e i n so u r c e M o d i f i e d v al u e S t ri n g t o L o we r C a se ( ) : R e t u r n s t h e st ri n g t o t h e l o we r c a se .charAt(j). o u t .charAt(j). Ex: st 1 = “ abc xyz “. O n l y t h e r e t u rn v al u e c o t ai n s t h e m o d i f i e d d a t a .length()-1. St ri n g st = “T hi s i s t o t e st ” . o u t . S t ri n g st 2 = st 1 . st 2 = st 1 . The concatenation operator "+" creates a new String with one more character on the end. S y st e m . rev refers to a String. The new String reference is assigned to rev (the old String is now garbage).SATEESH N N o t e : I n a n y of t h e st r i n g f u n c t i o n s t h e so u r c e wi l l n o t b e m o d i f i e d. Ex t r a ct s a p o r t i o n o f t h e st r i n g f r om S t ri n g su b st r i n g ( i n t st a r t I n d ex ) : Ex t r a c t s f r om st a r t i n d ex t o e n d i n g of t h e st r i n g . i nt e n d I n d e x ) : st a r t i n d ex t o e n d i n d e x . a new String is created: rev += data. j-. for ( int j=data. t ri m ( ) . p ri n t l n ( st 2 ) .

SATEESH N

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

S t ri n g B uf f er : d by app en di n g a c h ar a r r ay, a e r m a ni pul at i on. C o n str u c to r s :

A S t ri ng B uf f er o b j e ct h ol ds a S t ri n g of c h ara c t e r s t h a t c a n b e c ha n g e c ha r ac t er s at t he end a n d by i nse r t i ng c har a c t er s. Ho wev er , unl i k e S t ri n gB uf f er c om e s wi t h m a ny m et h od s c o nv eni e nt f or c h a r a c t A St ri ng Buf f er aut om ati cal l y g r ows i n l eng t h as n e ed ed.

p u bl i c St ri n gBuf f er () p u bl i c St ri n gBuf f er (i nt c ap aci t y ):

:

c r e at e an em pt y St ri n gB uf f er c r e at e a St ri n gB uf f e r wi t h i ni t i al r oom f o r c ap aci t y c ha ra ct er s

p u bl i c St ri n gBuf f er (S tri ng st )

:

c r e at e a St ri n gB uf f e r c ont ai ni n g t he c h ar acte r s f rom st

U su al l y, i f p r og r am ex ec ut i o n sp e e d i s a c o nc er n, y o u sh o ul d dec l ar e a S t ri ngB uf f er t o be j ust som ewha t l ar ger t han y ou m i ght need . T hi s d oe sn ' t waste m uc h sp a c e a nd put s f e w d em a nd s o n t he r u n-t ime sy st em . A s wi t h a rr ay s, St ri n gB uf f er i nd ex es st art a t 0 an d g o u p t o l en gt h- 1. Som e S t ri n gBuf f er m et h od s ar e:

M e th o d s : S t ri n gBuf f er ap pe nd ( c ha r c ) : A p pe nd c t o t h e e nd of t h e St ri n gBuf f er

S t ri n gBuf f er ap pe nd ( i nt i ) : Co nv ert i t o c har ac t er s, t h en ap pe nd t hem t o t h e e n d of t h e St ri n gB uf f er , sam e f o r ot h er prim i t iv e d at a t y pe s. S t ri n gBuf f er ap pe nd ( St ri n g s ) : S t ri n g Buf f er. i nt ca paci t y () : A p pe nd t h e c h ar act er s i n s t o t h e e nd of t he

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

c h ar c har At ( i nt i nd ex ) : G et t he c ha r act er a t i nd ex . S t ri n gBuf f er i n se rt ( i nt i nd ex , c ha r c ) : I nse rt ch ar act er c at i n dex ( ol d c ha ra ct er s m ov e ov er t o m ak e r oom ). S t ri n gBuf f er i n se rt ( i nt i nd ex , St ri ng st ): I n sert c h ar act er s f r om st st art i ng at po si ti o n i . S t ri n gBuf f er i nse r t ( i nt i nd ex , i nt i ) : a t i nd ex , sam e f or ot her d at a t y p es i nt l e ngt h( ) : StringBuffer reverse() : Conv er t i t o c har ac t er s, t hen i nser t t hem st ar t i ng

R et u rn t h e n um b er of c har ac t er s. R ev erse t he or de r of t he c h ar act er s. S e t t h e c har ac t er at i n dex t o c.

v oi d se t C ha rAt ( i nt i nd ex , c h ar c ) : S t ri n g t o St ri ng () :

R et u rn a St ri n g o bj ect c ont ai ni n g t he c ha ra ct e r s i n t h e St ri n gBuf f er.
66 SATEESH N

SATEESH N

// In this version of reverse(), only two new objects are created: the StringBuffer and the String object that is returned to the caller. public class ReverseTester_St_Buf { public static String reverse( String data ) { StringBuffer temp = new StringBuffer(); for ( int j=data.length()-1; j >= 0; j-- ) temp.append( data.charAt(j) ); return temp.toString(); } public static void main ( String[] args ) { System.out.println( reverse( "Hello" ) ); } }

Data Conversions : public class DataTypeConverter { public static void main(String artgs[]) { // Converting int to string int my_int = 3; // approach 1 String my_str = Integer.toString(my_int); System.out.println("int to String (1): "+my_str); // approach 2 String my_str2 = ""+my_int; System.out.println("int to String (2): "+my_str2); // Converting string to int String str; str = "25"; // approach 1 int i =Integer.parseInt(str); System.out.println("String to int (1): // approach 2 i = Integer.valueOf(str).intValue(); System.out.println("String to int (2):

"+i); o u tp u t : "+i); int to int to String String String String String String (1): String (2): to int (1): to int (2): to long : to float : to double : 3 3 25 25 25 25.6 25.6

// Converting string to long long l = Long.valueOf(str).longValue(); System.out.println("String to long : "+l); // Converting string to float str = "25.6"; float f = Float.valueOf(str).floatValue(); System.out.println("String to float : "+f); // Converting string to double double d = Double.valueOf(str).doubleValue(); System.out.println("String to double : "+d); } }
67

SATEESH N

SATEESH N

IO Management
What is a a stream? Java programs perform I/O operations through streams. A stream is a sequence of data that flow from a source to destination. i.e., producing or consuming the information. A stream is linked to a physical device by the java I/O system. The physical device may be keyboard, memory, disk file, network socket or console.

Input to a java program : A java program can consume input from a key board, memory, a disk file or a network socket. To bring in information, a program opens a stream on an information source (a file, memory, a socket) and reads the information sequentially, as shown here:

Output from a java program : A java program can produce output on a console, memory, a disk file or a network socket. Similarly, a program can send information to an external destination by opening a stream to a destination and writing the information out sequentially, like this:

No matter where the data is coming from or going to and no matter what its type, the algorithms for sequentially reading and writing data are basically the same :

Reading

Writing

--> open a stream --> open a stream --> while more information --> while more information read information write information --> close the stream --> close the stream All of the streams--readers, writers, input streams, and output streams--are automatically opened when created. You can close any stream explicitly by calling its close method. Or the garbage collector can implicitly close it, which occurs when the object is no longer referenced.

68

SATEESH N

SATEESH N

There are two kinds of streams :

Byte Streams and Character Streams.

The java.io package contains a collection of stream classes ( InputStream and OutputStream classes, Reader and Writer classes ) that support these algorithms for reading and writing. To use these classes, a program needs to import the java.io package. Character Streams versus Byte Streams Prior to JDK 1.1, the input and output classes (mostly found in the java.io package) only supported 8bit 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 bytestream 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 ISOLatin-1 8-bit bytes).  They are easier to internationalize because they are not dependent upon a specific character encoding.  They use buffering techniques internally and are therefore potentially much more efficient than byte streams. Bridging the Gap Between Byte and Character Streams To bridge the gap between the byte and character stream classes, JDK 1.1 and JDK 1.2 provide the java.io.InputStreamReader and java.io.OutputStreamWriter classes. The only purpose of these classes is to convert byte data into character-based data according to a specified (or the platform default) encoding. For example, the static data member "in" in the "System" class is essentially a handle to the Standard Input (stdin) device. If you want to wrap this inside the java.io.BufferedReader class that works with character-streams, you use InputStreamReader class as follows: BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); character Streams : Reader and Writer are the abstract parent classes for character-stream based classes in the java.io package. As discussed above, Reader classes are used to read 16-bit character streams and Writer classes are used to write to 16-bit character streams. The following figure shows the class hierarchies for the Reader and Writer classes.

69

SATEESH N

These streams are typically used to read and write binary data such as images and sounds. programs should use the byte streams. are used for object serialization.SATEESH N byte Streams : To read and write 8-bit bytes. 70 SATEESH N . 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). Two of the byte stream classes. The following figure shows the class hierarchies for the InputStream and OutputStream classes. ObjectInputStream and ObjectOutputStream.

which can then be StringWriter converted to a String. File Concatenation SequenceInputStream N/A Concatenates multiple input streams into one input stream. ByteArrayOutputStream Memory Pipe Use StringReader to read characters from a String in memory. StringWriter collects the StringReader characters written to it in a StringBuffer. thereby reducing the number of accesses required on the original data source. These are the easiest streams to write to. these streams are used to read from or write to a file on the native file system. I/O Streams Type of I/O Streams Description CharArrayReader Use these streams to read from and write to memory. Buffer data while reading or writing. Peeking Ahead Printing Buffering Filtering 71 SATEESH N . Use StringWriter to write to a String. You create CharArrayWriter these streams on an existing array and then use the read and ByteArrayInputStream write methods to read from or write to the array.io contains character streams and byte streams that perform the same type of I/O but for different data types. PipedOutputStream FileReader FileWriter FileInputStream FileOutputStream N/A Collectively called file streams. Buffered streams are typically more efficient than similar nonbuffered streams and are often used with other streams. Contain convenient printing methods. java. StringBufferInputStream StringBufferInputStream is similar to StringReader. Counting LineNumberReader Keeps track of line numbers while reading. LineNumberInputStream PushbackReader PushbackInputStream PrintWriter PrintStream BufferedReader BufferedWriter BufferedInputStream BufferedOutputStream FilterReader FilterWriter FilterInputStream FilterOutputStream These input streams each have a pushback buffer. PipedReader Implement the input and output components of a pipe. except that it reads bytes from a StringBuffer. which filter data as it's being read or written. When reading data from a stream. Object Serialization ObjectInputStream ObjectOutputStream N/A DataInputStream DataOutputStream Used to serialize objects. so you will often see other writable streams wrapped in one of these. Note that many times. These abstract classes define the interface for filter streams.io's streams and describes what they do.SATEESH N Using the Streams The following table lists java. Data Conversion Read or write primitive data types in a machine-independent format. Pipes are PipedWriter used to channel the output from one thread into the input of PipedInputStream another. it is sometimes useful to peek at the next few bytes or characters in the stream to decide what to do next.

You can get the name of the default character encoding by calling System.. b o ol e a n d e l e t e ( ) : D el e t e s t h e f i l e o r d i r e ct o r y . it returns null. using the default character encoding or a character encoding specified by name. StreamTokenizer : A class used to parse the input streams called StreamTokenizer.*. used to parse the stream of input. boolean canRead( ) : Method asks if the file is readable. Note: the File class does not provide for I/O. Example : f i l el e n . j a v a / / t o f i n d t h e l e n g t h of t h e f i l e import java. An InputStreamReader reads bytes from an InputStream and converts them to characters.String child) : Methods : l o n g l e n g t h ( ) : R e t u r n s t h e l e n g t h of t h e f i l e. Rather it is often used in the arguments for the file I/O class methods. b o ol e a n i sF i l e ( ) : R e t u r n s t r u e i f t h e g i v en p a t h r e p r e se n t s a f i l e o t h e r wi se f al se . Otherwise.getProperty("file. You could use this method if you wanted to avoid overwriting the contents of an existing file when you create a new FileWriter. b o ol e a n i sD i r e ct o r y ( ) : R eturns true if the File object refers to a directory. C o n s t ru c t o r : F i l e ( S t ri n g p a t h n am e ) : The file instance can be created with a path name.io. Note that the StreamTokenizer class is NOT a subclass of InputStream.io. An OutputStreamWriter converts characters to bytes. this function returns an array of type String[] containing the names of the files in this directory.File class. b o ol e a n l i st ( ) : If the File object refers to a directory. i f i t e x i st s. I t r et u r n s 0 i f f i l e i s n o t av ai l a bl e .encoding"). b o ol e a n e x i st s( ) : R eturns true if the file named by the File object already exists. using the default character encoding or a character encoding specified by name and then writes those bytes to an OutputStream. class FileLength { public static void main(String args[]) { 72 SATEESH N . boolean setReadOnly( ) : Makes the file property to read only. It returns false if it refers to a regular file or if no file with the given name exists.SATEESH N Converting between Bytes and Characters InputStreamReader OutputStreamWriter A reader and writer pair that forms the bridge between byte streams and character streams. Allows separate specification of the path and the file name. File(String parent. StreamTokenizer is a utility class F i l e : Files and directories are accessed and manipulated through the java.

73 SATEESH N . This constructor is used.println("File not found.IOException.java". public class ByteArrayIOStreams { public static void main(String args[]) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(). None of the methods of this class throw an IOException because the data comes from an array instead of an actual I/O device.System.i<s.charAt(i)).out. for(int i=0.SATEESH N try { String fname = "d://sateesh_inputfile.out. though its size increases if necessary. This constructor is used. however.io. The position of the end of the stream depends on the constructor used. the end of the stream is the end of the byte ByteArrayInputStream(byte[] buffer.write(s. java. This class does not support the ability to mark a position in the stream. Constructors : public ByteArrayOutputStream( ) : Creates a new byte array output stream. System. java. give existing filename"). } catch(Exception ex) { if(ex instanceof FileNotFoundException) { System.io. } } Out put: d://sateesh_inputfile. The buffer automatically grows as data is written to it.lang. String s = "This is a test.println( fname +" file size: "+f. File f = new File(fname). A call to reset().length(). Example: import import import import ByteArrayIOStreams.ByteArrayInputStream. public ByteArrayOutputStream(int size) : Creates a new byte array output stream.java file size: 13662 } } ByteArrayInputStream : A ByteArrayInputStream is a stream whose data comes from a byte array. the end of the ByteArrayOutputStream : This class implements an output stream in which the data is written into a byte array.++i) outStream.java java. does position the stream at the beginning of the byte array.ByteArrayOutputStream.". Consturctors : ByteArrayInputStream(byte[] buffer) : array.io. int offset.length()). The buffer capacity is initially 32 bytes. java. int length): stream is reached at the index given by offset+length.

size()). java. 74 SATEESH N . the end of the stream is the end of the public CharArrayReader(char[] buf.System. This constructor is used. byte inBuf[] = new byte[inBytes].println(bytesRead + " bytes were read" ).CharArrayWriter. the end of the CharArrayWriter : The CharArrayWriter class represents a stream whose data is written to an internal character array. java. Example: CharArrayIOReadWrite. int bytesRead = inStream. int offset. inBytes).CharArrayReader. System. but it deals with a Java character stream rather than a byte stream. public CharArrayWriter(int initialSize) : This constructor creates a CharArrayWriter with an internal buffer that has a size of initialSize characters.toByteArray()). Consutrctors : public CharArrayReader(char[] buf) : character array. which ByteArrayInputStream does not. public class CharArrayIOReadWrite { public static void main(String args[]) throws IOException { CharArrayWriter out = new CharArrayWriter(). The buffer grows automatically as data is written to the stream.lang. System. The position of the end of the stream depends on the constructor used. int inBytes = inStream.io. 0.SATEESH N OutPut : System.println("inStream has " + inBytes + " available bytes"). size: 15 ByteArrayInputStream inStream = new ByteArrayInputStream(outStream. but it operates on an array of Java characters instead of a byte array.out.io. This constructor is used. outstream: This is a test.out. System. A copy of the array can be obtained using the toCharArray() method.println("outstream: " + outStream). System. Furthermore. inStream has 15 available bytes 15 bytes were read They are: This is a test. } } CharArrayReader : The CharArrayReader class represents a stream whose data comes from a character array. The buffer grows automatically as data is written to the stream. This class is similar to ByteArrayInputStream.println("They are: " + new String(inBuf)). int length) : stream is reached at the index given by offset+length. This class is similar to ByteArrayOutputStream.out.IOException. The data from a CharArrayWriter can be sent to another Writer using the writeTo( ) method.io.available().out. java.read(inBuf. Constructors: public CharArrayWriter( ) : This constructor creates a CharArrayWriter with an internal buffer that has a default size of 32 characters.println("size: " + outStream.out.java import import import import java. this class supports marking a position in the stream.

If the buffer is full.out. The buffer grows automatically as data is written to the stream.println("They are: "+s). suppose you create a parser that expects to read tokens from a stream. s = sb.size()). so changes made to the String affect the data that the StringReader returns. for(int i=0. System. ready( ) : If there is any data left to be read from the string. this method returns true. in = new CharArrayReader(out. or socket. This method writes the given value into the internal buffer. The buffer grows automatically as data is written to the stream.println("outstream: "+out).length()+" characters were read").".out. such as a file.println("size: "+out. Methods : public void write(int c) : expanded. while((ch = in.out. size: 15 15 characters were read They are: This is a test.toCharArray()). You can easily add one using StringReader. Methods : read( ) : This method returns the next character from the string. But you want to provide a method that also parses a big string.++i) out.i<s. StringReader : The StringReader class is useful when you want to read data in a String as if it were coming from a stream. it is 75 SATEESH N . The method cannot block. StringBuffer sb = new StringBuffer(""). pipe.write(s. such as a file or the console.charAt(i)). 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 data is not copied.toString(). System. StringWriter : The StringWriter class is useful if you want to capture the output of something that normally sends output to a stream. System.read()) != -1) sb.out. While using a StringBuffer is more efficient.println(s. For example. output : int ch=0. System. Constructors : public StringReader(String s) : This constructor creates a StringReader that uses the given String as its data source. Public StringWriter( int initialSize ) : This constructor creates a StringWriter with an internal buffer that has a size of initialSize characters. } } outstream: This is a test. CharArrayReader in. A PrintWriter wrapped around a StringWriter competes with StringBuffer as the easiest way to construct large strings piece by piece.SATEESH N String s = "This is a test.length().append((char) ch).

java.toString().java import import import import java. public StringBuffer getBuffer( ) : This method returns a reference to the StringBuffer object that is used in this StringWriter.out.++i) outStream. System.println("They are: "+s).length()+" characters were read").".io. Output : outstream: This is a test.StringWriter.write(s.println(s. They are: This is a test. Methods : i n t r e a d ( ) t h r o ws I O Ex c e p t i o n : R e a d s a c h a r a c t e r f r om t h e f i l e a n d r e t u r n s t h e A S C I I v al u e of t h a t c h a r a c t e r . I t r e t u r n s – 1 o r EO F .out.StringReader.out.io. StringBuffer sb = new StringBuffer("").println("size: "+outStream. 76 SATEESH N . System.length().charAt(i)).IOException. int ch=0.println("outstream: "+outStream). s = sb. Example : StringReadWrite.length()). v oi d cl o se ( ) t h r o ws I O Ex c e p t i o n : Cl o se s t h e o p e n e d f i l e. } } F i l eI n p u tS t r e a m : T hi s c l a ss i s u se d f o r o p e n i n g a f i l e i n t h e i n p u t m o d e a n d a l l o w s u s t o r e a d t h e c o n t e n t s of t h e f i l e . System. String s = "This is a test.toString()).SATEESH N public void write(String str) : This method copies the characters of str into this object's internal buffer. for(int i=0. If the internal buffer is full. I f t hi s f i l e c a n ’ t b e o p e n e d t h e F i l e N o t F o u n d Ex c e p t i o n wi l l be t h r o wn .out.lang.read()) != -1) sb.i<s. it is expanded. StringReader inStream = new StringReader(outStream.append((char) ch).System.io. size: 15 15 characters were read System. while((ch = inStream. C o n s t r u c to r : F i l e I n p u t St r e am ( St ri n g f i l e n a m e ) t h r o ws F i l e N o t F o u n d E x c e pt i o n : Opens the giv en f i l e i n t h e i n p u t m o d e . java. public class StringReadWrite { public static void main(String args[]) throws IOException { StringWriter outStream = new StringWriter().toString(). java.

fileinputstreamreader.*. F i l e O ut p u t S t r e am ( F i l e f i l e o b j e c t ) t h r o ws I O Ex c e p t i o n : This FileOutputStream that sends its output to the file represented by the specified File. C o n s t r u c to r : Opens a f ile i n t h e o u t p u t m o d e .j a v a / / T h i s p r o g r a m t a k e s a f i l e n a m e .io. } 77 // read remaining characters SATEESH N .close().print( (char) ch). while(ch != -1) // while(ch != EOF) { // Displaying on console System.SATEESH N F i l eO u t p u t S t r e a m : data into the file. void close( ) throws IOException : This method closes this file output stream and releases any resources used by it. ch = fin. class FileIP_OPStreams { public static void main(String args[]) { try { String in_fname = "d://sateesh_inputfile. fileoutputstreamreader. bufferedreader etc.out. } fin. // to read 1st character Out put: This sample file is created for testing io streams.txt". String out_fname = "d://sateesh_outputfile.read(). wh i c h a l l o ws u s t o wr i t e t h e F i l e O ut p u t S t r e am ( S t ri n g f i l e n am e ) t h r o ws I O E x c e pt i o n : This constructor FileOutputStream that sends its output to the file named by the specified String. import java. Methods: constructor creates a creates a 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. E x a m p l e : FileIP_OPStreams. o p e n s t h a t f i l e a n d d i sp l a y s t h e c o n t e n t s o f f i l e o n c o n so l e .println("File not found"). write( ) : Takes an ASCII value and writes the given character into the file. // Wrinting into output file fout.write(ch). fout..close(). FileOutputStream fout = new FileOutputStream(out_fname).read(). } catch(FileNotFoundException ex) { System. int ch = fin.txt". FileInputStream fin = new FileInputStream(in_fname).out.

wrap an InputStreamReader around a FileInputStream.) import java. the stream is positioned at the beginning of the file. 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. (For the host system this will correspond to one byte at a time.java The following CopyFile program uses FileReader and FileWriter to copy the contents of a file named sateesh_inpufile.io. FileWriter out = new FileWriter(outputFile). } } } FileReader : FileReader stream is used to read character data from text files. public class CopyFile { public static void main(String[] args) throws IOException { try { File inputFile = new File("D://sateesh_inputfile. int c.txt into a file called sateesh_outputfile. If you need to specify the character encoding or the buffer size. If append is true. Constructors : public FileWriter(String fileName) throws IOException: output to the file named by the specified String. the stream is positioned at the end of the file. If you need to specify the character encoding or the buffer size.*.txt ").println("Read/Write Error"). 78 SATEESH N .txt "). FileReader in = new FileReader(inputFile).SATEESH N catch(IOException ex) { System. public FileReader(File file) throws FileNotFoundException: This constructor creates a FileReader that gets its input from the file represented by the specified File. File outputFile = new File("D://sateesh_outputfile. and data is appended to the end of the file.txt : The read( ) method obtains one character at a time from the File. if append is false. FileWriter : FileWriter stream is used to write character data into text files. Otherwise. and any previous data is overwritten. Constructors : public FileReader(String fileName) throws FileNotFoundException This constructor creates a FileReader that gets its input from the file named by the specified String. Example : CopyFile. This constructor creates a FileWriter that sends its public FileWriter(String fileName. wrap an OutputStreamWriter around a FileOutputStream. 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.out. boolean append) throws IOException : This constructor creates a FileWriter that sends its output to the named file.

java.out. in. public class Concatenate_SeqIS_Ex1 { public static void main(String[] args) throws FileNotFoundException { String filelist[] = {"D://sateesh_file1. java.println("File not found"). int c. try { SequenceInputStream s = new SequenceInputStream(is1.out.txt)").write(c). while ((c = s. System.txt".read()) != -1) { System. InputStream is2 = new FileInputStream(filelist[1])."D://sateesh_file2. out.out.write(c). (D://sateesh_outputfile. java. } catch(FileNotFoundException ex) { System. Concatenate. } 79 SATEESH N .FileInputStream. SequenceInputStream(Enumeration e) : This constructor creates a SequenceInputStream that reads from each of the InputStream objects in the given Enumeration.SequenceInputStream.IOException.txt) } } S e q u en c e I n p u tS t r e a m : sources.is2).io.println("One file is copied.txt"}. java.close(). C o n s t r u c to r s : The SequenceInputStream creates a single input stream from multiple input SequenceInputStream(InputStream s1. InputStream s2) : This constructor creates a SequenceInputStream that reads first from s1 and then from s2.FileNotFoundException. E x a m p l e : Concatenate_SeqIS_Ex1. Each object in the Enumeration must be an InputStream.io. This example program.java import import import import import java. (D://sateesh_outputfile.close(). InputStream is1 = new FileInputStream(filelist[0]). uses SequenceInputStream to implement a concatenation utility that sequentially concatenates files together in the order they are listed. } s.close(). } Output : One file is copied.InputStream.SATEESH N while ((c = in.read()) != -1) out.io.io.io.

Vector vfilelist = new Vector().io.out.FileNotFoundException. java.Vector.println("Concatenate: " + e).io.add(is2). try { SequenceInputStream s = new SequenceInputStream(e).IOException. java."D://sateesh_file2.txt public class Concatenate_SeqIS_Ex2 { public static void main(String[] args) throws FileNotFoundException { String filelist[] = {"D://sateesh_file1. int c. the data stream classes are designed so that their objects can be chained to other streams.io.util.io.write(c).SATEESH N catch (IOException e) { System. java. However. and read or write some other non-byte value from/to a file? The answer is to use Java's DataInputStream and DataOutputStream classes. What do you do when you need to read integers. but you cannot directly chain a data input stream object to a FileReader object. bufferedreader etc. while ((c = s. } } } Data Stream Classes : A problem with the FileInputStream and FileOutputStream classes is that they only work at the byte level. For example. Output : File name: sateesh_fiel1.Enumeration. outputstreamreader. As with the buffered stream classes. floating-point.add(is1).err. Enumeration e = vfilelist.read()) != -1) System. java. s.err.close(). java. } } } E x a m p l e : Concatenate_SeqIS_Ex2.FileInputStream.elements()). Output : Same as above program red green blue yellow black 80 SATEESH N . inputstreamreader. you can only chain data stream objects to byte-oriented streams. File name: sateesh_fiel2.java import import import import import import import java. you can chain a data input stream to a FileInputStream object and call the data input stream's methods to read integer.txt".SequenceInputStream.InputStream. } catch (IOException ex) { System. vfilelist.util.elements().io. java. //SequenceInputStream s = new SequenceInputStream(vfilelist.txt This sample file is created for testing io streams. and other data items. InputStream is1 = new FileInputStream(filelist[0]). write floating-point values. vfilelist..txt"}.println("Concatenate: " + e). InputStream is2 = new FileInputStream(filelist[1]).

wr i t e B y t e (i n t v ). wr i t e B y t e s( S t ri n g s) . public class DataIOStreams { public static void main(String[] args)throws IOException { // write the data out 81 SATEESH N . wr i t e L o n g ( l o n g v ). This constructor creates a DataInputStream object that reads D a t a O u tp u t St r e a m : DataOutputStream allows you to write lines of text and Java primitive data types in a portable way.readLine( ) method. or a file.SATEESH N DataInputStream : portable way. This constructor creates a DataOutputStream that uses out Java also provides a corresponding DataInputStream. wr i t e C h a r s( S t r i n g s) . or wraps.io. a network connection. wr i t e F l o a t (f l o a t v ). Example: DataIOStreams. whether it be the user console. DataInputStream allows you to read lines of text and Java primitive data types in a Deprecated: This method does not properly convert bytes to characters. wr i t e I n t (i n t v ). As of JDK 1. C o n s tu r c t o r s : public DataOutputStream(OutputStream out) : as its underlying stream. This means you can write a data structure out to a disk or network connection.java import java. wr i t e D o u b l e ( d o u b l e v ) . wr i t e U T F ( St ri n g st r ) .*. 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). wr i t e C h a r ( i n t v ). DataOutputStream provides simple methods to write primitive data-types out to any output stream. which will allow you to read data back. st r i n g double float int long sh o r t st r i n g Method wr i t e B o o l e a n ( b o o l e a n v ) . Data Type boolean byte c h a r . the given input stream. and read it back at a later date. the preferred way to read lines of text is via the BufferedReader.1. wr i t e S h o r t ( i nt v ). with: BufferedReader d = new BufferedReader(new InputStreamReader(in)). C o n s t r u c to r : public DataInputStream(InputStream in) : from.

00 }. System. 50 }....SATEESH N DataOutputStream out = new DataOutputStream(new FileOutputStream ("D://invoice1. int deptno. 8600.. } } 82 SATEESH N EmployeeName Sateesh Ravi Kumar Srinivas Kishore Varma EmployeeName Sateesh Ravi Kumar Srinivas Kishore Varma . 12000.. System.out.writeDouble(sal[i]).println(). 7700. 12000..length. } } catch (EOFException e) { } in..out..0 12 System. System.0 8 out.append(chr).. String[] employees = { "Sateesh".out.. System...print(in.print(dept[i]).readInt().readChar()) != '\n') employee. "Srinivas". System. i ++) { Output : System. employee = new StringBuffer(20). i < employees. Salary DeptNo System.txt")).readDouble(). double[] sal = { 6000.writeChar('\n'). Reading..readChar()). System.out.00...out. 8...println(employee.toString()).out. // read it in again DataInputStream in = new DataInputStream(new FileInputStream ("D://invoice1. 6000..print(" ").out. for (int i = 0. int[] dept = { 12. 8000. Salary DeptNo out.0 12 out.print(in. 7700...print(employees[i])..out.print(salary)..out. "Varma" }.close(). StringBuffer employee.. "Ravi Kumar". // throws out the tab char chr. 13.out. System. while ((chr = in.println("Salary DeptNo EmployeeName").print(sal[i]).print(deptno).writeInt(dept[i]).out. 6000..").println("Salary DeptNo EmployeeName").0 50 out. double salary.0 29 out.txt"))..out...0 13 out. 8600. out.println("Reading. 8000.. try { while (true) { salary = in..0 13 } 8000. Writing.0 50 System. 29...00.print(" ").0..writeChar('\t')..readChar()).writeChars(employees[i]).println("Writing. double total = 0. 8600.out. 12000..writeChar('\t').out.. "Kishore"....0 29 System..00.. 7700.").out.0 8 System.close(). // throws out the tab deptno = in. System. System.

io. int sz) : This constructor creates a BufferedReader that buffers input from the given Reader. This class is used to bridge the gap between a Reader. to an InputStreamReader which is connected to an InputStream called 'in'. t he I n p u t S t r e am R e a d e r c o nv e r t s t h e d a t a f r om t h e b y t e st r e a m s t o c h a r a c t e r st r e a m s.*. Methods : S t ri n g r e a d L i n e ( ) t h r o ws I O Ex c e p t i o n : R e a d s a l i n e ( S t r i n g ) f r om gi v e n i n p u t st r e a m or null if the end of the stream has been reached. class ISR_BR_ReadLineNos { public static void main(String args[]) { 83 SATEESH N . and an InputStream. i . public BufferedReader(Reader in. // Connect a BufferedReader. BufferedReader : t h e st r i n g f o rm a t .j a v a / / t o a c c e p t a f i l e n a m e a s c o m m a n d l i n e a r g u m e n t a n d t o d i sp l a y t h e c o n t e n t s o f f i l e a l o n g wi t h t h e l i n e n o ’ s. .even filtered input streams such as DataInputStream. C o n s t r u c to r s : public InputStreamReader(InputStream in) : This constructor creates an InputStreamReader that gets its data from in and translates bytes to characters using the system's default encoding scheme.SATEESH N Reading lines from the file : f ol l o wi n g 2 cl a sse s a r e u se d . r e a d s t h e d a t a f ro m t h e g i v e n i n p u t st r e a m i n t h e b y t e f o rm a t a n d c o nv er t s i n t o t h e c h a r a c t e r f o rm a t . import java. B uf f e r e d R e a d e r . 1 . b u f f e r s t h e c h a r a c t e r s a n d c o n v e r t s t h em i n t o 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. Constructors : I n o r d e r t o r e a d l i n e f r om a n y i n p u t st r e a m t h e 2 . public InputStreamReader(InputStream in. I n p u t St r e a m R e a d e r : T h e I n p u r S t r e am R e a d e r . You can do the same with an OutputStream to a Writer (OutputStreamWriter). BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ). InputStreamReader is a reader that can be connected to any InputStream . 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. using a buffer of the given size. T h e B uf f er e d R e a d e r . e . or BufferedInputStream. / / f i l e n a m e : ISR_BR_ReadLineNos. Here's an example that shows InputStreamReader in action. I n p u t S t r e am R e a d e r .

SATEESH N try { String fname = "D://sateesh_inputfile. BufferedReader etc.println(n+": "+str). read( ) : This method is used to read single character. A line is considered to be terminated by any one of a line feed ('\n'). InputStreamReader. int n = 0. reading characters into a buffer Out put: 1: 2: 3: 4: 5: 6: 7: This sample file is created for testing i/o streams. You can specify the size of the buffer used by BufferedInputStream when it is created or accept the default of 2048 bytes.readLine(). 84 SATEESH N . It then intercepts your calls to the read methods and attempts to satisfy your request with data in its buffer. str = br. // BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fname))). or cache. skip( ) : This method is used to skip number of characters. Methods : setLineNumber( ) : This method enable you to set the internal line number count maintained by LineNumberInputStream. FileInputStream fin = new FileInputStream(fname). } br. while( str != null) { n++. or a carriage return followed immediately by a linefeed. int) : of the given size. } catch(Exception ex) { System. especially those bound to slower sources like a file or network connection.readLine( ). Consturctors : LineNumberReader Reader) : Create a new line-numbering reader.. LineNumberReader (Reader. readLine( ) : This method is used to read a line of text. If the data in the buffer is not sufficient. "+ex). a carriage return ('\r'). Create a new line-numbering reader.close(). //this statement can be used instead of above 3 lines String str = br. BufferedReader br = new BufferedReader(isr). to the stream.txt". getLineNumber( ) : This method enable you to get the internal line number count maintained by LineNumberInputStream. OutputStreamReader.out. System.out. InputStreamReader isr = new InputStreamReader(fin).println("Error: } } } BufferedInputStream : The BufferedInputStream's contribution to its attached stream is the addition of a buffer. LineNumberReader : A buffered character-input stream that keeps track of line numbers. using the default input-buffer size. a read to the next input stream in the chain is done to fill the buffer and return the data requested. This has the effect of improving the performance of some input streams.

IOException. java.txt"). public class LineNumberReader_Ex1 { public static void main(String args[]) throws IOException { FileReader inFile = new FileReader("D://sateesh_inputfile.out. } 85 SATEESH N Out put : Enter 5 strings: Red Green Blue Yellow Black Black Yellow Blue Green Red .io.. 3. // BufferedReader stdin = new BufferedReader(new InputStreamReader(System.println().SATEESH N Example : import import import import import LineNumberReader_Ex1.i++) arr[i] = stdin.io.lang. for(i=0.System. java. fileinputstreamreader.println(inLines.FileReader. int i. BufferedReader stdin = new BufferedReader(isr). 4.i--) System. bufferedreader etc.io. This file is created for testing io streams. for(i=4. System.io. String inputLine. } } } R e a d i n g l i n e s f r o m t h e k e y b o a r d : T o r e a d l i n e s f r om t h e k e y b o a r d t h e sy st e m . java. 2. java. java. while ((inputLine=inLines.readLine()) != null) { System.out.out.i>=0.in)). fileoutputstreamreader.LineNumberReader. LineNumberReader inLines = new LineNumberReader(inFile). 5. 6.in).getLineNumber()+". 7.out.java Output : 1. import java. i n sh o u l d b e a t t a t c h e d t o t h e B uf f e r e d R e a d e r .BufferedWriter. Example : // ISR_BR_ReadLines.println("Enter 5 strings:\n").println(arr[i]). System. j a v a t o a c c e p t 5 l i n e s f r om t h e k e y b o a r d a n d d i sp l a y t h em i n t h e r ev e r se o r d e r . class ISR_BR_ReadLines { public static void main(String args[]) { try { InputStreamReader isr = new InputStreamReader(System.i<5.io. String arr[] = new String[5]. "+inputLine).readLine().*.

This behavior is different from that of a PrintStream object.in) ). void println(String str) throws IOException : This method writes "true" to the underlying output stream if b is true. class PrintWriter_KB { public static void main(String args[]) { try { //key board BufferedReader stdin = new BufferedReader(new InputStreamReader (System.java / / t o a c c e p t 5 l i n e s f r om t h e k e y b o a r d a n d sa v e t h em i n t h e f i l e sa t e e sh _ o u t p u t f i l e . The constructor creates the intermediate OutputStreamWriter that converts characters to bytes using the default character encoding. otherwise it writes "false". boolean autoFlush) : This constructor creates a PrintWriter object that sends output to the given OutputStream. for separating lines of text. the method writes "null". Example : PrintWriter_KB. Methods: void print(String str) throws IOException : This method writes the given String to the underlying output stream. If String is null. If autoFlush is true. 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. If necessary. void write(String str) throws IOException : This method writes the given String to the underlying output stream.getProperty("line. every time a println( ) method is called.separator") Constructors : public PrintWriter(OutputStream out) : This constructor creates a PrintWriter object that sends output to the given OutputStream. rather than the newline character. which calls its flush() method each time a line separator or newline character is written.txt")). the method blocks until the String is written.*. 0. //output PrintWriter out = new PrintWriter(new FileOutputStream("D://sateesh.io. This line separator is equivalent to the value returned by: System. PrintWriter uses the system's default encoding scheme to convert characters to bytes. the string is followed by a line separator. the PrintWriter object calls its flush( ) method.println("Error: } } } "+ex). t x t (f i l e n am e ).length) for the underlying output stream and catching any exceptions that are thrown. import java. public PrintWriter(OutputStream out.out. s. The constructor creates the intermediate OutputStreamWriter that converts characters to bytes using the default character encoding. The method does this by calling write(s.SATEESH N catch(Exception ex) { System. In either case. 86 SATEESH N . PrintWriter also uses the system's own specific line separator.

} //write into out.txt Enter target file name: D://sammm. // open the target file in output mode PrintWriter out = new PrintWriter(new FileOutputStream(targetfname)).print ("Enter source file name: "). // open the 1st file in input mode BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(sourcefname))).e.println("File Created. out. // start reading from source and copy each line to the targer String str = in.readLine(). // write into targer str = in.out. System. system. } } } Example: Co p y F i l e _ P W .close().readLine().out.print("Enter target file name: ").readLine(). System.close().println(str). j a v a / / t o c o p y d a t a f r om t h e 1 st f i l e t o 2 n d f i l e import java.readLine().println("error:"+ex).readLine().i<=5. } catch(Exception ex) { System.out // keyboard BufferedReader stdin = new BufferedReader(new InputStreamReader(System.txt Copied SATEESH N .out.io. String targetfname = stdin. out. i.out.").i++) { System.close(). class CopyFile_PW { public static void main(String args[]) { try { // console i.in)). String sourcefname = stdin.close(). into file Enter: red Enter: green Enter: blue Enter: yellow Enter: black File Created. stdin.*.out.e... // reading filename System. 87 Output : Enter source file name: D://sateesh_inputfile. } in.println(str). // from the source file while(str!=null) { out. //read from key board Output : String str = stdin.SATEESH N for(int i=1. out.print("Enter: ").

err objects are FileOutputStreams that use a PrintStream filter. each of the println() methods also append a newline to each object written. those streams have limited sizes.SATEESH N System. the thread can hang. Java supplies the PipedInputStream. This filter adds the capability to force the attached stream to be flushed every time a newline (\n) character is written. (Those classes are located in the java. A technique that is often used by threads wishing to communicate involves piped streams. PipedReader / PipedWriter : The PipedReader / PipedWriter class represents half of a communication pipe. a writing thread could write more output to a piped output stream than that stream can accommodate. one thread writes data to the piped output stream and another thread reads that data by way of the piped input stream. Piped Stream Classes Threads are often required to communicate. The communication pipe formed by a PipedReader and a PipedWriter should be used to communicate between threads.) CAUTION Deadlock might occur if a single thread uses a piped output stream connected to a piped input stream. an exception is thrown. PipedOutputStream. and performs both writing and reading operations on that stream. public int read( ) throws IOException : Reads the next character of data from this piped stream. Although there are no synchronization problems with piped streams. The System.out and System.out. PrintStream : We have actually been using the PrintStream filter in many programs. To prevent that from happening.out. If both ends of a pipe are used by the same thread. and the excess output would be lost. The idea behind piped streams is to connect a piped output stream to a piped input stream.println("Copied"). PipedReader. This constructor creates a PipedReader that 88 SATEESH N . It also provides several overloaded versions of print() and println() that write each of the primitive data types to the attached stream as strings. To support piped streams. and PipedWriter classes in its standard class library.println("Error: } } } "+ex). Methods : public void connect(PipedWriter src) throws IOException : This method connects the given PipedWriter to this PipedReader object. data written to the PipedWriter can be read from the PipedReader.io package. the reading thread must be responsive. As a result. a PipedReader must be connected to a PipedWriter. Then. When the two halves of a communication pipe are connected. PipedReader : Constructors : public PipedReader(PipedWriter src) throws IOException : receives data from the given PipedWriter. In addition. } catch(Exception ex) { System. If there is already a connected PipedWriter.

// src writes pw.pw = pw. i < 15. this. PipedReader pr.io. class MyThread extends Thread { private PipedReader pr. Methods : public void connect(PipedReader sink) throws IOException : This method connects this PipedWriter object to the given PipedReader. MyThread (String name.write ("src " + " A" + i + "\n").pr = pr. pr.close (). an exception is thrown. PipedWriter pw) { super (name).read ()) != -1) System.java import java.*. } } catch (IOException e) { } } } class PipedThreads { public static void main (String [] args) throws IOException { 89 SATEESH N This constructor creates a PipedWriter that sends data to the Writes the specified char to the piped output stream. // dst reads .close ().equals ("src")) { for (int i = 0.SATEESH N PipedWriter : Constructors : public PipedWriter(PipedReader sink) : given PipedReader.print ((char) item). public void write(int c) throws IOException : Example: PipedThreads. } public void run () { try { if (getName (). while ((item = pr. i++) pw.out. } else { int item. this. private PipedWriter pw. If this PipedWriter or sink is already connected.

SATEESH N PipedWriter pw = new PipedWriter (). the default is one character. mt1. pw). int size) : This constructor creates a PushbackReader that reads from the given Reader. pr. using a pushback buffer with the default size of one byte. pw).start (). This functionality is useful for implementing things like parsers that need to read data and then return it to the input stream. } catch (InterruptedException e) { } mt2. try { Thread. The FilterInputStream is attached to an input stream by passing the input stream to the filter stream's constructor. it can be pushed back into the stream so that it can be reread. after data has been read from a PushbackReader. you can specify the number of characters that you are allowed to push back. This class does not make any modifications to the attached stream. Methods : public void unread(int c) throws IOException : buffer. PipedReader pr = new PipedReader (pw). public PushbackReader(Reader in.start (). using a pushback buffer of the given size. MyThread mt2 = new MyThread ("dst". Constructors : public PushbackReader(Reader in) : This constructor creates a PushbackReader that reads from the given Reader. In other words. ObjectInputStream : ObjectOutputStream : This method puts the given character into the pushback 90 SATEESH N . When you create a PushbackReader object. FilterReader : FilterWriter : PushbackReader : The PushbackReader class represents a character stream that allows data to be pushed back into the stream.sleep (2000). MyThread mt1 = new MyThread ("src". } } Output : src src src src src src src src src src src src src src src A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 Filter Streams FilterInputStream is the base class for all the input stream filters. pr. but merely provides the chaining functionality that will be exploited by its subclasses. PushbackReader is the character-oriented equivalent of PushbackInputStream.

from the beginning of the file where the next read or write operation occurs. the end of the file is encountered. so it supports reading and writing of all the primitive data types. Methods : getFilePointer( ) : This method returns the current position in the file. 123456 file. in bytes.RandomAccessFile. the seek() method allows you to alter the current position of the file pointer to any location in the file. true System. file.close(). readBoolean( ) : This method reads a byte as a boolean value from the file. The method blocks until the byte is read. import java.out. RandomAccessFile implements both the DataInput and DataOutput interfaces. Both constructors take a mode parameter that specifies whether the file is being opened solely for reading.writeDouble(1234.readDouble()). String mode) : This constructor creates a RandomAccessFile to access the file with the specified name in the specified mode.writeInt(123456).readInt()).writeBoolean(true).readChar()). so it supports reading and writing of all the primitive data types. String mode) : This constructor creates a RandomAccessFile to access the specified File in the specified mode. Unlike FileInputStream and FileOutputStream.out. the end of the file is encountered.out. file.io. 1234.java import java.56 System.IOException. Example : RandomAccessFile_Ex1. A byte that contains any other value is read as true. public RandomAccessFile(String name. public final void writeBoolean(boolean v): If v is true."rw"). public class RandomAccessFile_Ex1 { public static void main(String args[]) throws IOException { RandomAccessFile file = new RandomAccessFile("D://sateesh_inputfile. seek( ) : This method sets the current file position to the specified position.lang.io. } } 91 SATEESH N . A byte that contains a zero is read as false. file. The file is specified using a File object or a String that represents a pathname. RandomAccessFile supports random access to the data in the file. or for reading and writing. or an exception is thrown.System.56). Output : file. write( ) : This method writes the low-order eight bits of b to the file as a byte . The position is the offset. Each of the constructors can throw a SecurityException if the application does not have permission to access the specified file using the given mode.println(file.seek(0).SATEESH N RandomAccessFiles : The RandomAccessFile class reads data from and writes data to a file.readBoolean()).out. If v is false. Constructors : public RandomAccessFile(File file. The position is the offset.writeChar('j').println(file. System. The method blocks until the byte is read. RandomAccessFile implements both the DataInput and DataOutput interfaces. in bytes.seek(1). file. the method writes a byte that contains the value 0. this method writes a byte that contains the value 1 to the file.println(file. j file. or an exception is thrown.txt". System. import java.println(file. from the beginning of the file where the next read or write operation occurs. read( ) : This method reads the next byte from the file.

and '-' String quote characters "'" and "'" Comment character "/" Constructors : public StreamTokenizer(Reader in) : Reader. public int nextToken() throws IOException : This method reads the next token from the stream. use ordinaryChar('/'). after a call to this method. numeric. the next call to the nextToken() method returns the same result as the previous call to the nextToken()method without reading any input. '6'. and '\u00A0' and '\u00FF'. The variable ttype is set to the character value. This constructor creates a StreamTokenizer that reads from the given TT_NUMBER TT_WORD Quoted string A quoted string has been parsed. and sval contains the string itself. In other words.SATEESH N StreamTokenizer : The StreamTokenizer class performs a lexical analysis on an InputStream object and breaks the stream into tokens. or whitespace character. '7'. '3'. '4'. This method may be called multiple times if there are multiple characters that begin comment lines. The value can be found in the variable nval. 'A' through 'Z'.'. string quote. A word has been parsed. use ordinaryChar(). alphabetic. The end of a line has been reached. '0'. Although StreamTokenizer is not a general-purpose parser. '2'. The eolIsSignificant() method controls whether endof-line characters are treated as whitespace or returned as TT_EOL tokens. For example. quoted strings. By default. public void ordinaryChar(int ch) : This method causes this StreamTokenizer to treat the given character as an ordinary character. A number has been parsed. a StreamTokenizer treats the '/' character as a comment character. numbers. '. The word can be found in the variable sval. A StreamTokenizer recognizes identifiers. To specify that a character is not a comment character. 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. Numeric characters '1'. The parseNumbers() method tells the StreamTokenizer to recognize numbers distinct from words. and various comment styles. public void pushBack( ) : This method has the effect of pushing the current token back onto the stream. The variable ttype is set to the quote character. 92 SATEESH N . to tell the StreamTokenizer that the slash does not start a single-line comment. This means that the character has no special significance as a comment. a StreamTokenizer recognizes the following: Whitespace characters between '\u0000' and '\u0020' Alphabetic characters from 'a' through 'z'. '9'. '8'. Character A single character has been parsed. it recognizes tokens that are similar to those used in the Java language. The nextToken() method parses the following tokens: TT_EOF TT_EOL The end of the input stream has been reached. By default. The value returned is the same as the value of the variable ttype. The StreamTokenizer ignores all of the characters from the comment character to the end of the line. '5'. You can tell the StreamTokenizer what characters to use as quote characters using quoteChar( ).

System. case StreamTokenizer.commentChar('#').out.encountered. default: System.").io. // Parse according to input token switch(token) { case StreamTokenizer. Number: 1979. To specify that a character is not a string-quote character.println("EOL encountered.TT_WORD: System. However.nextToken().println("EOF encountered. or. do { int token=inStream.TT_EOF: System.out.out.out. break. public void slashStarComments(boolean flag) : By default. or the end of the stream.encountered. if(token=='!') eof=true.io. Example: import import import import import java. in other words.0 Word: Year .encountered. and sval is set to the actual string. break. 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. if you call slashSlashComments(true).0 Word: Month .TT_EOL: System. int hi) : This method causes this StreamTokenizer to treat characters in the specified range as characters that are part of a word token. the single-quote character and the double-quote character are string-quote characters. 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. the nextToken() method recognizes and ignores double-slash comments. java.in)). if you call slashStarComments(true). java. Number: 10.0 EOF encountered.out. the ttype variable is set to the quote character."). public void quoteChar(int ch) : This method tells this StreamTokenizer to treat the given character as the beginning or end of a quoted string.SATEESH N public void slashSlashComments(boolean flag) : By default.println((char) token+" encountered. By default. consider the characters to be alphabetic. public void wordChars(int low.StreamTokenizer. a StreamTokenizer does not recognize slash-star comments.io. } } while(!eof). a line terminator. Number: 3. However.InputStreamReader.nval).println("Word: "+inStream.sval).BufferedReader.TT_NUMBER:System. java. StreamTokenizer inStream = new StreamTokenizer(inData). case StreamTokenizer. public class StreamTokenizer_Ex1 { public static void main(String args[]) throws IOException { BufferedReader inData = new BufferedReader(new InputStreamReader(System.lang. break. eof = true. java. When the parser encounters a string-quote character.").println("Number: "+inStream. boolean eof = false. the nextToken() method recognizes and ignores slash-star comments. break.io. case StreamTokenizer. Output : Word: DOB : encountered.IOException. } } 93 SATEESH N . a StreamTokenizer does not recognize double-slash comments. inStream. use ordinaryChar(). Word: Date .

By using those classes. l a n g . } c a t c h ( N um b e rF o rm a t Ex c e p t i o n ex ) { S y st em . j a v a / / t o a cc e p t 2 n um b e r s f r om t h e k e y b o a r d a n d d i sp l a y t h e t o t al . In t e g e r c la ss : p u b l i c st a t i c i n t p a r se I n t ( S t r i n g st r ) t h r o w s N u m b e r F o rm at Ex c e pt i o n T h e p a r se I n t f u n c t i o n av ai l a b l e i n t h e i nt e g e r c l a ss t a k e s a st r i n g a n d c o n v e rt s i n t o t h e n um e r i c f o rm a t . i m p o r t j av a. b. S y st em . o u t . st r = st d i n . p r i nt l n ( " C o nv e r si o n f i n al " ). b = I nt e g e r . S y st em . p a r se I n t ( st r ) . o u t . st r = st d i n . o u t . p a r se I n t ( st r ) .SATEESH N Zip Stream Classes Did you know that Java makes it easy to read and write Zip files? Zip support manifests itself in the standard class library by way of the ZipInputStream and ZipOutputStream filter stream classes. o u t . p r i nt l n ( "T o t al i s : "+ c ). } c a t c h (I O Ex c e p t i o n ex ) { S y st em . S t ri n g st r . } } } 94 SATEESH N Out put: E:\Core>javac inteclas. p r i nt l n ( "E n t e r a n um b e r : ") . i m p o r t j av a. r e a d L i n e ( st r ). c l a ss i n t e c l a s { p u b l i c st a t i c v o i d m ai n ( S t ri n g a r g s[ ] ) { try { // key board B uf f e r e d R e a d e r st d i n = n e w B uf f e r e d Re a d e r ( n e w I n p u t S t r e a m R e a d e r ( S y st em . c = a + b. o u t . *. p r i nt l n ( "E n t e r a n o t h e r : " ) . p r i nt l n ( "E r r o r : "+ ex ). i nt a . r e a d L i n e ( st r ). * . i n ) ). a = I nt e g e r . it is possible to create a command-line version of the popular WinZip utility. and other classes that (along with ZipInputStream and ZipOutputStream) are part of the java. / / f i l e n am e : i n t e cl a s . c .java E:\Core>java inteclas Enter a number : 10 Enter another : 20 Total is : 30 E:\Core> .zip package. S y st em . i o.util.

v oi d se t P ri o r i t y (i n t p ri o ri t y) : C h a n g e s t h e p r i o r i t y of t h e T h r e a d . u si n g t h e T h r e a d cl a ss i i . st a t i c T h r e a d c u r r e n t T h r e a d ( ) : R e t u r n s t h e c u r r e n t t h r e a d . T h r e a d ( ) : c r e a t e s a t h r e a d wi t h a d ef a ul t n a m e . : Makes the thread Makes the current thread to wait until the v oi d i n t e r r u p t ( ) : I n t e r r u p t s a sl e e p i n g t h r e a d . p ri o r i t y i s: 2 d ef a u l t i s : 5 i n t g et P ri o r i t y ( ) : R e t u r n s t h e c u r r e n t p ri o ri t y of t h e t h r e a d . t h r e a d s t h a t a r e c r e a t e d ei t h e r b y t h e T h r e a d cl a ss o r wi t h h e l p of R u n n a b l e i n t e rf a c e c a n o n l y b e c o n t r ol l e d by t h e T h r e a d c l a ss. U si n g R u nn a b l e i nt e rf a c e i . i . st a t i c v oi d sl e e p ( l o n g m i l l i se c o n d s ) t h r o w s I n t e r r u p t e d E x c e p t i o n : t o sl e e p f o r t h e sp e c i f i e d t i m e. v oi d se t N a m e (S t ri n g n e wN a m e ) : c h a n g e s t h e n a m e of t h e T h r e a d . M a i n T h r e a d : W h e n ev er we r u n a j av a p r o g r a m t h e p r o g r a m wi l l b e p l a c e d i n a n a l r e a d y r u n n i n g t h r e a d wh i c h i s k n o wn a s m ai n T h r e a d . i . . 95 SATEESH N . t h e t h r e a d wi l l b e a d d e d t o t h e t h r e a d Q u e u e S t ri n g g e t N am e ( ) : R e t u r n s t h e n am e of t he t h r e a d . . e . Al l t h r e a d s t h a t a r e c r e a t e d i n t h e p r o g r a m wi l l b e t h e c h i l d t h r e a d s o f t h e m ai n T h r e a d . W h e n ev e r t h e m ai n T h r e a d st o p s t h e p r o g r a m wi l l b e t e rm i n a t e d . i t su p p o r t s m u l t i t h r e a d e d p r o g r a m s. T h r e a d ( R u n n a b l e r .SATEESH N M U L T I T H R E AD I N G : O n e of t h e m ai n a dv a n t a g e i n j av a p r o g ra m m i n g i s. I n t h e f ol l o wi n g e x am pl e a r e f e r e n c e of t he m ai n T h r e a d wi l l b e o b t a i n e d u si n g the current Thread f uncti on. E a c h T h r e a d c o n t ai n s n a m e . C o n st r u c t o r s: T h r e a d ( S t ri n g n am e ) : cr e a t e s a t h r e a d wi t h sp e c i f i e d n am e. i . b o o l e a n i n l i v e ( ) : R e t u r n s t r u e i f t h e T h r e ad i s st i l l r u n n i n g . T h r e a d c l a ss : T h r e a d c l a s s i s t h e m a i n c l a s s t o m a n a g e a l l t h e t h r e a d s i n a j av a p r o g r a m . A m u l t i t h r e a d e d p r o g r a m i s p r o g r a m t h a t c o n t a i n s 2 o r m o r e p a rt s t h a t r u n s c o n c u r r e n t l y. Thread(Runnable r) : M e t h o d s: v oi d st a r t ( ) : st a r t s t h e T h r e a d . Mi n. E a c h p a rt of a p r o g r am i s c a l l e d a t h r e a d . v oi d j oi n ( ) t h r o w s I n t e r r u p t e d E x c e p t i o n sp e c i f i e d t h r e a d f i ni sh e s. e . S t ri n g n am e ) : C r e a t e s a t h r e a d u si n g t h e r u n n a b l e i n t e rf a c e . T h r e ad g r o u p e t c . p ri o r i t y i s: 1 M a x . . Creating a Thread : I n j av a a t h r e a d c a n be c r e a t e d i n 2 wa y s. p ri o r i t y . o t h e r wi se f al se . M u l t i t h r e a di n g e n a b l e s u s t o r u n m u l t i p l e pa r t s o f t h e p r o g r am at t h e sa m e t i m e .

r. " ). } } / / f i l e n am e : th r e a d 2 .SATEESH N Ex: v oi d m ai n ( ) { T h r e a d r = T h r e a d . . i < = 1 0 . sl e e p ( 2 0 0 0 ) . } c a t c h ( I n t e r r u p t e d Ex c e p t i o n ex ) { S y st em . . } } 96 Out put: / / m ai n T h r e a d E:\Core>javac thread. } } S y st em . p ri n t l n ( " C o u n t i s: "+ i ) ... . . try { r. o u t . o u t . . i < = 1 0 . j a v a / / sam e a s a b ov e p r o g r am c l a ss t h r e a d 2 { p u b l i c st a t i c v o i d m ai n ( S t ri n g a r g s[ ] ) { f or ( i nt i = 0. " ). o u t . / / M a i n T h re a d } c a t c h ( I n t e r r u p t e d Ex c e p t i o n ex ) { S y st em . o u t . E:\Core> SATEESH N . sl e e p ( 1 0 0 0 ) .java / / f i l e n am e : / / T h e f ol l o wi n g p r o g r a m p ri n t s t h e v al u es f r om 1 t o 1 0 .-. p ri n t l n ( " F i ni sh e d . .java E:\Core>java thread2 Count is : 0 Count is : 1 Count is : 2 Count is : 3 Count is : 4 Count is : 5 Count is : 6 Count is : 7 Count is : 8 Count is : 9 Count is : 10 Finished .. . } } S y st em . p ri n t l n ( " M ai n T h r e a d I n t er r u p t e d " ) . try { T h r e a d .currentThread(). p ri n t l n ( " C o u n t i s: "+ i ) .java E:\Core>java thread Count is : 0 Count is : 1 Count is : 2 Count is : 3 Count is : 4 Count is : 5 Count is : 6 Count is : 7 Count is : 8 Count is : 9 Count is : 10 Finished . c u r r e nt T h r e a d ( ). i + + ) { S y st em .--. o u t . p ri n t l n ( " M ai n T h r e a d I n t er r u p t e d " ) .. o u t .-} thread. . sl e e p ( 1 0 0 0 ) . c l a ss t h r e a d { p u b l i c st a t i c v o i d m ai n ( S t ri n g a r g s[ ] ) { Thread r = Thread. f o r e a c h i t e r at i o n t h e m ai n T h r e a d sl e e p s f o r 1 se c o n d . i + + ) { S y st em . -. p ri n t l n ( " F i ni sh e d . E:\Core> Out put: E:\Core>javac thread2. f or ( i nt i = 0.

SATEESH N c r e a t i ng a T h r ead u s i ng t h r ea d c l a s s : T h e f i r st wa y o f c r e a t i n g a t h r e a d . o u t . First Thread : 2 try Second Thread : 29 { First Thread : 3 T h r e a d . p ri n t l n ( "F i r st T h r e a d : "+ i ). t h e 1 t h r e a d p r i n t s t h e v al u e s nd f r om 1 t o 1 0 wi t h t i m e of 1 se c .) { S y st em . i > = 2 6 . i s t o c r e a t i n g a c l a ss t h a t ex t e n d s t h e T h r e a d cl a ss. } } 97 SATEESH N st . a l l t h e st a t e m e n t s i n t h e r u n ( ) f u n ct i o n wi l l b e ex ec u t e d i n a se p a r a t e p r o c e s s. p r i nt l n (" F i r st T h r e a d I n t e r r u p t e d " ) . f o r e a c h i t e r a t i o n . t h e 2 t h r e a d p ri n t s t h e v al u e s f r om 3 0 t o 2 6 wi t h t h e g a p o f 2 se c . o u t . . j a v a / / I n t h e f o l l o wi n g e x am pl e 2 t h r e a d s wi l l b e c r e a t e d . sl e e p ( 1 0 0 0 ) . / / f i l e n am e : mu l th r e a d . W h e n ev e r a c l a ss e x t e n d s t h e T h r e a d c l a ss t h e f ol l o wi n g f u n c t i o n sh o u l d b e ov er ri d d e n . st a r t ( ) . o u t . c l a ss F i r st T h r e a d ex t e n d s T h r e a d Out put: { E:\Core>javac multhread. st a r t ( ).java p u bl i c v oi d r u n ( ) E:\Core>java multhread { f o r (i n t i = 1 . f o r e a c h i t e r a t i o n .. SecondThread s = new SecondThread(). } } } } c l a ss m u l t h r e a d { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { F i r st T h r e a d f = n e w F i r st T h r e a d ( ) . b o t h t h e t h r e a d s a r e u si n g a r o u n d 1 0 se c . i . s. i < = 1 0 . p u b l i c v oi d r u n ( ) : W h e n ev e r we st a r t t h e t h r e a d u si n g t h e st a r t m e t h o d t h e t h r e a d wi l l b e a d d e d t o t h e t h r e a d q u e u e a n d t h e t h r e a d c a l l s t h e r u n ( ) f u n c t i o n . Second Thread : 27 } First Thread : 7 } First Thread : 8 } Second Thread : 26 c l a ss S e c o n d T h r e a d e x t e n d s T h r e a d First Thread : 9 { First Thread : 10 p u bl i c v oi d r u n ( ) { E:\Core> f o r (i n t i = 3 0 . } c a t c h ( I nt e r r u p t e d Ex c e p t i o n ex ) { Sy st e m . i . f . First Thread : 4 } Second Thread : 28 c a t c h ( I nt e r r u p t e d Ex c e p t i o n ex ) First Thread : 5 { First Thread : 6 S y st em . b o t h t h e t h r e a d s wi l l b e st a r t a t t h e sa m e t i m e . e. try { T h r e a d . o u t . i + + ) Second Thread : 30 { First Thread : 1 S y st em . p ri n t l n ( " S e c o n d T h r e a d : "+ i ) . p ri n t l n ( " S e c o n d T h r e a d I n t e r r u p t e d " ) . sl e e p ( 2 0 0 0 ) .

java E:\Core>java mymulthread Second : 26 First : 1 First : 2 Second : 27 First : 3 First : 4 Second : 28 First : 5 First : 6 Second : 29 First : 7 First : 8 Second : 30 First : 9 First : 10 Finished . e n d i n g v a l ue e t c . 2 0 0 0 ) . M yT h r e a d s = n e w M y T h r e a d ( " se c o n d " . i + + ) { S y st em . i < = e n d . st a r t ( ) . 10 . st a r t ( ) . } } Out put: E:\Core>javac mymulthread. } p u bl i c v oi d r u n ( ) { / / p ri n t t h e v a l u e s f o r (i n t i = st a r t . o u t . t hi s. B e c a u se J av a d o e sn ’ t su p p o r t m u l t i p l e I n he r i t e n c e f o r cl a sse s w e c a n u se t h e r u n n a b l e i n t e rf a c e f o r cr e a t i n g a t h r e a d i n t h e f ol l o wi n g c o n d i t i o n . e n d . sl e e p ( d e l a y ) . o u t . p ri n t l n ( g e t N am e ( )+ " I nt e r u p t e d " ) . i n t e n d . . f . i nt st a r t . W h e n ev e r a cl a ss i m pl em e n t s t h e r u n n a b l e i n t e rf a c e t h e c l a s s sh o u l d o v e rr i d e t h e f ol l o wi n g f u n c t i on public void run( ). 2 6 . i n t d e l a y ) { se t N a m e ( n am e ) . d e l a y = d el a y . E:\Core> C r e a t i ng a T h re ad u s in g R u nn ab l e i n ter f a c e : T h e se c o n d m e t h o d f o r c r e a t i n g a T h r e a d i s t o c r e a t e a c l a ss t h a t i m pl em e n t s t h e r u n n a b l e i n t e rf a c e . W h e n we wa n t a c l a ss t o e x t e n d a n o t h e r c l a ss a n d we w a n t t h i s c l a ss t o wo r k a s a T h r e a d t h e n r u n n a b l e i n t e rf a c e sh o u l d b e u se d . } c a t c h (I n t e r r u p t e d Ex c e pt i o n ex ) { Sy st e m . t ry { T h r e a d . st a r t = st a r t . 1 . t hi s. F o r t h i s p u r p o se t h e st a r t v a l u e . . . t hi s. 3 0 . p ri n t l n ( g e t N am e ( ) + " "+ i ) . e n d = e n d . d e l a y. s. 98 SATEESH N . M y T h r e a d ( St r i n g n am e. c l a ss M y T h r e a d e x t e n d s T h r e a d { i n t st a r t .SATEESH N / / f i l e n am e : m y m u l th r e a d . } } } } c l a ss m ym ul t h r e a d { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { M yT h r e a d f = n e w M y T h r e a d ( "F i r st " . wi l l b e t a k e n a s p a r a m et e r s. 1 0 0 0 ) . j a v a / / t h e f ol l o wi n g p r o g r a m i s e n h a n c e m e n t f or t h e p r ev i o u s p r o g r a m wh i c h p r ov i d e s o n l y o n e t h r e a d c l a s s wi t h m u l t i pl e i n st a n c e s.

st a r t ( ). } c a t c h ( I nt e r r u p t e d Ex c e p t i o n ex ) { S y st em . sl e e p ( 1 0 0 0 ) . st a r t ( ). } } } } c l a ss se c o n d i m p l em e n t s R u n n a b l e { p u bl i c v oi d r u n ( ) { f o r (i n t i = 3 0 .) { S y st em . n e w T h r e a d ( s) . p ri n t l n ( " Out put: E:\Core>javac runintrface. o u t . o u t .. n e w T h r e a d ( f ) . t 1 . // // T h r e a d t 1 = n e w T h r e a d ( f ). l a n g . } c a t c h (I n t e r r u p t e d Ex c e pt i o n ex ) { S y st em . p r i nt l n (" S e c o n d I n t e rr u p t e d " ) . st a r t ( ) . st a r t ( ). p ri n t l n ( " F i r st : "+ i ). i .java E:\Core>java runintrface Second : 30 First : 1 First : 2 Second : 29 First : 3 First : 4 Second : 28 First : 5 First : 6 Second : 27 First : 7 First : 8 Second : 26 First : 9 First : 10 E:\Core> S e co n d : " + i ). i > = 2 6 . sl e e p ( 2 0 0 0 ) . . } } } } c l a ss r u n i n t rf a c e { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { f i r st f = n e w f i r st ( ) . *. try { T h r e a d . o u t . c l a ss f i r st i m p l em e nt s R u n n a b l e { p u bl i c v oi d r u n ( ) { f o r (i n t i = 1 .SATEESH N / / f i l e n am e : r u n i n t r f a c e . i + + ) { S y st em . j a v a i m p o r t j av a. t ry { T h r e a d . T h r e a d t 2 = n e w T h r e a d ( s) . // // } } 99 SATEESH N t 2 . p r i nt l n (" F i r st I n t e r r u p t e d" ) . o u t . i < = 1 0 . se c o n d s = n e w s e c o n d ( ) .

} } } 100 SATEESH N Out put: E:\Core>javac synchprinterfun. i n t d e l a y ) { S y st em . } } S y st em . } c a t c h (I n t e r r u p t e d Ex c e pt i o n ex ) { S y st em . i < = e n d . d e l a y = d e l a y. try { T h r e a d . } } c l a ss u s e r e x t e n d s T h r e a d { p ri n t e r p . e n d . p r i nt l n ( "[ " ). p = p . t h i s. o u t . } p u bl i c v oi d r u n ( ) { sy n c h r o n i z e d ( p ) { p. st a r t = st a r t . p r i nt l n ( "] " ). t h i s. p ri n t l n ( " "+ i ) . S y n c h r o n i z e d st a t em e n t s i . W h e n t wo o r m o r e t h r e a d s a r e t r y i n g t o ac c e ss t h e s a m e sh a r e d d ev i c e a n d i f t h e d ev i c e c a n ’ t b e sh a r e d t h e n we sh o u l d a p p l y sy n c h r o n i z a t i o n . p r i n t ( st a r t . sl e e p ( d e l a y ) . f o r (i n t i = st a r t . i . i + + ) { S y st em . i n t st a r t . d e l a y ). e n d = e n d . e n d . i n t d e l a y ) { t h i s. S y n c h ro n i ze d f u n c t io n s : S y n c h r o n i z a t i o n c a n b e a c h i ev e d b y p r ef i x i n g t h e f u n ct i o n wi t h t h e k e y wo r d sy n c h r o n i z e d . i n t e n d . i n t e n d . o u t . S y n c h r o ni z e d f u n ct i o n s i i .java E:\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> . t h i s. d e l a y.SATEESH N S y n c h r o n i z a ti o n : S y n c h r o n i z at i o n i s t h e p r o c e ss o f a p p l yi n g q u e u e m e c h a n i sm o n t h r e a d s. p r i nt l n (" T h r e a d I nt e r r u p t e d " ) . o u t . j a v a c l a ss p r i n t e r { sy n c h r o n i z e d v oi d p ri n t (i n t st a r t . i n t st a r t . S y n c h r o n i z a t i o n c a n b e a c hi ev e d i n t wo wa y s. o u t . / / f i l e n am e: s y n c h p r i n t e r f u n . u se r ( p r i n t e r p .

1 . i n t st a r t . 2 0 0 0 ) . } } i i . u 3 . 4 5 . c a l l t h e p r i n t ( ) f u n c t i o n i s a sy n c h r o n i z e d b l o c k f or t h e o bj e c t p . sl e e p ( d e l a y ) . } } c l a ss u s e r e x t e n d s T h r e a d { p ri n t e r p . u se r ( p r i n t e r p . st a r t ( ) . u se r u 2 = n e w u se r ( p . 4 1 . st a r t ( ) . u 1 . o u t . i n t d e l a y ) { t h i s. I f t h e p r i n t ( ) f u n c t i o n i s n o t sy n c h r o n i z e d . f o r (i n t i = st a r t . i n t e n d . p r i nt l n ( "] " ). 1 5 0 0 ) . o u t . u se r u 3 = n e w u se r ( p .java E:\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> SATEESH N . e n d . o u t . i n t d e l a y ) { S y st em . i n t e n d . u 2 . p ri n t l n ( " "+ i ) . u se r u 1 = n e w u se r ( p . i n t st a r t . p r i nt l n ( "[ " ). 1 0 . S y n ch r o n i ze d st a te m en t s : S u p p o se i f t h e f u n c t i o n o n wh i c h we wa n t o a c h i ev e sy n c h r o n i z a t i o n i s a t h i r d p a r t y p r o d u c t a n d i f we c a n n o t m o d i f y t h e so u r c e c o d e t h e n t o a c h i ev e t h e sy n c h r o n i z a t i o n we sh o u l d a p p l y t h e sy n c h r o n i z e d st a t e m e nt s.SATEESH N c l a ss sy n c h p r i n t e r f u n { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { p r i nt e r p = n e w p r i n t e r ( ). o u t . / / f i l e n am e: s y n c h p r i n t e r s t m . i + + ) { S y st em . d e l a y. } } S y st em . 101 Out put: E:\Core>javac synchprinterstm. 1 0 0 0 ) . 3 0 . 2 6 . p = p . p r i nt l n (" T h r e a d I nt e r r u p t e d " ) . j a v a c l a ss p r i n t e r { sy n c h r o n i z e d v oi d p ri n t (i n t st a r t . i < = e n d . st a r t ( ) . try { T h r e a d . } c a t c h ( I nt e r r u p t e d Ex c e p t i o n ex ) { S y st em .

p u b l i c v oi d n o t i f y( ) t h r o w s I n t e r r u p t e d E x ce p t i o n : so t h a t t h e wa i t i n g t h r e a d r e su m e s. st a r t ( ) . Makes the current thread t o N o t i f i e s t h e wa i t i n g t h r e a d .SATEESH N t h i s. st a r t = st a r t . p u b l i c v oi d wa i t ( ) t h r o w s I n t e r u p t e d E x c ep t i o n : wa i t . u se r u 1 = n e w u se r ( p . 2 6 . e . 3 . 3 0 . t h e qu e u e Q wa s e m p t y . e n d = e n d . u se r u 2 = n e w u se r ( p . u 1 . 4 1 . 1 . st a r t ( ) . i n so m e c a se s a T h r e a d e n t e r s i n t o wa i t i n g st a t e t i l l i t r e c e iv es i n p u t f r om a n o t h e r T h r e a d . } p u bl i c v oi d r u n ( ) { p . u 3 . Si m i l a rl y. p ri n t ( st a r t . 1 0 . e. o n c e the input is ready. a T h re a d sh o u l d n o t i f y t h e wa i t i n g T h r e a d . sy n c h r o n i z e d v oi d p u t (i n t n ) { 102 SATEESH N . 4 5 . T h e f ol l o wi n g t h r e e f u n c t i o n s o f t h e o b j e c t c l a ss a r e u se d f o r c om m u n i c at i o n b e t we e n t h e T h r e a d s. 2 0 0 0 ) . } } c l a ss sy n c h p r i n t e r st m { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { p r i nt e r p = n e w p r i n t e r ( ). d e l a y ). 1 0 0 0 ) . 2 . t h i s. d e l a y = d e l a y. st a r t ( ) . / / f i l e n am e : i n t e r th r e a d . u 2 . t h e T h r e a d wi t h t h e h i g h e st p ri o r i t y wi l l r e su m ef i r st . b o o l e a n f l a g = f a l se . u se r u 3 = n e w u se r ( p . i . } } In t e r T h r e ad C o m m u n i ca t i on : S om e t i me s t h e o u t p u t o f o n e T h r e a d wi l l b e t h e i n p u t o f a n o t h e r T h r e a d i . c l a ss Q { i n t n. . e n d . i f t h e / / c o n su m e r c o n su m e s t h e v al u e . . p u b l i c v oi d n o t i f y Al l ( ) t h r o ws I n t e r r u p t e d E x c e p t i o n : N o t i f i e s a l l t h e wa i t i n g T h r e a d s. j a v a / / F l a g b e c om e s t r u e . i f t h e su p p l i e r p a ss t h e v al u e . F l a g b e c om e s f al se . 1 . t h i s. 1 5 0 0 ) .

p ri n t l n ( " T h r e a d I n t e r r u p t e d" ) . t hi s. } p u b l i c v oi d r u n ( ) { f o r (i nt i = 1. } } } c l a ss p r o d u c e r e x t e n d s T h r e a d { Q q. c o n su m e r (Q q ) { t h i s. / / n o t at c o n su m ed S y st em . / / j u st su p p l i e d n o t i f y ( ).java E:\Core>java interthread Supplied : Consumed: Supplied : Consumed: Supplied : Consumed: Supplied : Consumed: Supplied : Consumed: Supplied : Consumed: Supplied : Consumed: Supplied : Consumed: Supplied : Consumed: Supplied : Consumed: Supplied : Consumed: 1 1 2 2 3 3 4 4 5 5 6 6 7 7 7 7 8 8 9 9 10 10 } c at c h ( I n t e r r u pt e d Ex c e p t i o n ex ) { S y st em . p ri n t l n ( " C o n su m e d : " + n ). p ri n t l n ( "T h r e a d I n t e rr u p t e d " ) . / / Q wa s e m p t y / / n o t i f y t h e su p p l i e r Out put: E:\Core>javac interthread. o u t . o u t . / / n o t su p p l i e d S y st em . / / i nf o rm t h e c u st om e r } c a t c h (I n t e r r u p t e d Ex c e p t i o n ex ) { S y st em . p u t (i ). o u t . } 103 E:\Core> SATEESH N . n o t i f y( ) . q = q . q = q . / / su p p l y 2 0 v al u e s } } } c l a ss c o n s u m e r ex t e n d s T h r e a d { Q q. i < = 2 0 . i + + ) { q . p r i nt l n ( "S u p p l i e d : "+ n ) . producer(Q q) { t hi s.SATEESH N try { i f (f l a g = = t r u e ) wa i t ( ). } } sy n c h r o n i z e d v oi d g e t ( ) { try { i f (f l a g = = f a l se ) wa i t ( ) . n = n . f l a g = f a l se . o u t . f l a g = t r u e.

st a r t ( ) . g e t ( ) .SATEESH N p u b l i c v oi d r u n ( ) { f or ( i nt i = 1. p . } } 104 SATEESH N . c o n su m e r c = n e w c o n su m e r ( q ) . / / r e c e i v e 2 0 v a l u e s f r om t he q u e } } } c l a ss i n t e r t h r e a d { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { Q q = new Q(). i + + ) { q. c. i < = 2 0 . producer p = new producer(q). st a r t ( ) .

boolean ret) : As above.*. String delimit.print("Enter a string:"). StringTokenizer tok = new StringTokenizer( data ). Tokens are separated from each other by delimiter characters. For example. using the default delimiters. StringTokenizer constructors : public StringTokenizer( String arg ) : Create a StringTokenizer based on String. 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. newline. public StringTokenizer( String arg.out. } } output : Enter a string: sateesh kumar sateesh kumar 105 SATEESH N . or specify your own. but if ret is true. u ti l. The tokens in this case are 12 and 8 and 5 and 32. System. The default delimiters are: space.nextToken() ).in)).j a va . import java.util.io.println( tok. Such a group is called a token. The StringTokenizer class is found in java. p a c ka g e StringTokenizer Class : Tokens and Delimiters : SATEESH N Often an input String contains several groups of characters. String delimit) : public StringTokenizer( String arg.out. using the individual characters in delimit as delimiters. These tokens are delimited by the space character. which must be imported for the program to compile. The StringTokenizer class aids in breaking a String into tokens.*.readLine(). You can use the default delimiters. and carriage return.util. // File name : StrTok1. Create a StringTokenizer based on String. public class StrTok1 { public static void main ( String[] args ) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.hasMoreTokens() ) System. tab.java import java. while ( tok. then individial delimiters count as tokens also. where each group acts as a unit that has significance. String data = stdin.

nextToken() ). Each time nextToken() is called.util. but this time with the delimiters specified in the constructor.in)).io.SATEESH N More than one Delimiter Works : Tokens can be separated by more than one delimiter. and User-specified Delimiters Here is the program again. . String nextToken( ) : Return the next token. The countTokens() method starts with the total number of tokens the String has been broken into. / / F i l e n am e : S t rT o k 2 . and minus.readLine().out.*. one token (starting with the first) is consumed.*.out. There are several spaces separating the tokens in the example. The delimiters are now space.hasMoreTokens() ) System. plus.println( tok. public class StrTok2 { public static void main ( String[] args ) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System. } } o u tp u t : Enter a string:c = a + b c a b 106 SATEESH N . j a v a import java. StringTokenizer tok = new StringTokenizer( data.print("Enter a string:"). equals. // note the space before = while ( tok. System. . import java. boolean hasMoreTokens( ) : Return true if there are more tokens. " =+-" ). countTokens() will report one less token. String data = stdin. Some methods of the class: StringTokenizer Methods : int countTokens( ) : Return the number of tokens remaining.

print("Enter a string:").Date Represent points in time.util. / / F i l e n am e : S t rT o k 3 .out.Date Abstract java.util.SATEESH N Returning Delimiters You probably regard the "=" and the "+" symbols as important.Format java. so they should be regarded as tokens.SimpleTimeZone extends java.sql. including information about applicable daylight savings rules.text. import java.text. All other classes are in the java. java.util.Date use in SQL statements.SimpleDateFormat extends java.* package extend java.Timestamp extends java. String data = stdin.* package.Calendar Abstract java.util.out.Calendar java.*.util. + b StringTokenizer tok = new StringTokenizer( data.println( tok.text.Date Note that DateFormat and related classes are in the java.util. 107 SATEESH N . as an alternative to using the information from Locale.TimeZone Abstract java. // note the space before = while ( tok. public class StrTok3 c { public static void main ( String[] args ) throws IOException = { BufferedReader stdin = a new BufferedReader(new InputStreamReader(System. This is done by using true as the third parameter in the constructor: Now individual delimiters (as well as tokens) are returned by nextToken().text.GregorianCalendar extends java. printable String and vice versa.readLine().DateFormat extends java. j a v a o u tp u t : Enter a string: c = a + b import java. C a l e n d a r a n d GregorianCalendar Classes : The various responsibilities for handling dates have been distributed among the following classes: java.* package..sql.util. Transformation into well-formatted. } } D a t e .TimeZone java.DateFormatSymbols Represents a point in time.Time extends java.text. But "+" also needs to work as a delimiter so that "12+8" is broken into the tokens "12". java.Date extends java.io.nextToken() ).util.util.text. Interpretation and manipulation of Dates.*. "+" and "8". etc. and also include proper formatting for java.hasMoreTokens() ) System. weekdays.util. true ).Date. Translation of the names of months. Representation of an arbitrary offset from Greenwich Mean Time (GMT).util.in)). All date-handling classes in the java.DateFormat java. " =+-".sql.util.util. System.sql.

out.MONTH.set(java.add(Calendar. DateFormat df1 = DateFormat. and the various rules and side effects to manipulating a Calendar.println("Date1=" + df.getDateInstance(). The preferred way to get specific Dates is by manipulating a Calendar.println("Date3=" + df. java. System. which explains the difference between the add() and roll() methods.month + 1.util.format(dt2)).Date firstOfMonth = cal. for example //Get a default (Gregorian) Calendar set to now Calendar cal = Calendar. cal.DAY_OF_MONTH. with millisecond accuracy. and a get() method you can use to retrieve the value of a field. Date also has a number of deprecated (obsolete) methods for getting a date at a specific point in time. You use these to identify to the methods.out.DateFormat is an abstract class that is extended by the java. Obviously to interpret a point in time correctly. java.format(dt3)).println("Date2=" + df. Date dt1 = new Date(). //get default format for current Locale 108 SATEESH N .util.SimpleDateFormat class. //prints todays date //prints Feb 29. as a rule the javadoc should refer you to the newer or better alternative method to use. with names like DAY_OF_MONTH and MONTH. java. 2005 //prints Mar 1.01. //deprecated! year + 1900. 1). If you look at the java.29). //defaults to now Date dt2 = new Date(100.getTime(). //deprecated! parses a String //factory for a SimpleDateFormat DateFormat df = DateFormat.may also change the year! cal.Date class can be used to construct objects that represent a specific point in time.getInstance(). System.getTime(). You can use both these classes to display java.out.text.util.Calendar class.util. System. which field you are changing. There are several ways to construct a Date object.getDateInstance().Date today = new java. 1).util. //Set the DAY field to 1 and get the date java. 2005! The java compiler will warn you if you use methods marked with the javadoc @deprecated statement in your own classes.Date objects in various String formats and parse String representations of dates into Date objects. builds a Date object that represents 'now'. you'll notice it defines a bunch of integer class constants.util.format(dt1)).Date(). The default no arguments constructor. you also need to know what calendar and what timezone is appropriate. A Calendar provides 3 methods set() add() and roll() that you can use to change a 'field' in the Calendar. There are classes in the java.Date today = cal.util package that provide this frame of reference.text.util.Calendar. You'll want to read the javadoc for the Calendar class.day Date dt3 = new Date("02/30/2005"). //Add 1 month to the calendar .util.SATEESH N The java.

/* Getting the year as int from Date object you need to add 1900 to it to get the 4 digit year.format(today)).getYear() will return 100.println("Invalid date entered = " + newReportDate). So 100 + 1900 = 2000.31.text. mydate.text.java import import import import java.util.out.out.out.println("Todays Date is: "+today).out. //display month and year DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy"). java.out.31. 2005" //prints "01/31/2005" Again. The getYear() method returns the number of years elapsed after the year 1900. java.util. GregorianCalendar c = new GregorianCalendar().parse(newReportDate). //Feb 28th 0005 AD try { //turn a String into a Date object reportDate = df.println(df1.util. So if it's the year 2000 now. System. 2005" //prints "January.format(td). yyyy"). //standard mdy format //prints "Jan 31.30. } // File name : SimpleDateForm. java.println(df2.31}.GregorianCalendar.30.getYear() + 1900.isLeapYear(c. */ int year = new Date().format(today)).28.ParseException e1) { System. } catch (java. System.31. System.format(today)). System.util.31.YEAR)) ? 1 : 0.Calendar.out.30.31. 109 SATEESH N . class SimpleDateForm { public static void main(String args[])throws Exception { // Getting the Date in simple date format Date td = new Date(). String today = sdf. //Beware date literals without centuries! String newReportDate = "02/28/05".println(df3. int [] daysInMonths = {31.get(GregorianCalendar. java. System.SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy"). SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"). java.util.SATEESH N DateFormat df2 = new SimpleDateFormat("MMMM.Date. Here is an example of how to parse a String into a java.println("Present Year : "+year). you'll want to see the javadoc for the SimpleDateFormat class for more details. daysInMonths[1] += c.SimpleDateFormat.text.Date reportDate = null.Date.30.

println("1989-10-17 was a " + sayDayName(date1)).get(GregorianCalendar.SimpleDateFormat.println("Day of Month is : "+c.OCTOBER.DateFormatSymbols. java.get( Calendar. System.out. of Days in current Month is : No.get( Calendar.DAY_OF_MONTH )).DATE )). java. System.getTime().out. System.DAY_OF_WEEK_IN_MONTH )).println("Week of Month is: "+c.*.println("Day of Week is : "+day).get(Calendar. of Days in current Month is : "+c. } } } 110 SATEESH N .DAY_OF_MONTH)).out.println("Today is a " + sayDayName(date2)).text. } public static String sayDayName(Date d) { DateFormat f = new SimpleDateFormat("EEEE"). class GetDayName { public static void main(String[] args) { Date date1 =(new GregorianCalendar(1989. of Days in current Month is : "+daysInMonths[c.MONTH)]).DAY_OF_WEEK ).out.get( Calendar. try { return f.println("Day of Month is : "+c. int day = c. } output : catch(Exception e) { 1989-10-17 was a Tuesday e.java import import import import import java.getActualMaximum(GregorianCalendar.util. 17)). System. Today is a Saturday return "".printStackTrace(). System.out.text.println("No.DAY_OF_YEAR )). java. Date date2 = new Date().Calendar.println("No.println("Day of year is : "+c.text.out. of Days in current Month is Day of Week is : 7 Day of Month is : 19 Week of Month is: 3 Day of year is : 50 Day of Month is : 19 28 : 28 // File name : GetDayName.DateFormat.out.get( Calendar.format(d).out. } } output : Todays Date is: 19/02/2005 Present Year : 2005 No.out. Calendar. System.SATEESH N System. java.util. System. System.

SimpleDateFormat.out. if(today_date.DateFormat.compareTo(cur_date).*.toString()). SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy"). } else { System.util.java import import import import java.text.*.text.Date.toString()). public class StringTODate_Converter { public static void main(String[] args) throws ParseException { String today_str = "04-01-2005". System.SHORT).println(cur_date.util.parse(today_str). System.text.out. java.out. import java.setLenient(false).java // Validate a date import java. // throws a ParseException // String dt = "1990-10/10".println("Before").println(today_date. int res = today_date.println("Equal"). } } } output : Tue Jan 04 00:01:00 IST 2005 Sat Feb 19 02:15:09 IST 2005 -1 Before // File name: ValidateDate.after(cur_date)) { System.getDateInstance(DateFormat. today_date = df.out.ParseException.out.SATEESH N // File name: StringTODate_Converter. java. // this is important! 111 SATEESH N . public class ValidateDate { public static void main(String[] args) { // Using DateFormat String dt = "1990/10/88".text. df. Date cur_date = new Date(). Date today_date = new Date(). } else if(today_date. System. java.println(res).out.before(cur_date)) { System. // throws a IllegalArgumentException try { DateFormat df = DateFormat. // throws a ParseException // String dt = "1990-10-35".println("After").

try { SimpleDateFormat sdf = new SimpleDateFormat(fdt).println(e. // must do this gc.println(e.out. sdf. // exception thrown here } catch (Exception e) output : { e. gc. gc. } catch (ParseException e) { System.dec otherwise it will throw exception */ try { GregorianCalendar gc = new GregorianCalendar().YEAR.getMessage()). 2004).parse(sdt).DATE. Date dt2 = sdf.println("Invalid date").println("Invalid date").out.setLenient(false).println(gc.jan to 11 . System.println("Date is ok = " + dt2). } /* Using GregorianCalendar.set(GregorianCalendar.set(GregorianCalendar. // 12 is invalid month gc. } catch (IllegalArgumentException e) { System. 11).set(GregorianCalendar.out. System.parse(dt). Unparseable date: "1990/10/88" } Date is ok = Sat Feb 19 00:00:00 IST 2005(050219) Fri Dec 24 02:22:06 IST 2004 } } 112 SATEESH N .out.setLenient(false).SATEESH N Date dt2 = df. give months 0 .out.printStackTrace().println("Date is ok = " + dt2 + "(" + sdt + ")"). } catch (IllegalArgumentException e) { System.MONTH. String fdt = "yyMMdd". System.out.getMessage()).getTime()). 24). } catch (ParseException e) { System. } // Using SimpleDateFormat String sdt = "050219".out.

equals() method for comparison) removeAll(Collection c) . Until now. they are not considered collections in JAVA. we notice a few things of interest:    All classes inherit from AbstractCollection. but not both.Collections : SATEESH N Collections are a vital part of any programming language...returns whether or not there are any elements in the collection contains(Object obj) . 113 SATEESH N . there are many collection classes and they are arranged in a hierarchy which contains both abstract and concrete classes.same as above but looks for ALL elements specified in the given collection parameter. clear( ) .empties out the collection by removing all elements. Although arrays collect objects together. we've just looked at the interfaces .same as above but adds ALL elements specified in the given collection parameter.adds the given object as an element to the collection (its location is not specified) addAll(Collection c) .returns the number of elements in the collection isEmpty( ) . Here are just a few: Notice that there are 4 abstract classes and 6 concrete classes shown.equals( ) method for comparison) containsAll(Collection c) . Modifying methods (changes the collection in some way):       add(Object obj) . 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( ) .removes the given object from the collection (uses . remove(Object obj) . The classes seem to be split as either having a List behaviour or a Set behaviour.same as above but removes all elements EXCEPT THOSE specified in the given collection parameter. retainAll(Collection c) . All classes (or their parents) implement one of the Collection interfaces.returns whether or not the given object is in the collection (uses . They allow many objects to be collected together and stored as one. which contains common behaviour for all collections. so what about the actual collection classes ? Well.same as above but removes ALL elements specified in the given collection parameter. Examining the diagram.

114 SATEESH N . We can later on. Vector..e. Stacks and LinkedLists have further restrictions.e. Stack and LinkedList): The List classes:    are ordered may contain duplicates have indexable elements (using zero-based indexing). 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).. As we will see. There are 4 main List implementations: Vector  a general kind of list with many useful accessing/modifying/searching methods  a synchronized class ArrayList also general like Vectors an unsynchronized class (faster than Vectors) LinkedList   methods for double-ended access. location in the collection). ArrayList. 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). access or modify particular elements according to their index (i.SATEESH N The List Classes Lets now examine the classes that implement the List interface (i.

myList. aVector = new Vector(Collection col). myList.   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. ArrayList anArrayList = new ArrayList()..add(c). ArrayList anArrayList = new ArrayList(Collection col). A Vector (or ArrayList):     can store arbitrary objects like an array. 115 SATEESH N .add(new BankAccount()).out. you can then apply any of the standard collection methods (plus others): Vector myList = new Vector( ).e. E. When extracting elements from a Vector or an ArrayList (or in fact ANY collection at all). //can use ArrayList v = new ArrayList( ). myList. use ArrayList instead of Vector. in that case.println(myList. except when the vector gets full .size().add(new Date()).i++) { Customer c = (Customer)v. myList. we must type-cast the result of the get(int index) method: for (int i=0. In more recent versions of JAVA (i.. Here are two ways of making one and storing it in a variable: Vector Vector aVector = new Vector(). } To get the Customers back out later. will grow automatically as space is needed (grows either by a default or user-defined amount). i<v. v.add(new Date()). i++) { Customer c = new Customer(). has an efficient method for adding an element. "Rahul".println(myList..get(i). instead for(int i=0. they cannot grow or shrink in response to an application's changing storage requirements. System. i<names. it takes time to "grow" the vector before adding the new element.SATEESH N Vectors and ArrayLists Arrays have a fixed size . Consider creating a Vector of Customer objects: String[] names = {"Sateesh".add("Hello"). ArrayList myList = new ArrayList( ). Java2) there is another class called ArrayList that has the same functionality as the Vector class.g. "Nani"}.size()). myList.add("Hello").size()). c.setNamenames[i]).. Vector v = new Vector().. Once created.add(new BankAccount()). Notice that the Vector and ArrayList are used the same way once created !!! If you do not care about synchronization. System.. myList. JAVA has a class called Vector for just this purpose.out.length. the element is returned as type Object. cannot store values of primitive data types unless they are wrapped up in a wrapper class. "Sanjana".

mv. i++) System.getName()). // or ArrayList mv = new ArrayList().red).out. ArrayList(int initialCapacity) : Constructs an empty list with the specified initial capacity.*. Example : import java.addElement("Hello"). //This would cause an error.elementAt(i)).out. i< mv. ArrayList(Collection c) : Constructs a list containing the elements of the specified collection.println(mv. //Note how a vector can store objects of different types mv.addElement(99) //Walk through each element of the vector for(int i=0.util.addElement(new Integer(99)). public class Vector_Ex1 { public static void main(String argv[]) { Vector_Ex1 obj = new Vector_Ex1(). in the order they are returned by the collection's iterator. in the order they are returned by the collection's iterator.amethod().size().addElement(Color. Constructs an empty vector with the specified initial capacity and with its Vector(int initialCapacity. int capacityIncrement) : initial capacity and capacity increment Constructs an empty vector with the specified ArrayList Constructors: ArrayList( ) : Constructs an empty list with an initial capacity of ten. }//End of main public void amethod() { Vector mv = new Vector().*. import java. mv.println(c. obj. Vector(int initialCapacity) : capacity increment equal to zero. Vector(Collection c) : Constructs a vector containing the elements of the specified collection. } Vector Consturctors : Vector( ) : Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.SATEESH N System.awt. }//End of amethod } 116 SATEESH N .As a vector will not storeprimitives //mv.

and we want to know how to use them.. import java....g.println(c. enumerate through) the elements of a collection once Many methods in Java return Enumerations instead of Collections or Vectors (e. often do so by returning the elements as an Enumeration.add("Tharni").println(names. } } 117 SATEESH N ... Enumerations have two methods:   hasMoreElements( ) .nextElement(). get me the next one Users make successive calls to nextElement( ) to obtain the elements from the collection. Vector VNames = new Vector().awt.nextElement()). VNames.b=0] 99 Enumerations and Iterators Enumerations are objects that:   generate elements from a collection one by one.add("Srinu").SATEESH N out put : Hello java.out.Color[r=255. VNames. } Example : Here is an example of how to use the Enumeration class on a Vector: import java.Enumeration.hasMoreElements( )) { Customer c = (Customer)v.e. names = VNames. elements()) Enumerations are not supported by ArrayLists. Enumerations are widely used in JAVA. Even though Enumerations are "old news"..add("Sateesh"). are there any more left ? nextElement( ) . we still discuss them here because there are still many JAVA enterprise methods that return Enumerations . Many. public class Enumeration_Ex1 { public static void main(String args[]) { Enumeration names.hasMoreElements()) System. many methods that need to return collections of objects.util. instead.getName()).elements( ).Vector.util. while (names. VNames.add("Ravi").out. ArrayLists use Iterators.elements().g=0. System.. are meant to be used to traversing (i. which are also supported by Vectors. while (e. VNames. Normally we use a while loop with hasMoreElements( ) as the sole condition: Enumeration e = v.

seven.println(elementno+" if(aString.remove(aString).out. nine. import java. "three". "six".util. two.out. "eight". Element"). ten] Element NO. "four".out.nextElement(). Element 1 one 2 two 3 three 4 five 5 six 6 seven 7 nine 8 ten After Vector: [one. eight. six. For some reason. five.hasMoreElements()) { String aString = (String)nums. JAVA does not allow you to remove from a collection that you are enumerating through !! Consider this (logically correct) example.length() > 4) aVector. public class Enumeration_Ex2 { public static void main(String args[]) { String[] num = {"one". "nine". three. } System. "ten"}. int elementno = 1.println("After Vector: " + aVector). "five". "two".asList(num)).SATEESH N out put: Sateesh Tharni Srinu Ravi Another common mistake is to remove from the collection that is being enumerated through. System.util. two. System.Arrays. while(nums. ten] 118 SATEESH N .println("Element NO.Vector. four. then this does not work properly. "seven".elements(). // during this statement element no and element will be changed elementno++. Vector aVector = new Vector(java. six. eight.util. "+aString). nine.out. } } out put: Before Vector: [one. five.Enumeration. System.println("Before Vector: " + aVector). four. Enumeration nums = aVector. and then look at the output to follow: Example : import java. If for example we want to enumerate through some items in a vector and remove items as well from the vector.

asList(num)). are there any more left ? next( ) . int elementno = 1. "nine". There are 3 methods:    hasNext( ) . Also. "five". elementno++.println("After Vector: " + aVector). we can use an Iterator.. To get an iterator.Vector...Arrays. } } 119 SATEESH N Element"). // Returns a ListIterator for forward / backward / modifying traversal. 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( ).util. get me the next one remove( ) .. not from the iterator. "two". import java.println("Before Vector: " + aVector).println("Element NO. but they have additional capability to remove from the collection which is being iterated through.listIterator().Iterator. An iterator is a tool like Enumerations for iterating (i. The moral is .. is not correct since the "eight" string was NOT removed as it should have been. the Vector. traversing) through the elements of a collection. don't use Enunerations if you are gonna be removing from the collection that you are enumerating through! To solve this problem. public class Iterator_Ex1 { public static void main(String args[]) { String[] num = {"one".iterator(). "ten"}.. // Returns an Iterator for forward traversal //ListIterator nums = aVector.. while(nums. "seven". System. . System.next(). "eight". This is a problem with Enumerations. The item is removed from the underlying collection.out.iterator(). send the iterator() message to a collection (such as a Vector): aVector.hasNext()) { String aString = (String)nums...util. after removing.SATEESH N Notice that the Enumeration did NOT produce all the items. } System.remove(). System. Here is how to use the iterator in a similar example to that above: Example : import java. "three". Vector aVector = new Vector(java. Iterators are very much like Enumerations.util. "+aString).println(elementno+" if (aString.out. Iterator nums = aVector. "six".out.length() > 4) nums.out.e. "four".

ten] Element NO. which can then be cast back to the original object type. Hashtables work by mapping a key to a value. } Example : package util. nine. two. four.out. data). Element 1 one 2 two 3 three 4 four 5 five 6 six 7 seven 8 eight 9 nine 10 ten After Vector: [one. The get method returns an object. six. otherwise its difficult to get the data back. Note that hashtables don't store keys sequentially. I've written a little demo that adds one hundred strings to a hashtable.nextElement() ). System. and returns an index number.Collections. you can always ask for an Enumeration of the hashtable's keys.SATEESH N out put: Before Vector: [one. ten] HashTable : Hashtables are an extremely useful mechanism for storing data. as a key. which wraps the int primitive data type.) { String str = (String) hash. eight. four. /* To demonstrate hashtables. It's important to know the key that maps to a value. hash.keys(). which is stored in an in-memory data structure. If you want to process all the elements in a hashtable. etc. Data is placed into a hashtable through the put method.util. However. for example. You can use a String.hasMoreElements(). three.get( e. Integer. Each string is indexed by an Integer. five. two. Individual elements can be returned. Rather than searching through all elements of the hashtable for a matching key. and can be accessed using the get method. // Use an Integer as a wrapper for an int Integer integer = new Integer ( i ). so you'll need to instead use Char. and the data is then accessed. nine. or perhaps a number such as an Integer. */ public class HashTable { public static void main (String args[]) throws Exception { // Start with ten. import java. so there is no ordering to the list. five. or the entire list can be displayed.*.println (str).put( integer. a hashing function analyses a key. This index matches a stored value. six. you can't use a primitive data type. expand by ten when limit reached 120 SATEESH N . seven. e. Long. // Get all values with an enumeration of the keys for (Enumeration e = hash.

just put. What do you do if some of your objects have duplicate keys? When you have duplicates.hasMoreElements().10).. just the last? both? If you are clever. You cannot have elements with duplicate keys.toString()). before you put. To get the last duplicate. e.println (hash. If you add a new element that duplicates the key of an existing element.println (hash.keys().println ("Displaying all values of Hashtable. if so.. what do you want to find when you do a lookup? Just the first.SATEESH N Hashtable hash = new Hashtable(10. // Get value out again System. This is a bit inefficient for nonduplicates. Your logic might look a bit like this: Example : 121 SATEESH N . do nothing.nextElement(). Any you might handle the special case of just one duplicate with an array. (Hashtable is unordered )"). To get the first duplicate.parseInt(e. Store each of the duplicates in one of the slots of the ArrayList. "Number : " + i).get(new Integer(21))). } } } out put : Number : 5 Number : 21 Displaying all values of Hashtable. int hashkey.get(new Integer(5))).out. System.. do a check to see if the element is already in the Hashtable.out. (Hashtable is unordered ) Number : 20 Number : 41 Number : 62 Number : 83 Number : 40 etc. For them. i <= 100. To get both.put( integer. for (int i = 0. store an ArrayList as the value. ) { hashkey = Integer. It will replace what was there before. it will replace it.. Dealing With Duplicates Hashtables don't permit duplicates. System.out.get(new Integer(hashkey))). i++) { Integer integer = new Integer ( i ). hash.out. // Get all values Enumeration e = hash. you ca get all those behaviours with a Hashtable. } // Get value out again System. you could store just the plain Object. for (.println (hash.

addElement(key). public class AssocArray_Dictionary extends Dictionary { private Vector keys = new Vector(). or null in Java terms. the key can only be the handle for one value term.removeElementAt(index). } public Object remove(Object key) { int index = keys.removeElementAt(index).addElement(value). it will return at most one object as its value from the collection. if(index == -1) return null. return values.size(). } public Object put(Object key. } public Enumeration keys() { return keys. } public boolean isEmpty() { return keys. The same object can be the value for multiple keys. private Vector values = new Vector(). } public Enumeration elements() { return values.indexOf(key). values. The way a dictionary works is if you provide an object as a key. } public Object get(Object key) { int index = keys.SATEESH N Dictionaries The abstract Dictionary class describes the interface for working with key-value maps. keys.elements(). } 122 SATEESH N . // indexOf() Returns -1 if key not found: if(index == -1) return null. return returnval.isEmpty(). However. values.util.elementAt(index). How the actual key-value pairs are stored is dependent on the specific implementation.indexOf(key). Object value) { keys. Example : import java.elements(). return key. Object returnval = values. If the key isn't in the map. you get nothing back.*. public int size() { return keys.elementAt(index).

String.length.out. It’s efficient only from the standpoint of size. In addition. c++) aa. 'h' }. 't'. a BitSet will be wasteful.) The following example shows how the BitSet works and demonstrates the version 1. for(char c = 'a'. That is. which makes it appear that the Java version 1. c <= 'z'.set(i).println("Uppercase: " +aa.clear(i). the collection will expand as you add more elements. it is slightly slower than using an array of some native type. i--) if(((1 << i) & bt) != 0) bb. for(int i = 7.1. like 8 bits. This implies that if you’re storing anything smaller. The BitSet does this as well – sort of.SATEESH N // Test it: public static void main(String[] args) { AssocArray_Dictionary aa = new AssocArray_Dictionary(). sometimes it works and sometimes it doesn’t. for(int i = 0. char[] ca = { 's'. 's'. 'a'. else bb.nextInt(). BitSet bb = new BitSet(). i < ca.valueOf(c). i >=0.put(String.0 bug: Example : // Demonstration of BitSet public class BitSet1 { public static void main(String[] args) { Random rand = new Random(). so you’re better off creating your own class to hold your flags.valueOf(c). 123 SATEESH N . In a normal Vector. the minimum size of the BitSet is that of a long: 64 bits. 'i'. (It is fixed in Java 1. and it is used if you want to efficiently store a lot of on-off information.valueOf(ca[i]))). } } out put: Uppercase: S Uppercase: A Uppercase: T Uppercase: I Uppercase: S Uppercase: H BitSet A BitSet is really a Vector of bits.toUpperCase()). // Take the LSB of nextInt(): byte bt = (byte)rand. i++) System. if you’re looking for efficient access.0 implementation of BitSet is just badly done.get(String.

for(int j = 0. 9. i--) if(((1 << i) & it) != 0) bi. 4. System. else bs. b1023. System. else bi. 14.println("set bit 127: " + b127). 7} bit pattern: 0100011100000000000000000000000000000000000000000000000000000000 short value: -14048 bits: {5.out. 15} bit pattern: 0000010010010011000000000000000000000000000000000000000000000000 int value: -1916419530 bits: {1. 18. j++) bbits += (b.println("bits: " + b). 27.println("int value: " + it). BitSet b1023 = new BitSet(512). int it = rand. 11. 8.get(j) ? "1" : "0"). 16.out. // Without the following. b127.println("short value: " + st).clear(i). 15.println("set bit 1023: " + b1023). an exception is thrown // in the Java 1. i >=0. b255.set(1023).out. 6. BitSet bi = new BitSet(). System.out.set(127). } static void printBitSet(BitSet b) { System.set(255). printBitSet(bb). 2. 26. short st = (short)rand.set(i).set(1024). 31} bit pattern: 0110110001000011101000111011000100000000000000000000000000000000 124 SATEESH N .size() . printBitSet(bs).out. BitSet b255 = new BitSet(65). 5. System. 5. 14. 22. i >=0.nextInt(). System.set(i). printBitSet(bi).nextInt(). 24. System.out.SATEESH N System.out. 23. } } out put: byte value: -30 bits: {1.out.println("bit pattern: " + bbits). // Test bitsets >= 64 bits: BitSet b127 = new BitSet(). j < b. i--) if(((1 << i) & st) != 0) bs.println("byte value: " + bt). BitSet bs = new BitSet().0 implementation of BitSet: // b1023. for(int i = 15.clear(i). for(int i = 31. String bbits = new String().println("set bit 255: " + b255).

"March". 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(). we put them at the top and when removing them. "June". pop() . Stack is inherited from Vector. "September". 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. What’s rather odd is that instead of using a Vector as a building block to create a Stack. empty() . when placing items in the stack.return the top element of the stack without removing it. That is. The topmost element has position 1. 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. "November". peek() . we always take the top one off. "July". If there are no elements in the stack. -1 is returned. 125 SATEESH N . Like all of the other collections in Java.return whether or not there are any elements in the stack. an error occurs. Although Stack inherits many other methods from its superclasses.util.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. search(Object obj) . If the object is not found in the stack. "May". "April".*. "October". So it has all of the characteristics and behaviors of a Vector plus some extra Stack behaviors. We all know that a stack is a collection of items that are placed or "stacked" on top of one another. If duplicates exist. If there are no elements in the stack. what you push and pop are Objects. whatever you “push” on the Stack last is the first item you can “pop” out. first-out” (LIFO) collection. public class StackDemo2 { static String[] months = { "January". an error occurs. the position of the topmost one is returned. That is. "December" }. Here’s a simple demonstration of Stack that reads each line from an array and pushes it as a String: Example : import java.remove and return the top element of the stack. The very definition of a stack implies a last-in-first-out protocol when accessing the items. "August".return the distance of the given object from the top of the stack. so you must cast what you pop. "February".

System. March .out. September . // Treating a stack as a Vector: stk. April .addElement("The last line").out.pop()). October .println("stk = " + stk). December ] element 5 = June popping elements: The last line December November October September August July June May April March February January Lang Package 126 SATEESH N .empty()) System. i++) stk.SATEESH N public static void main(String[] args) { Stack stk = new Stack().length.out. July . August . while(!stk.out.println("element 5 = " + stk.push(months[i] + " "). May . June . for(int i = 0.println("popping elements:"). System. November . System.elementAt(5)).println(stk. February . } } output : stk = [January . i < months.

p u b l i c c l a ss a p p l e t 1 ex t e n d s A p p l e t { p u bl i c v oi d i n i t ( ) { se t B a c k g r o u n d ( C o l o r .A p p l e t s & A W T ( A b s t ra c t Wi n dow To ol k i t ) : SATEESH N Ap p l e t : A n A p p l e t i s a p r o g r a m d e si g n e d i n j av a a n d wi l l b e pl a c e d o n t h e se rv e r. T h e a p p l e t wi l l b e d o wn l o a d e d f r om t h e se r v e r t o t h e cl i e nt a l o n g wi t h “ H T M L ” d o c u m e n t s a n d r u n s i n t h e c l i e n t s we b b r o w se r ( i . j av a sav e f i l e n a m e a s a p p l e t 1 . 2 . . o r a n g e ) . j a v a i m p o r t j av a. . se t C o l o r ( C o l o r. . p u b l i c v oi d st o p ( ) : W h e n ev e r t h e u se g o e s t o t h e n e x t d o c um e n t . 1 . t h e u se r c l o se s t h e W E B b r o wse r . 3 . se t F o n t ( n e w F o n t ( "G a r am o u n d " . W e c an ov e r ri d e t h e f ol l o wi n g m et h o d s d e p e n d i n g o n t h e r e q u i r em e n t . 1 5 0 ) . g . a n A p p l e t wi l l r u n a s a p a r t of t he we b d o c u m e n t ) . 1 0 0 . d a t a b a se se r v e r s e t c. An a p p l e t c a n o p e n c o n n e c t i o n wi t h t h e n e t wo r k se rv e r s. A n a p p l e t c a n c o n t ai n c o m p o n e n t s l i k e b u t t o n s. p u b l i c v oi d st a r t ( ) : C a l l e d af t e r i ni t . a wt . se t C o l o r ( C o l o r.java E:\Core>appletviewer applet1. cl a ss” wi d t h = 4 0 0 h e i g h t = 3 0 0> < / a p p l et > </html> W h e n ev e r a n A p p l e t i s b e i n g l o a d e d i n a W EB b r o ws e r . } p u bl i c v oi d p a i nt ( G r a p hi c s g ) { g . p u b l i c v o i d i ni t ( ) : T hi s m e t h o d wi l l b e c a l l e d wh e n ev e r t h e a p pl e t i s b e i n g l o a d e d i n t o t h e W EB b r o wse r f o r t h e f i r st t i m e . d r a wS t r i n g ( " S AT E ES H " .. ht m l . 2 0 ) ) . wh i c h wi l l b e u se d i n t h e g r a p h i c al i n t e rf ac e p r o g r am m i n g . c h e c k b o x e s e t c . 4 . t ex t b ox e s e t c .html . g .. i m p o r t j av a. 127 SATEESH N Out put : E:\Core> javac applet1. * . d r a wS t r i n g ( "T e st i n g t h e A p p l e t i n J av a " . a p p l e t . t hi s m e t h o d wi l l a l so b e c a l l e d ev e r y t i m e wh e n e v e r t h e d o c um e n t c o n t ai n i n g t h e a p p l e t i s r e di sp l a y e d o n t h e W EB b r o wse r . } } < ! . 1 0 0 . r e d ) . B O L D . t h e W E B b r o wse r c a l l s t h e f ol l o wi n g m e t h o d s of t h e A p p l et . F o n t . e . / / f i l e n am e : a p p l e t 1. g . * . b l u e ) . C r e a t i n g a n A p pl e t : T o c r e a t e a n A p p l e t cr e a t e a cl a ss t h a t e x t e n d s t h e A p p l e t c l a ss. g . .> <html> < a p p l e t c o d e = “ a p p l e t 1.H T M L c o d e f o r a p p l e t 1 . AW T : AW T i s a c o l l e c t i o n of c l a sse s wh i c h p r ov i d e s g r a p h i c a l c om p o n e n t s su c h a s b u t t o n s. p u b l i c v oi d d e st r o y ( ) : W h e n ev e r t h e A pp l e t i s b e i n g r em ov e d f r om t h e W E B b r o w se r F o r ex . 5 0 ) .

U R L g e t C o d e B a se ( ) : R e t u r n s t h e U R L of t h e A p p l e t . b e c a u se t h e a p p l e t i s b e i n g e x e c u t e d i n a n o t h e r p r o g r a m i .li ghtgray color. i n t h e i g h t . v oi d d r a wst r i n g ( S t ri n g st r . y 1 ) t o ( x 2. i n t wi d t h . v oi d d r a wO v al ( i n t x . Ap p l e t c l a s s m e t h o d s : A p p l e t i s t h e su p e r c l a ss f o r a l l t h e a p p l e t s. 1 . I t r et u r n s n u l l i f t h e p a r am e t e r i s n o t av ai l a bl e . bl u e c o l o r . i nt y. i nt x 2 . i n t y. n 2 sp e c i f i e s t h e c u rv e d e t ai l s. i nt y . t h e A p pl e t i s b e i n g ex e c ut e d i n a W EB b r o wse r . i nt h e i g h t ) : D r a ws a o v al a t (x .gray color. v oi d r e p a i nt ( ) : R e d r a ws t h e A p p l e t . y) l o c a t i o n s wi t h t h e g iv e n wi d t h a n d h e i g h t .darkgray v al u e of the sp e c i f i e d c o l o r ( i n t r e dv al u e . v oi d se t B a c k g r o u n d ( c o l o r n e wc o l o r ) : v oi d se t F o r e g r o u n d ( c o l o r n e wc o l o r ) : color. H e r e n 1 . p u b l i c v oi d p a i n t ( G r a p h i c s g ) : T h i s m e t h o d wi l l b e c a l l e d wh e n e v e r t h e o u t p ut m u st b e r e d r a wn .SATEESH N T h e A p p l e t c l a ss m u st b e p u b l i c. y 2 ) 3 . y l o c a t i o n s wi t h t h e g iv e n wi d t h a n d h e i g h t . i nt n 1 .green c o l o r . i n t wi d t h . wh i t e c o l o r . 5 . T h i s m e t h o d al so r e c e i v e s a p a r a m e t e r of t h e g r a p h i c s cl a ss wh i c h c o n t a i n s t h e g r a p h i c s c o n t ex t d e t ai l s. i nt x . i n t y ) : Dr a w s t h e st r i n g a t (x .orange col or. v oi d d r a wR o u n d R e c t ( i n t x . v oi d sh o wS t a t u s( S t r i n g m sg ) b r o w se r . i nt y 2 ) : D r a ws a l i n e f r om (x 1 . e. S t ri n g g e t P a r am e t e r (S t ri n g p a r am N am e ) : Returns the p a r a m e t e r. T h e a b ov e 5 m e t h o d s c a n b e o v e r ri d d e n a n d wi l l b e c a l l e d b y t h e W E B b r o wse r d e p e n d i n g o n t h e u s e r n av i g a t i o n o n t h e HT M L d o c um e n t s. 128 SATEESH N . i n t h e i g h t ) : D r a ws a r e c t a n g l e a t x . i n t bl u ev al u e ) : Graphics Class Methods : T h e G r a p hi c c l a ss c o n t a i n s t h e G r a p h i c s c o n t e x t d e t ai l s wh i c h i s c o n t a i ni n g t h e f o l l o wi n g m e t h o d s. i nt g r e e nv a l u e .m agenta c o l o r . v oi d d r a wL i n e ( i n t x 1.cyan col or. T h e f ol l o wi n g m et h o d s a r e a l so av a i l a b l e i n t h e A p p l e t cl a ss wh i c h c a n b e c a l l e d i n t h e p r o g r am d e p e n d i n g o n t he r e q u i r em e n t . 5 . y el l o w color. * . pi n k c o l o r . T h e gr a p h i c s c l a ss av a i l a b l e i n t h e j av a . i n t y 1. bl a c k color. v oi d d r a wR e c t ( i nt x . i n t wi d t h . a wt . 2 . i n t n 2 ) : D r a w s a r o u n d e d r e c t a n g l e .red color. 4 . y ) l o c at i o n s. U R L g e t D o c u m e n t B a se ( ) : : D i sp l a ys t h e m e ssa g e i n t h e st a t u s b a r o f t h e W EB R e t u r n s t h e UR L o f t h e HT M L d o c um e n t . .

y 1 ) .o r di n a t t e s 129 SATEESH N E:\Core> javac appshapes. 1 1 . p u b l i c c l a ss a p p sh a p e s e x t e n d s A p p l e t { p u b l i c v oi d i ni t ( ) { se t B a c k g r o u n d ( C o l o r . 7 . 8 . . } p u b l i c v oi d p ai n t (G r a p h i c s g ) { D i m e n si o n d = g e t Si z e ( ) . h. i nt y[ ] = { h . v oi d d r a wP o l y g o n ( P o l y g o n p o l y ) : D r a w s a p o l y g o n . . / / se t t i n g a p o l y g o n i nt x [ ] = { 0 . i n t h e i g h t . b l a ck ) . h e i g h t . h / 2 . 5 ). p u b l i c i nt h ei g h t . a wt . i n t y . i m p o r t j av a. 0 . } / / F i l e n am e : ap p sh a p e s . i n t wi d t h . h / 2 }. i nt n 2 ) : F i l l s t h e sp e c i f i e d l o c a t i o n . v oi d S e t C ol o r ( C ol o r n e w c o l o r ) : S e t s t h e d r a wi n g c o l o r . v oi d f i l l R o u n d R e c t ( i n t x . / / 5 c o . D i m e n si o n g e t Si z e ( ) : R e t u r n s t h e si z e of t h e c om p o n e n t . y n ). P o l y g o n p o l y = n e w P o l y g o n ( x . i nt h e i g ht ) : F i l l s t h e sp e c i f i e d l o c at i o n . y 2 ) . 0 . Ex: P u b l i c Cl a ss D i m e n si o n { p u b l i c i nt wi d t h .java E:\Core> appletviewer appshapes. w/ 2 . v oi d f i l l R e c t ( i nt x . C o m p o n e n t C l a ss : C o m p o n e n t i s t h e s u p e r c l a ss f o r a l l t h e c l a sse s. . * . i nt wi d t h . v oi d f i l l O v al ( i nt x . i nt h = d. i n t n 1 .SATEESH N Ex: n1 n2 6 . * .html cont…. wi d t h . . w} . . y . (x 2 . v oi d f i l l P ol y g o n ( P ol y g o n p o l y ) : F i l l s t h e p o l y g o n . w. i n t y . j a v a Out Put : i m p o r t j av a. (x n . i n t wi d t h . i n t y . a p p l e t . i nt h e i g ht ) : F i l l s t h e sp e c i f i e s l o c a t i o n . wh i c h i s c o n t a i n i n g t h e f ol l o wi n g m e t h o d s. i nt w = d . P o l y g o n i s a c l a ss wh i c h c o n t a i n s (x 1 . 9 . 1 0 .

p 2 .8 ) . p 3 .8 . d r a wL i n e ( 0 . g. se t F o n t ( n e w F o n t ( "T i m e s n e w R o m a n " . p u b l i c c l a ss a p p se n d p a r a e x t e n d s A p p l e t { S t r i n g p 1. F o n t . } 130 SATEESH N . h . d r a wR e c t ( 4 .html / / F i l e n am e : a p p s e n d p a r a . c y a n ) .15. d r a wO v al ( 8 . a wt . d r a wS t r i n g ( " S am pl e S h a p e s" . se t C o l o r ( C o l o r. p 2 = g e t P a r am e t e r ( " e n am e " ). w.fill Polygon(pol y). 1 4 ) ) .java </body> </html> E:\Core> appletviewer appshapes. } } Sending Parameters : W e c a n se n d p a r a m et e r s t o a n A p p l et u si n g t h e p a r am t a g i n t h e H T M L d o c um e n t . 8. / / R et r i ev e t h e v al u e s of t h e p a r am et e r s p 1 = g e t P a r am e t e r ( " em p n o " ). cy a n ) . * . g .SATEESH N g . 0 . j a v a i m p o r t j av a. p 3 = g e t P a r am e t e r ( "j o b " ) . g . 4 . se t C o l o r ( C o l o r. p u b l i c v oi d i ni t ( ) { se t B a c k g r o u n d ( C o l o r .75.> <html> <body> < a p p l e t c o d e = " a p p se n d p a r a . S t ri n g g e t P a r am e t e r ( S t ri n g p a r am N am e ) : R e t u r n s t h e v al u e wh i c h i s a ssi g n e d t o p a r a m N am e i n h t m l c o d e . BO L D . h t m l . * .. / / HT ML Co d e < ! – a p p se n d p a r a . g . h .125. b l a ck ) . se t C o l o r ( C o l o r. y el l o w) . i m p o r t j av a.fill RoundRect(25. A j av a a p p l e t c an r e t r i ev e t h e v al u e s o f t h e p a r am e t e r s u si n g t h e f ol l o wi n g f u n ct i o n . c l a s s" wi d t h = 3 0 0 h e i g h t = 4 0 0 > < p a r am n am e = " em p n o " v al u e = " 1 0 1 " > < p a r am n am e = " e n am e " v al u e = " S a t ee sh r a j " > Out Put : < p a r am n am e = "j o b " v al u e = "M G R "> </appl et> E:\Core> javac appshapes. se t C o l o r ( C o l o r. g . w. w. g . se t C o l o r ( C o l o r. 3 0 .1 6 ) . a p p l e t .150. g r e e n ) . h ) . g . g .1 6 . 1 5 0 ) . g . l i g h t G r a y ). g.15). g . E a c h p a r am e t e r c o n t a i n s a n a m e a n d a v a l u e.

I m a g e O b se r v e r o b ) : v al u e s o n t h e g i v e n I m a g e o b se rv e r . B O L D .> < a p p l e t c o d e = ' a p p i m g. r e d ). t hi s) . t h i s) . } p u bl i c v oi d p a i nt ( G r a p hi c s g ) { g . 0.html -. d r a wS t ri n g ( p 3 . 5 0 . 0. I m a g e O b se rv e r o b ) : / / HT ML Co d e < ! – appimg.java E:\Core> appletviewer appimg. * . 5 0 ) . a p p l e t . 1 0 0 ) . d r a wI m a g e (i m g . i n t x . F o n t . 2 0 0 . g . a wt . 5 0 . j a v a Out Put : i m p o r t j av a.SATEESH N p u b l i c v oi d p ai n t (G r a p h i c s g ) { g . 1 4 ) ) . i m p o r t j av a. } } D r a win g I ma g e s o n t h e Ap p le t : T o p r e se n t a n i m a g e o n t h e a p p l e t .y v oi d d r a wI m a g e ( I m a g e i m g . j p g " ). v oi d d r a wI m a g e ( I m a g e i m g. g . * . } } E:\Core> javac appimg. d r a wS t ri n g ( p 1 . t h e i m a ge sh o u l d b e l o a d e d i n t o m em o r y u si n g o n e of t h e f ol l o wi n g f u n ct i o n s. se t C o l o r ( C ol o r . S t ri n g i m a g e ) : I m a g e g e t I m a g e ( U R L u r l _ of _i m a g e ) : T o d r a w t h e i m a g e t h e g r a p h i c s cl a ss p r o v i d i n g t h e f ol l o wi n g f u n c t i o n s. 0 . g . i nt h e i g ht . i n t y . p u bl i c v oi d i n i t ( ) { // loading the im age i m g= g e t I m a g e ( g e t C o d e B a se ( ) . Draw the im age at x. se t F o n t ( n e w F o n t ( " C om i c S a n s" . " k & h . d r a wI m a g e ( i m g . cl a ss' wi d t h = 3 0 0 h e i g h t = 4 0 0 > < / a p p l et > / / F i l e n am e : a p p i mg . 5 0 . / / g. p u b l i c c l a ss a p p i m g ex t e n d s A p p l e t { Im age im g. I m a g e g e t I m a g e ( U R L c o d e b a se . i nt y . 0 .html 131 SATEESH N . d r a wS t ri n g ( p 2 . i n t wi d t h . 1 5 0 ) . 2 0 0 . / / di sp l a y s t h e p a r am e t e r v al u e s g . i n t x .

we c a n n o t c r e a t e a n y i n st a n c e s o f t h e c o m p o n e n t c l a ss. i n t h ei g h t ) : S et s wi d t h a n d h e i g h t of t h e c om p o n e n t . C o m p on en t : i. i n t y ) : M ov e s t h e c o m p o n e n t t o t h e sp e c i f i e d l o c a t i o n. c h e c k b o x e s. C a nv a s Panel wi n d o w F r am e Di a l o g C o m p o n e n t i s a n a b st r a c t c l a ss. a wt “ p a c k a g e i s p r o v i di n g t h e f ol l o wi n g c o m p o n e n t c l a sse s. Label Check box Scrollbar Choice L i st Container v i i i . v. vii. p o i n t g e t L o c a t i o n ( ) : R e t u r n s t h e l o c a t i o n o f t h e c om p o n e n t . I t i s p r ov i d i n g a se t of m et h o d s wh i c h a r e av ai l ab l e i n a l l t h e su b c l a sse s. Button T ex t c om p o n e n t T ex t f i el d T ex t a r e a iii. iv.SATEESH N Ab s t ra c t Wi nd o wT o o l Kit P la c in g c o mp o n e n t s o n t h e Ap p le t : “ j av a. ( a ) c o m p o n e n t cl a ss : C o m p o n e n t i s a su p e r c l a s s f o r a l l t h e c om p o n e n t s. wh i c h a l l ow s u s t o p l a c e c o m p o n e n t s l i k e b u t t o n s. C o m p on en t c la s s Me t ho d s : v oi d se t B a c k g r o u n d ( C o l o r c o l o r ) : v o i d se t F o r e g r o u n d ( C o l o r c ol o r ) : Sets the background col or. ii. vi. b u t t h e m e t h o d s o f t he c o m p o n e n t cl a ss c a n b e u se d i n t h e su b c l as se s. v oi d se t L o c a t i o n ( i n t x . v o i d se t V i si bl e ( B o ol e a n v i si bl e ) : S h ow s t h e c o m p o n e n t t o t h e sp e c i f i e d l o c at i o n. . Ex: p u b l i c cl a ss p o i n t { public int x. b u t i t i s n o t c o n t a i ni n g a n y a b st r a c t m et h o d s i . ix. p u b l i c i n t y. e . d o o n t h e a p p l e t . v oi d se t E n a b l e d ( B o ol e a n e n a b l e s ) : E n a bl e s o r d i sa b l e s t h e c om p o n e n t . 132 SATEESH N . } v oi d se t S i z e ( i n t wi d t h. Sets the f oreground col or.

p u b l i c v oi d i ni t ( ) { b 1 = n e w B u t t o n ( "F i r st B u t t o n " ) . p u b l i c i nt wi d t h . Ex: B ut t t o n ( “S U B M I T ” ).SATEESH N v oi d g e t Si z e ( ) : Ex: p u b l i c cl a ss D i m e n si o n { p u b l i c i n t wi d t h . i . j a v a i m p o r t j av a.java E:\Core> appletviewer buttontest. a p p l e t . SUBMIT Button : S y n t ax : v oi d se t L a b e l ( St ri n g n e wl a b e l ) : v oi d g e t L a b e l ( ) : R e t u r n s t h e l a b e l of t h e b u t t o n . i nt wi d t h . } v oi d se t B o u n d s( i n t x . i nt h ei g h t ) : R e c t a n g l e g e t B o u n d s( ) : Ex: p u b l i c cl a ss R e c t a n g l e { p u b l i c i nt x . / / F i l e n am e : b u t to n t e s t . e n o l a b e l B u t t o n ( St r i n g L a b e l ) : c r e a t e s B u t t o n wi t h sp e c i f i e d l a b el .html 133 SATEESH N . p u b l i c i nt y.b2. / / sh o w s t h e c o m p o n e n t s o n t h e a p p l e t add(b1). b 2 = n e w B u t t o n ( " S e c o n d B u t t o n " ). i m p o r t j av a. publi c i nt hei ght. add(b2). * . C h a n g e s t h e l a b e l of t h e b u t t o n . p u b l i c i nt h ei g h t . * . p u b l i c c l a ss b u t t o n t e st ex t e n d s A p p l e t { Button b1. i n t y . } } Out Put : E:\Core> javac buttontest. a wt . B u t t o n ( ) : c r e a t e s b l a n k b u t t on . } F o r c r e a t i n g a p u sh b u t t o n .

b 2 = n e w B u t t o n ( " S e c o n d B u t t o n " ). a p p l e t . p u b l i c v oi d a c t i o n P e rf o rm e d ( A c t i o n Ev e n t e ) : T o h a n d l e a b u t t o n c r e a t e a c l a s s t h a t i m pl em e n t s t h e A c t i o n L i st e n e r i n t e rf ac e a n d ov e r ri d e t h e a c t i o n P e rf o rm e d m e t h o d . K e y L i st e n e r : F o r h a n d l i n g k e y ev e nt s. . I n t e rf a c e s : A c t i o n L i st e n e r : F o r h a n d l i n g b u t t o n s. m e n u i t em s e t c. a wt . M o u se L i st e n e r : A c t i o n L i st e n e r : Ac t i o n L i st e n e r i s c o n t ai n i n g t h e f ol l o wi n g m e t h o d . ev e nt p a c k a g e i s p r o v i d i n g t h e l i st e n e r i n t e rf a c e s f o r h a n d l i n g v a ri o u s t y p e s o f c om p o n e n t s. * . p u b l i c c l a ss b u t t o n t e st 2 e x t e n d s A p p l e t { Button b1. / / F i l e n am e : b u t to n t e s t 2 . F o r h a n d l i n g m o u se ev e n t s. b 2 . O n c e t h e c o rr e sp o n d i n g ev e n t o c c u r s t h e l i st e n e r s c a l l s t h e sp e c i f i e s m e t h o d . m o u se c l i c k e t c. l i st b o x e s. wh e n e v e r t h e ev e n t oc c u r s t h e l i st e n e r c a l l t h e c o r r e sp o n d i n g f u n ct i o n.java E:\Core> appletviewer buttontest2. j av a .SATEESH N Ha n d l in g C o mp o n e n t s : T o h a n d l e a n y c o m p o n e n t a l i st e n e r i s r e q u i r e d . W h e n ev e r t h e u se r c l i c k s o n t h e b u t t o n t h e l i st e n e r r e c e i v e s t h e ev e n t a n d ex e c ut e s t h e a c t i o n P e rf o rm e d m et h o d . a wt . A l i st e n e r wa i t s f o r a n e v e n t t o o c c u r . ev e n t . add(b2). a d d A ct i o n Li st e n e r ( n e w F i r st H a n d l e r () ) .html . W i n d o wL i st e n e r : F o r h a n d l i n g f oc u s ev e n t s. . a wt .b2. I t em Li st e n e r : F o r h a n d l i n g c h e c k b ox e s e t c . a d d A ct i o n Li st e n e r ( n e w S e c o n d H a n d l e r ( ) ) . i m p o r t j av a. * . . A d d t h e l i st e n e r t o t h e r e q u i r e d b u t t o n . i m p o r t j av a. A l i s t e n e r i s a p r o g r a m t h a t wi l l b e a t t a c h e d t o a c o m p o n e n t . A d j u st m e n t L i st e n e r : F o r h a n d l i n g sc r o l l b a rs. p u b l i c v oi d i ni t ( ) { b 1 = n e w B u t t o n ( "F i r st B u t t o n " ) . j a v a i m p o r t j av a. / / sh o w s t h e c o m p o n e n t s o n t h e a p p l e t add(b1). } // Handl ers First Button Clicked 134 SATEESH N Out Put : E:\Core> javac buttontest2. T h e l i st e n e r c o n t i n u o u sl y m o ni t o r s t h e c o m p o n e n t s f o r sp e c i f i c ev e n t s su c h a s k e y p r e s s. * . b 1 .

} } } / / F i l e n am e : b u t to n t e s t 3 . p u b l i c c l a ss b u t t o n t e st 3 e x t e n d s A p p l e t { Button b1. p u b l i c v oi d { b1 = new b2 = new / / sh o w s add(b1). * . a wt . } } } C lic k ed on S ec on d B ut t on i ni t ( ) B u t t o n ( "F i r st B u t t o n " ) . * . ev e n t . the com ponents on the applet Out Put : cont… E:\Core> javac buttontest3.SATEESH N cl a ss F i r st H a n d l e r i m pl em e n t s A c t i o n L i st en e r { p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e n t e ) { sh o wS t a t u s( " F i r st B u t t o n Cl i c k e d " ) . } } cl a ss S e c o n d H a n d l e r i m pl em e n t s A ct i o n L i st e n e r { p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e n t e ) { sh o wS t a t u s( " C l i c k e d o n S e c o n d B u t t o n " ) . a d d A ct i o n Li st e n e r ( n e w C o m m o n H a n d l e r ( ) ). j a v a i m p o r t j av a.java E:\Core> appletviewer buttontest3. b 2 . add(b2). i m p o r t j av a. a p p l e t .b2. * . a wt . e l se i f ( e . B u t t o n ( " S e c o n d B u t t o n " ).getSource() == b1 ) sh o wS t a t u s( " F i r st B u t t o n C l i c k ed " ) . i m p o r t j av a.html 135 SATEESH N . g e t S o u r c e ( ) = = b 2 ) sh o wS t a t u s( " C l i c k e d o n S e c o n d B u t t o n " ) . a d d A ct i o n Li st e n e r ( n e w C o m m o n H a n d l e r ( ) ). b 1 . } / / C om m o n H a n d l e r cl a ss C o m m o n H a n d l e r i m pl em e n t s A c t i o n L i st e n e r { p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e n t e ) { if ( e.

a d d A ct i o n Li st e n e r ( t h i s) . a wt . * . v oi d se t T ex t ( St r i n g t ex t ) : Pl a c e s t h e g i v en t ex t i nt o t h e t ex t b o x . ev e n t . } p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e nt e) { if ( e. i m p o r t j av a. j a v a i m p o r t j av a. p u b l i c c l a ss b u t t o n t e st 4 e x t e n d s A p p l e t i m pl em e n t s A c t i o n L i st e n e r { Button b1. i n t r o ws.html First Button Clicked T e x tF i el d ( ) : A t e x t f i el d i s u se d f o r t e x t f r om t h e u se r . } } E:\Core> javac buttontest4. * . i n t c o l s ) . a p p l e t . i m p o r t j av a. b 2 . T h e r e a r e 4 i m p o r t a n t c o n st r u c t o r s a r e t h e r e f o r T ex t F i el d . * . T ex t Ar e a ( i n t r o ws. T e x t Ar e a ( ) : F o r a c c e p t i n g m ul t i p l e l i n e s o f t ex t . i n t l e n g t h ) There are 2 im portant m ethods “ S t ri n g g e t T ex t ( ) : R et u r n s t h e t ex t i n t h e t e x t b ox .SATEESH N / / F i l e n am e : b u t to n t e s t 4 . T ex t F i el d ( ) T ex t F i el d ( S t ri n g st r ) T ex t F i el d ( i n t l e n g t h ) T ex t F i el d ( St r i n g st r. C o n st r u c t o r s : T ex t A r e a ( ) . Out Put : p u b l i c v oi d i ni t ( ) { b 1 = n e w B u t t o n ( "F i r st B u t t o n " ) .java E:\Core> appletviewer buttontest4. / / sh o w s t h e c o m p o n e n t s o n t h e a p p l e t add(b1). i n t c ol s ) Methods : S t ri n g g e t T ex t ( ) v oi d se t E d i t a b l e ( b o ol e a n e d i t a bl e ) 136 v oi d se t T ex t ( St r i n g t ex t ) v oi d a p p e n d ( S t ri n g t ex t ) SATEESH N . b 2 = n e w B u t t o n ( " S e c o n d B u t t o n " ). b 1 . v oi d se t E d i t a b l e ( B o o l e a n e d i t a b l e ) : M a ke s t h e t e x t r e a d o nl y o r r e a d a n d wr i t e .b2.getSource() == b1 ) sh o wS t a t u s( " F i r st B u t t o n C l i ck e d " ) . a d d A ct i o n Li st e n e r ( t h i s) . g e t S o u r c e ( ) = = b 2 ) sh o wS t a t u s( " C l i c k e d o n S e c o n d B u t t o n " ) . T ex t A r e a ( St ri n g st r . e l se i f ( e . a wt . add(b2).

a d d ( t 2 ). se t T ex t ( t 1 . t 2 . E:\Core> javac texttest. b 2 = n e w B u t t o n ( " C o p y U p " ). } p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e nt e) { if ( e. Button b1. i m p o r t j av a.SATEESH N / / F i l e n am e : t e x t t e s t . a d d A ct i o n Li st e n e r ( t h i s) . * .getSource() == b1 ) { t 2 . b 1 = n e w B u t t o n ( " C o p y D o wn " ) . se t T ex t ( " " ).html v oi d se t L a b e l ( S t ri n g n e wl a b e l ) : C h a n g e s t h e L a b e l . a p p l e t . a d d A ct i o n Li st e n e r ( t h i s) . b 1 . Out Put : p u b l i c v oi d i ni t ( ) { t 1 = n e w T ex t F i e l d ( 3 5 ). } el se i f ( e. p u b l i c c l a ss t ex t t e st ex t e n d s A p p l e t i m pl em e n t s A c t i o n L i st e n e r { T ex t F i el d t 1. g e t T ex t ( ) ). a d d ( t 1 ). se t T ex t ( "" ) . a wt . t 1 . add(b2). g e t S o u r c e ( ) = = b 2 ) { t 1. se t T ex t (t 2 . add(b1).b2. j a v a i m p o r t j av a. b 2 . ev e n t . i m p o r t j av a.java E:\Core> appletviewer texttest. } } } Checkbox : C o n st r u c t o r s : Checkbox( ) Methods : S t ri n g g e t L a b e l ( ) v oi d se t L a b e l ( St ri n g n e wl a b e l ) C h e c k b o x ( S t ri n g L a b e l ) T h e c h e c k b o x i s u se d f o r a c ce p t i n g B o ol e a n t y p e s of v al u e s. b o o l e a n g e t S t a t e ( ) : R et u r n s t r u e i f t h e c he c k b o x i s c h e c k e d o n o t h e r wi se f a l se . 137 SATEESH N . t 2. * . a wt . g e t T ex t ( ) ) . t 2 = n e w T ex t F i e l d ( 3 5 ). * .

g e t S o u r c e ( ) = = c b 1 ) { m sg = "F i r st C h e c k B ox : ". c b 2. add(cb2). i m p o r t j av a. b 1 .SATEESH N v oi d se t S t a t e ( B o o l e a n st a t e ) : C h a n g e s t h e st a t e o f t h e c h e c k b ox . g e t St a t e ( ) = = t r u e ? " C H E C K E D O N " : " C H E C K E D O F F " ). F ir s t c h ec k b ox O N S ec on d c h ec k b ox O F F Out Put : E:\Core> javac chkboxtest. a wt . } p u b l i c v oi d i t em S t at e C h a n g e d ( I t e m Ev e n t e) { S t ri n g m sg = "" . p u b l i c v oi d i ni t ( ) { se t F o n t ( n e w F o n t ( " c om i c S a n s" . wh i c h i s c o n t a i n i n g t h e f ol l o wi n g m e t h o d s. a wt . } sh o wS t a t u s( m sg ) . a d d I t em Li st e n e r ( t h i s) . c b 1 = n e w C h e c k b o x ( "F i r st C h e c k B ox ") . a d d A c t i o n L i st e n e r ( t h i s) . a p p l e t . } 138 SATEESH N . c b 2 = n e w C h e c k b o x ( " S e c o n d C h e c k B ox " ) . b 1 = n e w B u t t o n ( " S h o w B o t h D e t ai l s" ) . I t em Li st e n e r { C h e c k b ox c b 1 . m sg = m sg + ( c b 1 . i m p o r t j av a. F o n t . * . g e t S o u r c e ( ) = = c b 2 ) { m sg = " S e c o n d C h e c k B ox : " .java E:\Core> appletviewer chkboxtest. a d d I t em Li st e n e r ( t h i s) . add(b1). c b 2 . BO LD . P u b l i c v oi d i t em St a t e C h a n g e d ( I t em Ev e n t e ) : / / F i l e n am e : c h kb o x t e s t. } e l se i f ( e . A c h e c k b o x sh o u l d b e h a n d l e d u si n g I t e m Li st e n e r i n t e rf a c e. * . ev e n t . p u b l i c c l a ss c h k b o x t e st e x t e n d s A p p l e t i m pl e m e n t s A ct i o n Li st e n e r . c b 1 . 1 8 ) ) . add(cb1). j a v a i m p o r t j av a. m sg = m sg + ( c b 2 . g et S t a t e () = = t r u e ? " C H E C K E D O N " : " C H E C K E D O F F " ). * . Button b1.html i f ( e.

C h e c k b ox o p t 5 = n e w C h e c k b o x (" P o we r B u i l d e r ". add(opt2). a wt . sh o wS t a t u s( m sg ) . o p t 1 . a wt . t r u e ) . t r u e ) . g e t St a t e ( ) = = t r u e ? " O N " : " O F F " ) . p a c k . l a n g . add(opt4). m sg = m sg + ( c b 1 . C h e c k b ox o p t 1 = n e w C h e c k b o x (" C L a n g u a g " . j a v a i m p o r t j av a. m sg = m sg + ( c b 2 . t r u e ) . l an g . * . F o n t . a d d I t em Li st e n e r ( t h i s) . t r u e ) . / / F i l e n am e : r a d i o t e s t . m sg = m sg + " S e c o n d C h e c k B ox " . C h e c k b o x g e t S e l e ct e d c h e c k b ox ( ) : f r om t h e sp e c i f i e d g r o u p . i m p o r t j av a. add(opt1). C h e c k b ox o p t 3 = n e w C h e c k b o x (" J av a " . ev e n t . * . J av a c o nv e r t s them to “ Radi o Button “. B O LD . l a n g .getSource() == b1 ) { S t r i n g m sg = " ". a d d I t em Li st e n e r ( t h i s) . } } } c h e c k b o x g r o u p s : I f c h e c k b ox e s a r e a d d e d t o c h e c k b o x g r o u p s. p a c k . o p t 3 . o p t 2 . a d d I t em Li st e n e r ( t h i s) . m sg = " F i r st C h e c k B ox ". p u b l i c v oi d i ni t ( ) { se t F o n t ( n e w F o n t ( " A ri al Bl a c k " . add(opt3). a p p l e t . C h e c k b ox G r o u p p a c k = n e w C h e c k b o x G r ou p ( ) .java E:\Core> appletviewer radiotest. * . a d d I t em Li st e n e r ( t h i s) . o p t 4 . 1 4 ) ) . p u b l i c c l a ss r a d i o t e st ex t e n d s A p p l e t i m pl em e n t s I t em Li st e n e r { C h e c k b ox G r o u p l a n g = n e w C h e c k b o x G r o u p ( ) . a d d I t em Li st e n e r ( t h i s) . o p t 5 .html . add(opt5). g e t St a t e ( ) = = t r u e ? " O N " : " O F F " ) . C h e c k b ox o p t 2 = n e w C h e c k b o x (" C + + L a ng u a g " . C h e c k b ox o p t 4 = n e w C h e c k b o x (" Vi su a l Ba si c " .SATEESH N p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e nt e) { if ( e. t r u e ) . } 139 C + + L a n g u a g e P o w e r B u i l d eN SATEESH r R e t u rn s t h e r e f e r e n c e o f t h e se l e c t e d c h e c k b o x Out Put : E:\Core> javac radiotest. i m p o r t j av a.

u si n g the A d j u st m e n t L i st e n e r i n t e rf ac e . * . i n t g et V a l u e ( ) : R et u r n s t h e se l e c t e d v a l ue . ev e n t . 3 5 5 ). 0 . 1 0 0 . p u b l i c c l a ss sc r o l b a r r g b e x t e n d s A p p l e t i m pl em e n t s A d j u st m e n t Li st e n e r { S c r ol l b a r r e d = n e w S c r o l l b a r ( S c r ol l b a r . 0 . } } S c r o l l b a r : A sc r ol l b a r i s u se d f o r se l e c t i n g a v a l u e wi t hi n a g i v e n r a n g e . 0 . i n t i n i t i al v al u e . add(red). 0 . p u b l i c v oi d i ni t ( ) { se t L a y o u t ( n e w G r i d L a y o u t ( 4 . 1 0 0 . a wt . 3 5 5 ) . 0 . a p p l e t . v oi d se t V a l u e ( i n t v al ) : M ov e s t h e t h um b t o t h e sp e c i f i e d v al u e . g e t L a b e l ( ) + " sh o wS t a t u s( m sg ) . * . g e t L a b e l ( ) . sc r o l l b a r ( ) : C r e a t e s v e r t i c al sc r o l l b a r .SATEESH N p u b l i c v oi d i t em S t at e C h a n g e d ( I t e m Ev e n t e) { C h e c k b ox c 1 = l a n g . i m p o r t j av a. H O R I Z O N T A L . g e t S e l e ct e d C h e c k b o x ( ). 0 . St ri n g m sg = c 1 . add(blue). V E RT I C A L o r sc r o l l b a r . g e t S e l e ct e d C h e c k b o x ( ). Label l1 = new Label(). HO R I Z O NT A L . T hi s p u b l i c v o i d a d j u st m e n t V al u e C h a n g e d ( A d j u st m e n t Ev e n t e ) : / / F i l e n am e : scrolbarrgb. i m p o r t j av a. 1 ) ) . 140 SATEESH N . H O RI Z O N T A L sc r o l l b a r ( i nt st yl e .java i m p o r t j av a. i n t t h um b si z e . c o n s t ru c to r s : v oi d se t V a l u e s( i n t i ni t i al v a l u e. i nt t h um b si z e . S c r ol l b a r b l u e = n e w S c r o l l b a r ( S c r ol l b a r . 1 0 0 . 3 5 5 ). a wt . C h e c k b ox c 2 = p a c k . i nt m i n . sc r o l l b a r ( i n t st y l e ) : T h e st yl e m a y b e sc r o l l b a r. * . i nt m i n . A sc r o l l b a r sh o u l d b e h a n d l e d c o n t a i n i n g t h e f ol l o wi n g m e t h o d . add(l1). S c r ol l b a r g r e e n = n e w S c r o l l b a r ( S c r ol l b a r. i n t m ax ) : " + c 2. add(green). HO R I Z O NT A L . i nt m ax ) : C h a n g e s t h e r a n g e f o r t h e sc r o l l b a r .

SATEESH N

r e d . a d d A d j u st m e n t Li st e n e r ( t h i s) ; g r e e n . a d d A d j u st m e n t L i st e n e r ( t hi s) ; b l u e . a d d A dj u st m e n t Li st e n e r ( t h i s) ; } p u b l i c v oi d a dj u st m e n t V a l u e C h a n g e d ( A d j u st m e n t Ev e nt e ) { i nt r = r e d . g e t V al u e ( ) ; i nt g = g r e e n . g e t V a l u e ( ); i nt b = bl u e . g e t V al u e ( ) ; // get the new col or C o l o r n c = n e w C o l o r ( r , g, b ) ; l 1. se t B a c k g r o u n d ( n c ) ; sh o wS t a t u s( " R e d : " + r+ "G r e e n : "+ g + " Bl u e : "+ b ) ; } } Choice :

Out Put :
E:\Core> javac scrollbarrgb.java E:\Core> appletviewer scrollbarrgb.html

F o r c r e a t i n g a c om b o b ox o r d r op d o wn l i st b ox .

C o n st r u c t o r s : C h o i c e ( ) : C r e a t e s a c h o i c e c om p o n e n t . Methods : v oi d a d d ( St ri n g i t em ) : A d d a n i t em t o t h e c h o i c e b ox . S t ri n g g e t S e l e ct e d I t em ( ) : R e t u r n s t h e t ex t of t h e se l e c t e d i t em . i n t g e t S el e c t e d I n d ex ( ) : R e t u r n s t h e I n d e x of t h e se l e c t e d i t em st a r t i n g f r om z e r o . I t r e t u r n s m i n u s o n e ( - 1 ) o n n o se l e c t i o n . S t ri n g g e t I t em ( i n t i n d ex ) : R e t u r n s t h e t ex t of t h e sp e c i f i e d i t em . i n t g et I t em C o u n t ( ) : R e t u r n s t h e n um b e r of i t em s i n t h e c h oi c e c om p o n e n t . v oi d se l e c t ( i nt i n d ex ) : S el e c t s t h e sp e c i f i e d i t em . v oi d r em ov e ( i nt i n d e x ) : R em ov e s t h e sp e c i f i e d i t em .

v oi d r em ov e ( S t ri n g i t em ) : R em ov e s t h e sp e c i f i e d i t em . v oi d r e m ov eA l l ( ) : R e m ov e s a l l i t em s. A c h o i c e c o m p o n e n t c a n b e h a n d l e d u si n g I t em Li st e n e r i n t e rf ac e . L i s t : F o r cr e a t i n g a l i st b ox . L i st ( ) : d ef a u l t si z e . L i st ( i nt r o ws, b o o l e a n m u l t i se l e c t ) : A l l t h e f u n c t i o n s of t h e c h o i c e b o x su p p o r t e d i n t h e l i st b ox .
141 SATEESH N

SATEESH N

S t ri n g [ ] g e t S e l e ct e d I t em s( ) : R e t u r n s a l l t h e se l e c t e d i t em s. i n t [ ] g e t S el e c t e dI n d e x s( ) : R e t u r n s a l l t h e se l e c t e d i t em s.

A l i st b ox sh o u l d b e h a n d l e u si n g A c t i o n L i st e n e r i n t e rf a c e.

L a yo u t Ma n a g e me n t :
A l a y o u t sp e c i f i e s h o w t h e c o m p o n e n t s a r e a l i g n e d , si z e d a n d p o si t i o n e d i n t h e r u n t i m e of a n a p p l et . J av a . a wt p a c k a g e su p p o r t s t h e f o l l o wi n g f i v e l a y o u t cl a sse s f o r v a ri o u s a l i g nm e n t o f t h e c om p o n e n t s. F l o wL a y o u t BorderLayout G ri d L a yo u t CardLayout GridBagLayout

F l o w L a y o u t : I n t h e F l o wL a y o u t w h e n e v e r a c om p o n e n t i s a d d i t wi l l b e a d d e d i n t h e c u r r e n t r o w. I f t h e r e i s n o sp a c e i n t h e c u r re n t r o w, t h e c o m p o n e n t wi l l b e pl a c e d i n t he n e x t r o w. T h i s i s t h e d ef a u l t l a y o u t f or a p p l et a n d p a n e l s. F l o wL a y o u t ( ) : F l o wL a y o u t ( i nt al i g n ) : F l o wL a y o u t ( i nt al i g n , i n t v sp a c e , i n t h sp a c e ) :

align :

F l o wL a y o u t . C E N T E R F l o wL a y o u t . L E F T F l o wL a y o u t . R I G HT

( d ef a u l t )

v sp a c e a n d h sp a c e a r e t h e sp a c e d b e t we e n c om p o n e n t s v e r t i c al l y a n d h o ri z o n t al l y .

/ / F i l e n am e :

flowlay.java

Out Put :
E:\Core> javac flowlay.java E:\Core> appletviewer flowlay.html

i m p o r t j av a. a wt . * ; i m p o r t j av a. a p p l e t . * ; p u b l i c c l a ss f l o wl a y ex t e n d s A p p l e t { p u b l i c v oi d i ni t ( ) { se t B a c k g r o u n d ( C o l o r . pi n k ) ; se t F o n t ( n e w F o n t ( "B o o k A n t i q u a " , F o n t . BO L D , 1 6 ) ) ; se t L a y o u t ( n e w F l o wL a y o u t ( F l o wL a y o u t . R I G H T , 5 , 1 0 ) ) ; f or ( i nt i = 1; i < = 2 5 ; i + + ) { add(new Button("Button"+ i )); } } }

142

SATEESH N

SATEESH N

B o r d e r L a y o u t : I n t h e B o r d e r L a y o u t wh e n ev e r we a d d a c o m p o n e n t we sh o u l d a l s o sp e c i f y t h e di r e c t i o n of t h a t c om p o n e n t .

T h e f ol l o wi n g di r e c t i o n s a r e su p p o r t e d : B o r d e r L a y o u t . E A ST B o r d e r L a y o u t . W E ST BorderLayout.NORTH B o r d e r L a y o u t . S O UT H BorderLayout.CENTER Z e r o a r g um e n t c o n st r u c t o r ,

( d ef a ul t ) BorderLayout( ) :

T h i s i s t h e d ef a u l t l a y o u t f or f r am e s a n d d i a l o g s

/ / F i l e n am e : b o r d e r l a y . j a v a i m p o r t j av a. a wt . * ; i m p o r t j av a. a p p l e t . * ; p u b l i c c l a ss b o r d e r l a y ex t e n d s A p p l e t { S c r ol l b a r s1 = n e w S c r ol l b a r ( Sc r o l l b a r . VER T I C A L ) ; S c r ol l b a r s2 = n e w S c r ol l b a r ( Sc r o l l b a r . VER T I C A L ) ; C h o i c e c o u r se = n e w C h o i c e ( ) ; L i st l 1 = n e w L i st ( ) ; B u t t o n b 1 = n e w B u t t o n ( " S am pl e B ut t o n " ) ; p u b l i c v oi d i ni t ( ) { se t F o n t ( n e w F o n t ( " A ri al N a r r o w" , F o n t . BO L D , 1 4 ) ) ; se t L a y o u t ( n e w B o r d e r L a y o u t ( ) ) ; a d d ( s1 , B o r d e r L a y o u t . E A S T ); a d d ( s2 , B o r d e r L a y o u t . W E ST ) ; a d d ( l 1 , B o r d e r L a y o u t . C E N T E R) ; c o u r se . a d d ( " C L a n g u a g e " ) ; c o u r se . a d d ( " C + + " ) ; c o u r se . a d d ( " J av a " ); c o u r se . se l e c t ( 1 ) ; / / 2 n d i t em

Out Put :
E:\Core> javac borderlay.java E:\Core> appletviewer borderlay.html

l 1. a d d ( " Vi su a l B a si c " ) ; l 1. a d d ( " P o we r B u i l d e r ") ; l 1. a d d ( " D e l p h i " ) ; } }

143

SATEESH N

SATEESH N

GridLayout : I n t h e G r i d L a y o u t t h e t o t a l a r e a i s d i v i d e d i n t o r o ws a n d c o l u m n s. W h e n ev e r we a d d a c o m p o n e n t e a c h c om p on e n t wi l l b e a d d e d i n e a c h c e l l .

G r i dl a y o u t (i n t r o ws, i n t c o l s) : G r i dl a y o u t (i n t r o ws, i n t c o l s, i n t v sp a c e , i n t hsp a se ) : / / F i l e n am e : gridlay.java

Out Put :
E:\Core> javac gridlay.java E:\Core> appletviewer gridlay.html

i m p o r t j av a. a wt . * ; i m p o r t j av a. a p p l e t . * ; p u b l i c c l a ss g r i d l a y ex t e n d s A p p l e t { p u b l i c v oi d i ni t ( ) { se t B a c k g r o u n d ( C o l o r . p i n k) ; se t L a y o u t ( n e w G r i d L a y o u t ( 6 , 3 , 1 0 , 1 0 ) ) ; / / a d d 1 8 c om p o n e n t s f o r (i n t i = 1 ; i < = 1 8; i + + ) { a d d ( n e w B u t t o n ( " B u t t o n "+ i ) ) ; } } } P a n e l L a y o u t : A p a n e l i s a c o n t a i n e r o f c om p o n e n t s t h a t i s we a r e a b l e t o p l a c e c o m p o n e n t s l i k e B u t t o n s, c h e c k b o x e s e t c . , o n t h e p a n e l . A p a n e l c a n h av e a se p a r a t e background color, foreground color, layout etc., A p a n e l c a n c o n t a i n a n o t h e r p a n e l al so . / / F i l e n am e : p a n e l l a y . j a v a

Out Put :
E:\Core> javac panellay.java E:\Core> appletviewer panellay.html

i m p o r t j av a. a wt . * ; i m p o r t j av a. a p p l e t . * ; p u b l i c c l a ss p a n e l l a y ex t e n d s A p p l e t { Panel p1 = new Panel(); Panel p2 = new Panel(); p u b l i c v oi d i ni t ( ) { se t L a y o u t ( n e w B o r d e r L a y o u t ( ) ) ; / / f o r t he a p p l e t add(p1,BorderLayout.CENTER); a d d ( p 2 , B o r d e r L a y o u t . SO U T H ) ; p 1 . se t B a c k g r o u n d ( C o l o r . o r a n g e ) ; p 2 . se t B a c k g r o u n d ( C o l o r . p i n k) ; p 1 . se t L a y o u t ( n e w G r i d L a y o u t ( 2 , 2 , 5 , 5 ) ); p 1 . a d d ( n e w T ex t A r e a ( ) ); p 1 . a d d ( n e w T ex t A r e a ( ) );
144 SATEESH N

SATEESH N

p1.add(new Tex tArea()); p1.add(new Tex tArea()); p 2 . se t L a y o u t ( n e w F l o wL a y o u t ( ) ) ; p 2 . a d d ( n e w B u t t o n ( " F i r st " ) ) ; p2.add(new Button("Second")); p2.add(new Button("Third")); } } Card Layout : I n t h e c a r d l a y o u t a se t o f c a r d s wi l l b e a d d e d t o t h e l a y o u t . E a c h c a r d c a n c o n t a i n a n y n u m b e r of c om p o n en t s. T o c r e a t e a c a r d a p a n e l wi l l b e u se d . W h e n ev e r a c a r d i s se l e c t e d b y t h e u se r , t h e c o m p o n e n t s o f t h a t c a r d wi l l b e sh o wn o n the applet. W hi l e a d d i n g a c a r d , t o t h e c a r d l a y o u t we sh o u l d p r o v i d e a n am e f o r e a c h c a r d . T h i s n am e sh o u l d b e u se d t o b r i n g t h a t c a rd t o t h e f r o n t . / / F i l e n am e : cardlay.java

i m p o r t j av a. a wt . * ; i m p o r t j av a. a p p l e t . * ; i m p o r t j av a. a wt . ev e n t . * ; / / D e si g n i n g c a r d s c l a ss f i r st c a r d ex t e n d s P a n e l { f i r st c a r d ( ) { se t B a c k g r o u n d ( C o l o r . p i n k) ; se t L a y o u t ( n e w F l o wL a y o u t ( ) ) ; add(new Tex tFi el d(25)); add(new Tex tFi el d(25)); add(new Tex tFi el d(25)); } } c l a ss se c o n d c a r d e x t e n d s P a n e l { se c o n d c a r d ( ) { se t B a c k g r o u n d ( C o l o r . o r a n g e ) ; se t L a y o u t ( n e w G r i d L a y o u t ( 2 , 2 , 1 0, 1 0 ) ) ; add(new add(new add(new add(new T e x t A r e a ( ) ); T e x t A r e a ( ) ); T e x t A r e a ( ) ); T e x t A r e a ( ) );

Out Put :
E:\Core> javac cardlay.java E:\Core> appletviewer cardlay.html

} } c l a ss t h i r d c a r d ex t e n d s P a n e l { thirdcard() {
145 SATEESH N

SATEESH N

se t B a c k g r o u n d ( C o l o r . r e d ) ; se t L a y o u t ( n e w B o r d e r L a y o u t ( ) ) ; S c r ol l b a r s1 = n e w S c r o l l b a r ( S c r ol l b a r . H O R I Z O N T A L ) ; S c r ol l b a r s2 = n e w S c r o l l b a r ( S c r ol l b a r . V E R T I C A L ); a d d ( s1 , B o r d e r L a y o u t . S O U T H ); a d d ( s2 , B o r d e r L a y o u t . E A S T ); } } p u b l i c c l a ss c a r d l a y ex t e n d s A p p l e t i m pl em e n t s A c t i o n L i st e n e r { P a n el p 1 = n e w P a n e l ( ) ; P a n el p 2 = n e w P a n e l ( ) ; f i r st c a r d f c = n e w f i r st c a r d ( ) ; se c o n d c a r d sc = n e w se c o n d c a r d ( ) ; thirdcard tc = new thirdcard(); B ut t o n b 1 = n e w B u t t o n ( "S h o w f i r st " ) ; B ut t o n b 2 = n e w B u t t o n ( "S h o w se c o n d " ) ; B ut t o n b 3 = n e w B u t t o n ( "S h o w t h i r d " ) ; CardLayout myLayout = new CardLayout(); p u bl i c v oi d i n i t ( ) { se t L a y o u t ( n e w B o r d e r L a y o u t ( ) ) ; se t F o n t ( n e w F o n t ( "S a n ss e r i f " , F o n t . B O LD , 1 4 ) ) ; a d d ( p 2 , B o r d e r L a y o u t . C E NT E R ) ; a d d ( p 1 , B o r d e r L a y o u t . SO U T H ); p 1 . se t L a y o u t ( n e w G r i d L a y o u t ( 1 , 3 ) ); p1.add(b1); p1.add(b2); p1.add(b3); b 1 . a d d A ct i o n Li st e n e r ( t h i s) ; b 2 . a d d A ct i o n Li st e n e r ( t h i s) ; b 3 . a d d A ct i o n Li st e n e r ( t h i s) ; p 2 . se t L a y o u t (m y L a y o u t ); p 2 . a d d (f c, " c a r d o n e " ); / / n am e f o r t h e ca r d p 2 . a d d ( sc , " c a r d t wo " ) ; p 2 . a d d ( t c, " c a r d t h r e e " ) ; } p u bl i c v oi d a c t i o n P e rf o rm e d (A c t i o n Ev e n t e ) { if ( e.getSource() == b1 ) { m y L a y o u t . sh o w( p 2 , " c a r d o n e " ) ; } el se i f ( e. g e t S o u r c e ( ) = = b 2 ) { m y L a y o u t . sh o w( p 2 , " c a r d t wo " ) ; }
146 SATEESH N

SATEESH N

e l se i f ( e. g e t S o u r c e ( ) = = b 3 ) { m y L a y o u t . sh o w( p 2 , " c a r d t h r e e" ) ; } } }

G r i d B ag L a y o u t : G r i d B a g L a y o u t i s t h e m o st p o we r f u l l a y o u t t o pl a c e t he c o m p o n e n t s a t t h e r e q u i r e d l o c a t i o n s. T h e l a y o u t u se s a h e l p e r c l a ss ( t h a t i s G r i d B ag c o n st r a i n t s ) f o r pl a ci n g t h e c om p o n e n t s. G r i dB a g c o n st r a i n t i s c o n t ai n i n g som e v a ri ab l e s. They are i. int ii. int iii .i nt iv. int g r di x ; g ri d y ; g r i d wi d t h ; g r i d h ei g h t ;

I n t h e G r i d B a g L a y o u t t h e t o t a l a r e a i s d i v i d e d i n t o r o ws a n d c o l u m n s. W h e n ev e r we wa n t t o a d d a c o m p o n e n t , t h e l o c a t i o n a n d t h e d i m e n si o n s o f t h a t c om p o n e n t sh o u l d b e sp e c i f i e d u si n g t h e g r i d b a g c o nst r a i n t s a n d t h e n t h e c o m p o n e n t sh o u l d b e a d d e d . E a c h c om p o n e n t c a n o c c u p y m o r e t h a n o n e c e l l .

Sno Address Tfee Course
0 0 1 1

Sname

fpaid save save
2 3 4 5

Sno Address Tfee Course

Sname

2 3

fpaid save save

/ / F i l e n am e :

g r i d b ag . j a v a

i m p o r t j av a. a wt . * ; i m p o r t j av a. a p p l e t . * ; i m p o r t j av a. a wt . ev e n t . * ; p u b l i c c l a ss g r i d b a g ex t e n d s A p p l e t { L a b e l l sn o = n e w L a b e l ( " S n o " ); L a b e l l sn a m e = n e w L a b e l ( " S n a m e " ); L a b e l l a d d r e ss = n e w L a b e l ( " A d d r e s s" ) ;
147 SATEESH N

SATEESH N

L a b e l l t f e e = n e w L a b e l ( " T o t F e e " ); L a b e l l f p ai d = n e w L a b e l ( " F e e p ai d " ) ; L a b e l l c o u r se = n e w L a b e l ( " C o u r se " ) ; T ex t F i el d T ex t F i el d T ex t F i el d T ex t F i el d T ex t F i el d sn o = n e w T ex t F i e l d ( 1 0 ) ; sn a m e = n e w T ex t F i e l d ( 3 0 ) ; a d d r e ss = n e w T e x t F i e l d ( 5 0 ) ; t f e e = n e w T ex t F i el d ( 2 0 ) ; f p ai d = n e w T ex t F i el d ( 2 0 ) ;

C h o i c e c o u r se = n e w C h o i c e ( ) ; B u t t o n b 1 = n e w B u t t o n ( " S av e " ); Gri dBagLayout gb = new Gri dBagLayout(); G r i d B a g C o n st r a i n t s g c = n e w G ri d B a g C o n st r a i n t s( ) ; p u b l i c v oi d i ni t ( ) { se t L a y o u t ( g b ) ; g c . f i l l = G ri d B a g C o n st r a i n t s. B O T H ; / / a d d i n g l sn o g c . g ri dx = 0; g c . g ri d y = 0; g c . g ri d wi d t h = 1 ; g c . g ri d h e i g h t = 1 ; g b . se t C o n st r a i n t s( l sn o , g c ) ; a d d ( l sn o ) ; / / a d d i n g sn o g c . g ri dx = 1; g b . se t C o n st r a i n t s( sn o , g c ) ; a d d ( sn o ) ; / / a d d i n g l sn a m e g c . g ri dx = 2; g b . se t C o n st r a i n t s( l sn a m e , g c ) ; a d d ( l sn a m e ); / / f o r sn a m e g c . g ri dx = 3; g c . g ri d wi d t h = 3 ; g b . se t C o n st r a i n t s( sn a m e , g c ); a d d ( sn a m e ) ; / / a d d i n g l a d d r e ss g c . g ri dx = 0; g c . g ri d y = 1; g c . g ri d wi d t h = 1 ; g b . se t C o n st r a i n t s( l a d d r e s s, g c ) ; a d d ( l a d d r e ss) ;

Out Put :
E:\Core> javac gridbag.java E:\Core> appletviewer gridbag.html

148

SATEESH N

g c . g c . g c ) . g ri dx = 3. g ri dx = 1. g b . a d d ( " J av a " ). g c . a d d ( " P o we r B u i l d e r " ) . } } 149 SATEESH N . g b . g ri d wi d t h = 2 . g c . g c . g b . g ri d y = 2. se t C o n st r a i n t s( b 1 . g c ) . g c ) . se t C o n st r a i n t s( f p a i d. a d d ( a d d r e s s) . g c . g ri dx = 1. c o u r se . g ri dx = 4. g c ). a d d ( " V i su a l B a si c " ). a d d ( l c o u r se ) . g ri dx = 0. / / f o r c o u r se g c . a d d (f p a i d ). a d d ( c o u r se ) . g ri d wi d t h = 1 . / / a d d i n g l c o u r se g c . g ri d wi d t h = 1 . g b . g c ) . g b . se t C o n st r a i n t s( t f e e . g ri d wi d t h = 2 . g c . / / f o r f p ai d g c . se t C o n st r a i n t s( a d d r e s s.SATEESH N / / f o r a d d r e ss g c . g c ) . g ri dx = 1. g ri d y = 3. a d d ( l f p ai d ) . g b . g ri dx = 0. g c . add(tf ee). se t C o n st r a i n t s( c o u r se . g b . c o u r se . g ri d wi d t h = 2 . se t C o n st r a i n t s( l t f e e . g c ) . / / a d d i n g l f p ai d g c . se t C o n st r a i n t s( l f p a i d. g ri d wi d t h = 5 . g c . se t C o n st r a i n t s( l c o u r se . g ri d wi d t h = 1 . // f or tf ee g c . c o u r se . g ri dx = 4. add(b1). add(ltf ee). g b . g c ) . g ri d wi d t h = 3 . // addi ng l tfee g c . g c . // f or b1 g c .

i m p o r t j av a. f r am e ( S t ri n g t i t l e ) : Methods : v oi d se t T i t l e ( S t ri n g n e wT i t l e ) : S t ri n g g e t T i t l e ( ) : 150 SATEESH N . y .html b 1 . b u t t o n s. h e i g h t Out Put : E:\Core> javac nulltest. 7 5 . A f r am e c o n t a i ni n g t h e f ol l o wi n g f e a t u r e s : i.SATEESH N N U L L L a yo u t : I f t h e l a y o u t i s sa i d t o n u l l we sh o u l d sp e c i f y t h e l o c a t i o n a n d t h e d i m e n si o n of t h e c om p o n e n t s wh i l e a d d i n g . a p p l e t . se t B o u n d s( 2 1 0 . se t L a y o u t ( n u l l ) . 1 5 0 . Contains a m enu bar. wi d t h . 5 0 ). / / F i l e n am e : n u l l t e s t . p u bl i c v oi d i n i t ( ) { b 1 = n e w B u t t o n ( "F i r st B u t t o n " ) . a wt . iii. C o n st r u c t o r s : f r am e ( ) : C r e a t e s a f r am e . se t L o c a t i o n ( 5 0 . j a v a i m p o r t j av a. * . b 1 . p u b l i c c l a ss n u l l t e st ex t e n d s A p p l e t { B ut t o n b 1 . se t Si z e ( 1 5 0 . b 2 . T h e f r am e c o n t a i n s t i t l e b a r. * .y / / wi d t h . h e i g h t F r a me s : A f r am e i s a c o n t ai n e r wh i c h i s u se d f o r d i sp l a yi n g t h e c om p o n e n t s i n a se p a r a t e wi n d o w. m ax i m um . c r e a t e a cl a ss t h a t e x t e nd s t h e f r am e cl a ss. m i ni m i z e .java E:\Core> appletviewer nulltest. ii. 4 0 ) . b 2 . C o n t a i n s r e si z a b l e b o r d e r s. 4 0 ) . / / R em ov e t h e c u r r e n t L a y o u t //x. b 2 = n e w B u t t o n ( " S e c o n d B u t t o n " ). add(b1). add(b2). } } / / x . T o c r e a t e a f r am e.

151 SATEESH N . 1 5 0 ) . se t Si z e ( 2 0 0 . M y F r am e( ) { se t T i t l e ( " S am pl e F r am e 2 ") . cy a n ) . } } p u b l i c c l a ss f r am e t e st 1 ex t e n d s A p p l e t i m pl e m e n t s A ct i o n Li st e n e r { B ut t o n b 1 . a p p l e t . * . se t Vi si b l e (f al se ) . i m p o r t j av a.html i m p o r t j av a. i m p o r t j av a. se t B a c k g r o u n d ( C o l o r . p u bl i c v oi d i n i t ( ) { se t B a c k g r o u n d ( C o l o r . pi n k ) . i m p o r t j av a. * . a wt . b 1 . g e t S o u r c e ( ) = = b 2 ) f .SATEESH N / / F i l e n am e : frametest1. a wt . a wt . b 2 . * . ev e n t . add(b1). a wt . * . b 1 = n e w B u t t o n ( " S h o w F r am e " ). Out Put : M y F r am e f .java E:\Core> appletviewer frametest1. i m p o r t j av a.java i m p o r t j av a. se t V i si bl e ( t r u e ) . c l a ss M y F r am e ex t e n d s F r am e i m p l em e n t s A c t i o n L i st e n e r { B ut t o n b 1 = n e w B u t t o n ( "Ex i t P r o g r am " ) . a p p l e t . el se i f ( e. b 2 = n e w B u t t o n ( " Hi d e F r am e " ) . se t Si z e ( 3 0 0 . f = n e w M y F r am e () . b 2 . * . } } / / F i l e n am e : frametest2.java E:\Core> javac frametest1. a d d A ct i o n Li st e n e r ( t h i s) . a d d A ct i o n Li st e n e r ( t h i s) . add(b2).getSource() == b1 ) f . } p u bl i c v oi d a c t i o n P e rf o rm e d (A c t i o n Ev e n t e ) { if ( e. 2 0 0 ) . ev e n t . c l a ss M y F r am e ex t e n d s F r am e { M yF r am e ( ) { se t T i t l e ( " S am pl e F r am e " ). * .

java E:\Core> java frametest2 Handling a Frame : T o h a n d l e a f r am e t h e W i n d o wL i st e n e r wi l l b e u se d . } } } p u b l i c c l a ss f r am e t e st 2 ex t e n d s A p p l e t { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { M yF r am e f = n e w M yF r am e ( ) . ex i t ( 0 ). f . ev e n t . se t S i z e ( 3 0 0 . add(b1).SATEESH N se t B a c k g r o u n d ( C o l o r . 1. 6. p u b l i c v o i d wi n d o wC l o si n g ( W i n d o wEv e n t e ) : T h i s e v e nt wi l l b e c a l l e d w h e n ev e r t h e u se r c l i c k s o n t h e c l o se B u t t o n of t h e wi n d o w. 2 0 0 ) . a wt . } p u bl i c v oi d a c t i o n P e rf o rm e d (A c t i o n Ev e n t e ) { i f ( e. se t V i si bl e ( t r u e ) . 2. 7. se t L a y o u t ( n e w F l o wL a y o u t ( ) ) . p u b l i c v o i d wi n d o wC l o se d ( W i n d o wEv e n t e ) : Af t e r t h e wi n d o w w a s c l o se d . b 1 . p u b l i c v o i d wi n d o wD e i c o n i f i e d (W i n d o wEv e nt e ) : Af t e r t h e wi n d o w wa s r e st o r e d . a d d A ct i o n Li st e n e r ( t h i s) . p u b l i c v o i d wi n d o wO p e n e d ( W i n d o wEv e n t e ) : Af t e r t h e wi n d o w wa s o p e n e d . / / F i l e n am e : f r a m e t e s t 3 . p u b l i c v o i d wi n d o wA c t i v at e d ( W i n d o wEv e n t e ) : p u b l i c v o i d wi n d o wD e a c t i v a t e d ( W i n d o wEv en t e ) : p u b l i c v o i d wi n d o wI c o n i f i e d (W i n d o wEv e n t e) : W h e n ev e r t h e wi n d o w i s m i n i m i z e d . i m p o r t j av a. / / sh o w t h e f r am e } } Out Put : E:\Core> javac frametest2. i o. j a v a / / ov e r ri d e al l t h e m e t h o d s o f W i n d o wL i st e n e r i m p o r t j av a. * . * . 3. 4. pi n k ) . se t B a c k g r o u n d ( C o l o r . i m p o r t j av a. * . 5. 152 SATEESH N . W h i c h i s c o n t a i n i n g t h e f ol l o wi n g 7 m e t h o d s. S y st em . p i n k ). g e t S o u r c e ( ) = = b 1 ) { se t Vi si b l e (f a l se ) . c l a ss M y F r am e ex t e n d s F r am e i m p l em e n t s W i n d o wL i st e n e r { M y F r am e( ) { se t T i t l e (" S am pl e F r am e 3 ") . a wt .

} } w i n d o w Ad a p t e r : wi n d o wA d a p t e r i s a c l a s s a v ai l a b l e i n t h e j av a. 153 SATEESH N Out Put : E:\Core> javac frametest3. T h i s f e a t u r e i s i m p l em e nt s f r om j d k 1 . W h e n we c r e a t e a c l a s s t h a t e x t e n d s t h e wi n d o w a d a p t e r c l a ss we c a n ov e r ri d e o n l y t h e r e q u i r e d m et h o d s. 2 o n w a r d s. se t B o u n d s( 1 0 0 . } / / ov e r ri d i n g al l t h e 7 m e t h o d s of W i n d o wL i st e n e r p u b l i c v o i d wi n d o wC l o se d (W i n d o wE v e n t e ) { } p u b l i c v o i d wi n d o wC l o si n g (W i n d o wEv e n t e ) { se t V i si bl e (f al se ) . f .SATEESH N a d dW i n d o wL i st e n e r ( t h i s) .java E:\Core> java frametest3 . S y st em . 1 0 0 . 2 0 0 ) . a wt p a c k a g e wh i c h i m pl em e n t s t h e wi n d o wL i st e n e r i n t e r f a c e a n d o v e r ri d e s a l l i t s m e t h o d s wi t h o u t a n y st a t e m e n t s. se t V i si bl e ( t r u e ). } p u b l i c v o i d wi n d o wO p e n e d (W i n d o wEv e n t e ) { } p u b l i c v o i d wi n d o wA c t i v at e d (W i n d o wEv e n t e ) { } p u b l i c v o i d wi n d o wD e a c t i v a t e d (W i n d o wEv en t e ) { } p u b l i c v o i d wi n d o wI c o n i f i e d (W i n d o wEv e n t e) { } p u b l i c v o i d wi n d o wD e i c o n i f i e d (W i n d o wEv e nt e ) { } } c l a ss f r am e t e st 3 { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { My F r am e f = n e w M y F r am e ( ) . 3 0 0 . ex i t ( 0 ) . f .

a t t h e t i m e of c r e a t i n g t h e i n t e rf a c e of t h e cl a ss. * . * . } } } Out Put : E:\Core> javac frametest4. pi n k ) . i m p o r t j av a. M o u se L i st e n e r . * . a d dW i n d o wL i st e n e r ( n e w M yW i n d o wA d a p t e r ( ) ) . f . a wt . c l a ss M y F r am e ex t e n d s F r am e { M y F r am e( ) { 154 SATEESH N . i m p o r t j av a. i m p o r t j av a. / / F i l e n am e : frametest5. . se t B a c k g r o u n d ( C o l o r . A n on y m ou s c l a s se s : A n a n o n y m o u s c l a s s i s a c l a s s wh i c h a l l o ws u s t o o v e r ri d e a m et h o d of a c l a ss a t t h e t i m e of c r e a t i n g a n i n st a n c e of t h e cl a ss. se t Si z e ( 3 0 0 . 2 0 0 ) . wh i c h a r e c o n t a i n i n g m o r e t h a n o n e m et h o d s t h e c o r r e sp o n d i n g a d a p t e r c l a ss e s a l s o av ai l a bl e . a wt .java i m p o r t j av a. ev e n t .java i m p o r t j av a.SATEESH N / / F i l e n am e : frametest4. / / sh o w t h e f r am e } } S i m i l a r l y t h e i nt e rf a c e s l i k e F o c u sL i st e n e r . Ac t i o n L i s t en e r : T hi s i s a cl a ss wh i c h a l l o w s u s t o ov e r ri d e t h e m et h o d s o f t h e cl a ss . } cl a ss M yW i n d o wA d a p t e r e x t e n d s W i n d o wA d a p t e r // inner { p u b l i c v o i d wi n d o wC l o si n g (W i n d o wEv e n t e ) { se t Vi si b l e (f a l se ) . a p p l e t . K e y L i st e n e r e t c . se t V i si bl e ( t r u e ) . S y st em .java E:\Core> java frametest4 c l a ss f r am e t e st 4 { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { M yF r am e f = n e w M yF r am e ( ) . a wt . c l a ss M y F r am e ex t e n d s F r am e { M y F r am e( ) { se t T i t l e ( " S am pl e F r am e 4 ") . * . * . ev e n t . a wt . ex i t ( 0 ).

html C h ec k b ox b 1 . ex i t ( 0 ) . B O LD . state changed } } 155 SATEESH N . i m p o r t j av a. 5 0 .java E:\Core> appletviewer buttonchkbox. } } ). j a v a i m p o r t j av a. a wt . } } / / F i l e n am e : b u t t o n c h kb o x. p u b l i c v oi d i ni t ( ) { se t F o n t ( n e w F o n t ( "S a n ss e r i f " . c b 1 . Out Put : Sy st e m . a wt . C h e c k b ox c b 1 = n e w C h e c k b o x ( "S am p l e Ch e c k b o x " ).SATEESH N se t B o u n d s( 5 0 . E:\Core> java frametest5 } } c l a ss f r am e t e st 5 { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { M yF r am e f = n e w M y F r am e ( ). a d dW i n d o wL i st e n e r ( n e w W i n d o wA d a p t e r ( ) { p u b l i c v o i d wi n d o wC l o si n g (W i n d o wEv e n t e ) { se t Vi si b l e (f al se ) . a d d A ct i o n Li st e n e r ( n e w A c t i o n Li st e n e r ( ) { p u b l i c v oi d a ct i o n P e rf o r m e d ( A ct i o n Ev e nt e ) { sh o wS t a t u s( " F i r st B ut t o n Cl i c k e d " ) . * . 1 4 ) ) . f . p u b l i c c l a ss b u t t o n c h k b o x ex t e n d s A p p l e t { B u t t o n b 1 = n e w B u t t o n ( " F i r st B u t t o n " ). * . se t T i t l e (" S am pl e F r am e 5 " ) . a d d I t em Li st e n e r ( n e w I t em Li st e n e r ( ) { p u bl i c v oi d i t em St a t e Ch a n g e d ( I t e m Ev e nt e ) { sh o wS t a t u s( " C h e c k b o x S t a t e C h a n g e d " ) . F o n t . p i n k ). add(cb1). se t B a c k g r o u n d ( C o l o r . Out Put : E:\Core> javac buttonchkbox. se t Vi si b l e (t r u e ) . a p p l e t . * . } } ).java } ). add(b1). } E:\Core> javac frametest5. i m p o r t j av a. ev e n t . 3 0 0 . 2 0 0 ) .

SATEESH N / / F i l e n am e : g e t f o n t l i s t . a wt . T h e f ol l o wi n g cl a sse s wi l l b e u se d b y d e si g n i n g m e n u s. setVisible(true) . * . f . p r i nt l n ( "S u p p o r t e d f o n t n am e s " ) . / / T o ol Ki t i s av ai l a bl e i n c o n t ai n e r s S t ri n g a r r[ ] = t k. j a v a / / t o v i e w t h e av ai l a b l e f o n t s i n j av a i m p o r t j av a. o u t . o u t . g e t F o n t Li st ( ) . Menu Bar Menu M e n u I t em C h e c k b o x M e n u I t em PopupMenu MenuShortcut A m e n u c a n c o n t ai n t h e f ol l o wi n g i t em s. l e n g t h . i m p o r t j av a. T o ol k i t t k = g et T o o l k i t ( ) . M e n u I t em s C h e c b o x M e n ui t em s Separators M e n u s ( su b m e n u s ) A M e n u I t em sh o u l d b e h a n d l e d u si n g t h e A c t i o n L i st e n e r i n t e rf ac e a n d a C h e c k b o x M e n u I t em sh o u l d b e u si n g t h e I t em Li st e n e r i n t e rf a c e. * . i + + ) { S y st em . } } Out Put : E:\Core> javac getfontlist. c l a ss M y F r am e ex t e n d s F r am e { M yF r am e ( ) { se t T i t l e ("f o n t d em o " ) . p ri n t l n ( a r r [ i ] ). S y st em . i m p o r t j av a. a wt . f o r (i n t i = 0 . * . ev e n t . i < a r r.java E:\Core> java getfontlist Supported font names Dialog SansSerif Serif Monospaced DialogInput M e n u s : A f r am e c o n t ai n s m e n u b a r . i o. } } } class getfontlist { public static void main(String args[ ] ) { MyFrame f = new MyFrame( ) . 156 SATEESH N .

se t B o u n d s( 1 0 0 . se t Vi si b l e (t r u e ) . m b a r . / / t r u e : c t rl + sh i f t + O o p t sav e = n e w M e n u I t em ( " sav e" ) . a d d ( o p t n e w) . i m p o r t j av a. C h e c k b ox M e n u I t em o p t a u t o sav e = n e w C h e c k b o x M e n u I t em ( " A u t o S av e " ) . f i l e. o p t v e r t = n e w M e n u I t em ( " V e r t i c al " ). n e w M e n u S h o r t c u t ( ' O '. M e n u t i l e = n e w M e n u ( " T i l e " ). ev e n t . M e n u I t em o pt n e w. a d d ( o p t e x i t ) . n e w M e n u S h o r t c u t ( ' N ' . a d d (f i l e ) . 157 SATEESH N Out Put : E:\Core> javac menutest. f i l e. f . // add the m enu bar se t M e n u B a r ( m b a r ).java E:\Core> java menutest . o p t v e rt . I t em Li st e n e r { T ex t Ar e a t 1 = n e w T ex t A r e a ( ) . o p t h o r z . a d d ( o p t c a sc a d e ) . M y F r am e( ) { se t F o n t ( n e w F o n t ( " S a n se r i f " . a d d ( wi n d o w) . o p t c a sc a d e = n e w M e n u I t em ( " c a sc a d e " ) . a d d ( o p t o p e n ) . add(t1). MenuBar m bar = new MenuBar(). f i l e. f al se ) ) . } } c l a ss M y F r am e ex t e n d s F r am e i m p l em e n t s A c t i o n L i st e n e r . wi n d o w. a d d ( o p t sav e ) . a wt . a d d ( o p t a u t o sav e ) . o p t n e w = n e w M e n u I t em ( " n e w" . p u b l i c c l a ss m e n u t e st ex t e n d s A p p l e t { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { M yF r am e f = n e w M y F r am e ( ). wi n d o w.SATEESH N / / f i l e n am e : m en u t e s t. f i l e. f . o p t ex i t = n e w M e n u I t em ( " ex i t " ) . * . f i l e. j a v a i m p o r t j av a. 3 0 0 . a d d ( t i l e ) . o p t c a sc a d e . i m p o r t j av a. o p t ex i t . a p p l e t . * . M e n u wi n d o w = n e w M e n u ( "W i n d o w" ) . o p t o p e n . * . m b a r . 1 0 0 . t r u e ) ). BO LD . F o n t . o p t sa v e . a d d S e p a r a t o r ( ) . / / f al se : ct rl + N o p t o p e n = n e w M e n u I t em (" o p e n " . M e n u f i l e = n e w M e n u ( " F i l e " ). 2 0 0 ) . 1 4 ) ) . a wt . f i l e. o p t h o r z = n e w M e n u I t em ( " H o ri z o n t al " ) .

S y st em . p u b l i c v o i d K e y T y p e d ( K e y Ev e nt e ) : B o t h d o w n a n d u p . } e l se { t 1 . } } KeyListener : K e y L i st e n e r i s u se d f o r h a nd l i n g k e y ev e nt s.SATEESH N t i l e. a d d A c t i o n L i st e n e r ( t hi s) . p u b l i c v o i d K e y R e l e a se d ( K e y Ev e n t e ) : W h e n e v e r t h e k e y i s d o wn . o p t sav e . o p t o p e n . el se t 1 . se t T ex t ( " A u t o S av e : C HE C K E D O N ") . } } p u bl i c v oi d i t em St a t e C h a n g e d ( I t em Ev e n t e ) { i f ( o pt a u t o sav e . g e t A ct i o n C o m m an d ( ) + " se l e c t e d " ). se t T ex t ( e . a d d A c t i o n L i st e n e r ( t hi s) . 158 SATEESH N . a d d A c t i o n L i st e n e r ( t hi s) . e l se i f ( e. M o u s eL i s t e n e r : I t i s u se d f o r h a n d l i n g M ou se e v e n t s. o p t v e r t . a d d A c t i o n L i st e n e r ( t h i s) . g e t S o u r c e ( ) = = o p t ex i t ) { se t V i si b l e (f a l se ) . a d d A c t i o n Li st e n e r ( t h i s) . p u b l i c v o i d K e y P r e sse d ( K e y Ev e nt e ) : W h e n e v e r t h e k e y i s d o wn . a d d A c t i o n L i st e n e r ( t h i s) . } p u bl i c v oi d a c t i o n P e rf o rm e d (A c t i o n Ev e n t e ) { if ( e. p u b l i c v o i d M o u se R e l e a se d ( M o u se E v e nt e ) : wh e n e v e r t h e m o u se b u t t o n i s u p . a d d ( o p t v er t ). o p t ex i t . o p t c a sc a d e . o p t a u t o sav e . a d d A ct i o n Li st e n e r ( t h i s) . a d d I t em Li st e n e r ( t h i s) . t i l e. K e y Ev e nt : C h a r g e t K e y C h a r ( ) : R e t u r n s t h e c h a r a ct e r t y p e d b y t h e u se r . se t T ex t ( " A u t o S av e : C HE C K E D O F F " ) .getSource() == optnew ) t 1. g e t S o u r c e ( ) = = o p t o p e n ) t 1 . se t T ex t ( " O p e n o p t i o n se l e c t e d" ) . g e t St a t e ( ) = = t r u e ) t 1 . p u b l i c v o i d M o u se P r e s se d ( M o u se Ev e n t e ) : wh e n ev e r t h e m o u se b u t t o n i s d o wn . o p t n e w. o p t h o r z . ex i t ( 0 ). se t T ex t ( " N e w I t em S el e c t e d " ) . el se i f ( e. a d d ( o p t h o r z ) .

SATEESH N p u b l i c v o i d M o u se C l i c k e d ( M o u se Ev e n t e ) : wh e n e v e r t h e m o u se b u t t o n i s d o wn + u p . p u b l i c v o i d M o u se E n t e r e d ( M o u se Ev e n t e ) : M o u se i s e n t e r e d o n a c om p o n e n t i . popup. p o p u p . . a d d M o u se L i st e n e r ( n e w M y M o u se A d a p t e r ( ) ) .java E:\Core> java popuptest to close the applet goto command prompt and click ctrl+c SATEESH N . i m p o r t j av a. a d d ( n e w M e n u I t e m ( "F o u r t h o pt i on " ) ) . ev e n t . p o p u p . . a wt . . p o p u p . add(popup).o r d i n a t e s of t h e m o u se p o i n t e r . M o u se i s ov e r a c om p o n e n t . . t 1 . 159 Out Put : E:\Core> javac popuptest. a wt .addSeparator(). g e t X( ) . i nt y = e. sh i f t al t c t rl e n t er . M o u se E v e n t : i n t g et x ( ) : R e t u r n s t h e c o . p u b l i c v o i d M o u se E x i t e d ( M o u se Ev e n t e ) : M o u se i s o u t of a c om p o n e n t . a d d ( n e w M e n u I t e m ( "S e c o n d o p t i on " ) ) . a d d ( n e w M e n u I t e m ( "F i r st o p t i o n " )) . . e . p o p u p . } cl a ss M y M o u se A d a p t e r e x t e n d s M o u se A d a p t e r { p u b l i c v oi d m o u se P r e ss e d ( M o u s e Ev e n t e ) { i n t x = e . a p p l e t . PopupMenu popup = new PopupMenu(). * . i m p o r t j av a. B U T T O N 1 : l ef t B UT T O N 2 : m i d dl e B UT T O N 3 : ri g h t PopupMenu : A n o r m a l m e n u sh o u l d a l wa y s b e a t t a c h e d t o t h e m e n u b a r wh i l e a p o p u p m e n u c a n b e di sp l a y e d a n y wh e r e o n t h e c om p o n e n t . p o p u p . a d d ( n e w M e n u I t e m ( "F i f t h o p t i o n " )) . c l a ss M y F r am e ex t e n d s F r am e { T ex t Ar e a t 1 = n e w T ex t A r e a ( ) . i n t g et y ( ) : i n t g et M o d i f i e r s : Ex: R e t u r n s t h e b i t p a t t e r n of t h e m o u se k e y s a n d sh i f t k e y s. I f ct rl k e y i s p r e s se d v al u e 1 wi l l b e st o r e d o t h e r wi se 0 wi l l b e st o r e d . * . a d d ( n e w M e n u I t e m ( "T hi r d o p t i o n ") ) . / / F i l e n am e : popuptest.getY(). * . M y F r am e( ) { a d d ( t 1 ).java i m p o r t j av a. o n m l .

A d i al o g wh e n c o m p a r e d wi t h t h e f ra m e i s c o n t ai n i n g t h e f ol l o wi n g di f f e r e n c e. Functi ons : S t ri n g g e t F i l e ( ) : S t ri n g g e t D i r e ct o r y ( ) : / / F i l e n am e : F i l e t e s t . sh o w( t 1 . SA V E : F o r sav e d i al o g . } } Dialog : A d i a l o g i s si m i l a r t o a f r am e use d f o r d i sp l a y i n g i nf o rm at i o n i n a se p a r a t e wi n d o w. F i l e Di a l o g . 160 SATEESH N . i o. i m p o r t j av a. f . A d i al o g c a n b e m o d ul a r o r m o d e l e ss. j a v a E:\Core> javac filetest. } } } } / / e n d of M y F r am e p u b l i c c l a ss p o p u p t e st e x t e n d s A p p l e t { p u b l i c st a t i c v o i d m ai n ( S t ri n g a r g s[ ] ) { M yF r am e f = n e w M y F r am e () . B o o l ea n m o d al ) F i l e Di a l o g : I t d i sp l a y s t h e o p e n o r sav e d i a l o g b ox e s. S t ri n g t i t l e ) D i al o g ( F r am e p a r e n t . St r i n g t i t l e .getModifiers( ) & InputEvent. 3 0 0 . se t V i si b l e (t r u e ) . a wt . LO A D : f o r o p e n D i al o g . * . 2 .BUTTON3_MASK ) == InputEvent. A d i al o g c a n n o t c o n t ai n a m e n u b a r . y ) . 1 0 0 .BUTTON3_MASK ) // in the above statement & is bit-wise operator to verify the bit is ON or OFF { p o p u p . S t ri n g t i t l e . i nt t y p e ) Out Put : F i l e Di a l o g . ev e n t . C o n s t r u c to r : Type: F i l e D i al o g ( F r am e p a r e n t . * . se t B o u n d s( 1 0 0 . 3 . 2 0 0 ) . x . a wt . c l a ss f i l et e st { p u bl i c st a t i c v oi d m ai n ( St r i n g a r g s[ ] ) { M yF r am e f = n e w M y F r am e ( ). A d i al o g sh o u l d a l wa y s b e c r e a t e d f r om a f ra m e o r a f r am e a n o t h e r di a l o g . 1 . f . * .SATEESH N if( ( e. i m p o r t j av a.java E:\Core> java filetest i m p o r t j av a. C o n s t r u c to r : Di a l o g ( F r am e p a r e n t ) D i al o g ( F r am e P a r e n t .

2 ) ) . a d d A c t i o n L i st e n e r ( t h i s) . } } v oi d o p e nf i l e ( ) { try { f d. 1 4 ) ) . se t V i si bl e ( t r u e ) . se t Vi si b l e (t r u e ) . LO A D ). F o n t . i n t f i l e si z e = ( i nt ) f . b 2 . f . BO L D .add(b1). / / st a r t i n g p o st i o n 161 SATEESH N . B o r d e r L a y o u t . se t L a y o u t ( n e w G r i d L a y o u t ( 1 . 1 0 0 . i f ( d i r N am e ! = n u l l ) { S t r i n g f i l e n am e = d i r N am e + f d . F i l e D i al o g .SATEESH N f . 3 0 0 ) . a d d ( p 1 . b 1 . B u t t o n b 2 = n e w B u t t o n ( " Ex i t P r o g r am ") . F i l e f = n e w F i l e (f i l e n am e ) . M yF r am e ( ) { se t F o n t ( n e w F o n t ( " A ri al N a r r o w" . F i l e D i al o g f d = n e w F i l e D i al o g ( t hi s. S y st em . } } c l a ss M y F r am e ex t e n d s F r am e i m p l em e n t s A c t i o n L i st e n e r { T ex t A r e a t 1 = n e w T ex t A r e a ( ). SO U T H ) . C E NT E R ). g e t S o u r c e ( ) = = b 2 ) { se t V i si b l e (f a l se ) .add(b2). p 1 . a d d A c t i o n L i st e n e r ( t h i s) . a d d ( t 1 . Panel p1 = new Panel(). g e t F i l e ( ) . p1. B u t t o n b 1 = n e w B u t t o n ( "O p e n F i l e" ) . / / di pl a y t h e f i l e d i a l o g St r i n g d i r N am e = f d . l e n g t h ( ) . p1. g e t S o u r c e ( ) = = b 1 ) o p e nf i l e ( ) . B o r d e r L a y o u t . 4 0 0 . se t B o u n d s( 1 0 0 . } p u b l i c v oi d a ct i o n P e rf o rm e d ( A ct i o n Ev e nt e) { i f ( e. ex i t ( 0 ). g e t Di r e ct o r y ( ) . " S e l e ct F i l e" . / / n o . e l se i f ( e . of c h a r a c t e r s i n t st a r t = 0 .

r e a d ( a r r. se t T i t l e ( " " ).SATEESH N // open the fil e F i l e I n p u t St r e am f i n = n e w F i l e I n p u t St r e a m (f i l e n am e ) . } / / e n d of i f } c at c h ( Ex c e p t i o n ex ) { t 1. / / r e a d al l t h e / / p u t t h e r e a d d a t a. f i n . cl o se ( ) . / / R e a d al l t h e c h a r a ct e r i n t o t h e b uf f e r b y t e a r r [ ] = n e w b y t e [ f i l e si z e ] . st a r t . t 1 t 1. f i n . } } } / / e n d of M yF r am e c l a ss 162 SATEESH N . se t T i t l e (f i l e n a m e ). f i l e si z e ) . se t T ex t ( n e w S t ri n g ( a r r ) ) . se t T ex t ( "E r r o r : "+ ex ) .

In order to connect from a java program to the backend database a special program is required which is known as a driver.jdbc. to perform Database transactions. Class : Interfaces : DriverManager 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. Java Application JdbcOdbcBridge Driver Microsoft ODBC Data Base java. class Class : static Class forName( String class-name ) throws ClassNotFoundException Ex: Class. DriverName : JdbcOdbcBridge. which is of the type1 driver. Driver class name Getting a Connection with the Database : The following methods of DriverManager class can be used for opening connections with the database. SQL server etc. Data Base Java Program Driver The drivers are divided into 4 categories named as type1. type2. The following driver will be installed with jdk.odbc.JdbcOdbcDriver” ). type4. type3. 163 SATEESH N .SATEESH N This feature of Java allows a java program to connect with the backend database such as oracle. The above driver uses Microsoft ODBC to connect with the data bases.forName( “sun.sql package : This containing the following interfaces and classes for managing database transactions..

Creating a Data Source Name (DSN) : In the control panel ODBC in the userDSN . System..close( ). System. public static Connection getConnection( String url ) throws SQLException 2. Connection con = DriverManager.println("Driver Name : "+dbmd.out. Methods : Statement createStatement( ) throws SQLException : Creates a statement. System. System.out.out... for ex.out..out.getMetaData( ).getDriverName( )).println("Driver Not Loaded").out. ").java import java. A statement is used for executing SQL statements against the database..odbc. click on Finish button and specify a name for the data source.. Javaoracle // File name : testcon.*.println(" OK "). Class.println(" OK").print("Closing Connection.jdbc. } catch(ClassNotFoundException ex) { System. “ javaoracle “ is the data source name created in the control panel. System. String uname. PreparedStatement prepareStatement ( String sql statement ) throws SQLException : prepareStatement takes a query and compiles the query. public static Connection getConnection( String url. } } } Connection Interface : Manages a connection with the database.print("Getting Connection . click on the ADD button. "). for ex. which displays a list of the installed drivers select the required driver. con.println("SQL Error: "+ex).out. ”scott”. It can be used for executing any number of times of compiled query.println(" OK ")..JdbcOdbcDriver").getConnection("jdbc:odbc:javaoracle".out.getDatabaseProductName( )). 164 SATEESH N . “ scott “ is user name ."scott". “tiger” ).out...forName("sun. class testcon { public static void main(String args[ ]) { try { System. MicrosoftODBC for oracle.sql.getConnection( “jdbc:odbc:javaoracle”..SATEESH N 1. } catch(SQLException ex) { System..print("Loading Driver .out. “ tiger “ is the password .println("Database Name: "+dbmd."tiger"). DatabaseMetaData dbmd = con."). System. String pwd ) throws SQLException Ex : Connection con = DriverManager. System.

Field number starts from 1 . int getUpdateCount( ) : Returns the number of records that are effected in the last execution. The ResultSet contains the pointer which by default position at the first record. Contains the results of the result set. Statement : For executing the SQL statements against the database. ResultSetMetaData getMetaData( ) : resultset. DatabaseMetaData getMetaData( ) : connection. void rollback( ) : Moves cursor to the last saved position. returns true if a select statement is executed. void close( ) : Closes the statement. it returns false for a non-select statement. void setAutoCommit( Boolean autocommit ) : Sets on or off the auto commit. which contains the details of the ResultSetMetaData : int getColumnCount( ) : String getColumnLabel( int field no ) : 165 SATEESH N . void close ( ) : Closes the connection. Methods : ResultSet executeQuery( String select-statement ) : result set which contains the selected records. void close( ) : Closes the result set. which is used for executing stored procedures of the database. Executes the given select statement and returns the Returns the DatabaseMetaData which contains the details of the int executeUpdate( String dml-statement ) : Executes the given dml statement and returns the no. int getInt( int fieldno ) : Returns the value of the specified field. of records that are effected from the execution. ResultSet : Contains the selected records from the database. Returns the label of the specified column. Returns the ResultSetMetaData. Returns the number of selected fields. ResultSet getResultSet( ) : Returns the result set.SATEESH N CallableStatement prepareCall ( String sql statement ) : Prepares a callable statement. void commit( ) : Makes the changes permanent. boolean execute( String sql-statement ) : Executes any SQL statement. 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. default is true.

class getrecords { public static void main(String args[]) { try { System.").executeQuery("select * from emp"). System. int deptno = rs. Connection con = DriverManager..SATEESH N // File name : getrecords.close()."). } catch(Exception ex) { System.getInt(1).getConnection("jdbc:odbc:javaoracle".forName("sun.").createStatement(). import java.println()."tiger").getString("JOB").out. double sal = rs.jdbc.odbc...println("Loadig Driver . System. String job = rs. } } } 166 SATEESH N .JdbcOdbcDriver").println("Getting Connection. con. // display the resultset while(rs. // create the statement Statement stmt = con."scott".out.out..close()..sql.println("Error: "+ex).out. stmt. Class. // execute the query and get the resultset ResultSet rs = stmt. System.*.out. String ename = rs.println(empno+"\t"+ename+"\t"+job+"\t"+sal+"\t"+deptno).println("EMPNO NAME JOB SAL DEPTNO\n").getDouble(4).getInt("DEPTNO").next()) { int empno = rs.println("Connection Established.io.java // to print the employee details from thel emp table of oracle import java..getString(2).*. } rs.close(). System..out.out. System.

print("\t"+rs.getMetaData(). Connection con = DriverManager.").n.println("Connection Established. } rs.out. } catch(Exception ex) { System.println(). System.executeQuery(query).out.readLine().println("Error: "+ex). // display the resultset while(rs.out.io.println("Getting Connection.in)).SATEESH N // File name : getrecords2.forName("sun.sql. int i. // create the statement Statement stmt = con.out.out.println().getColumnCount().println("Loadig Driver .getString(i))..").out.out. System.*.")."scott"..*.next()) { // for each row for(i=1.java // to execute the given select statement and display the records import java. ResultSetMetaData rm = rs.. String query = stdin.. } System.odbc.out.i<=n.println(). stmt. } } } 167 SATEESH N . n = rm.i++) { System.close(). System.createStatement(). // execute the query and get the resultset ResultSet rs = stmt.close(). Class. class getrecords2 { public static void main(String args[]) { try { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.close()."tiger"). System.. import java. System.print("Enter Query:> ").jdbc...getConnection("jdbc:odbc:javaoracle".JdbcOdbcDriver"). System.out. con.

java // to accept a query & display the fetched records of the query along with the column headings import java. con.getColumnCount(). } } static void displayRecords(ResultSet rs) { try { int i. } catch(Exception ex) { System.. str = stdin. rs.trim(). ResultSet rs = stmt.close().createStatement().close().jdbc.equals("QUIT")) break.readLine().out.println(). class getrecords3 { public static void main(String args[]) { try { BufferedReader stdin = new BufferedReader(new InputStreamReader(System."tiger").").forName("sun.getMetaData().in))."scott".println().. Statement stmt = con.n.out.getConnection("jdbc:odbc:javaoracle".odbc. System. // displaying headings 168 SATEESH N .println("Error: "+ex). Class.*.println("Error: "+ex).out.executeQuery(str).SATEESH N // File name : getrecords3.out.out.JdbcOdbcDriver"). } } stmt. if(str.sql. import java.io. while(true) { try { System.*.toUpperCase()..close(). displayRecords(rs). System. } catch(Exception ex) { System. ResultSetMetaData rsmd = rs. Connection con = DriverManager.println("Getting Connection .out. n = rsmd. String str.print("Query>"). System.

out.out. } System. The methods first. last. The method absolute will move the cursor to the row number indicated in the argument passed to it. System. ResultSet.i<=n. In order to open in a scrollable mode the statement should be created with the following parameters. Statement createStatement( int ResultSetType.println("\t-----------------------------------------"). 3.SATEESH N for(i=1. 169 SATEESH N .. and afterLast move the cursor to the position their names indicate.TYPE_SCROLL_SENSITIVE : The record pointer is scrollable. ResultSet. the cursor moves the given number from the end. } } } Whenever we open the resultset using the executingQuery( ) function the result set will be opened in a forward only mode.i++) { System.out.out. the record pointer can be moved only in the forward direction but not in the backward direction. } System. ResultSet. so calling absolute(-1) puts the cursor on the last row.println().TYPE_SCROLL_INSENSITIVE : The record pointer is scrollable.out. so calling absolute(1) puts the cursor on the first row. } } catch(Exception ex) { System. If the number is positive.print("\t"+rs.getString(i)).next()) { for(i=1. and also effects the ResultSet also effects the client applications.println(). int concurrencyType ) throws SQLException : ResultSetType : 1. // display the record values while(rs.i<=n. i. 2. concurrencyType : 1.CONCUR_UPDATABLE : The values in the ResultSet can be modified. beforeFirst. the cursor moves the given number from the beginning.TYPE_FORWARD_ONLY : The record pointer can be moved only in the forward direction. ResultSet.e.println("Error: "+ex). Moving the Cursor to a Designated Row : You can move the cursor to a particular row in a ResultSet object. ResultSet. but the ResultSet doesn’t effects for the new changes made by the other applications. If the number is negative.getColumnLabel(i)).CONCUR_READ_ONLY : The values in the ResultSet can’t be modified.i++) { System. ( default ) 2.print("\t"+rsmd.out.

f."Deptno"}. boolean absolute( ) : Moves the cursor to the given row number in this ResultSet object. import java. boolean relative( ) : Moves the cursor a relative number of rows.setVisible(true). Button b1.*. class navigaterecords { public static void main(String args[]) { MyFrame f = new MyFrame().*."EName". f. either positive or negative.b4.relative(-3). // rowNum should be 3 // File name : navigaterecords.setTitle("Employee Details"). The method getRow lets you check the number of the row where the cursor is currently positioned. } } class MyFrame extends Frame implements ActionListener { TextField arr[] = new TextField[5]. Connection con.getRow( )."Job".SATEESH N boolean next( ) boolean first( ) boolean last( ) : Moves the record pointer to the next record returns true on success and false on failure.awt.n.getRow( ). ResultSet rs.300). Ex: Getting the Cursor Position : int getRow( ) : Returns the current row number Ex: int rowNum = rs. Ex: int rowNum = rs. boolean previous( ) : Moves the record pointer to the prev record returns true on success and false on failure. String fieldNames[] = {"Emp No".400.sql. 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( ). : Moves the record pointer to the last record returns true on success and false on failure. MyFrame() { 170 SATEESH N .*. f.getRow().b2.absolute(4) . // moves the cursor to the fourth row rs.awt.b3."Sal". : Moves the record pointer to the first record returns true on success and false on failure.event.setBounds(100. Ex: rs.100. // rowNum should be 1 rs. Statement stmt.b5.relative(2). import java. int rowNum = rs.java // to display the employee details in a frame import java. int i.

b4. p1. b5 = new Button("Exit"). b3 = new Button("Next").setLayout(new GridLayout(5. displayRecord(3).add(b5). b2 = new Button("Previous"). add(p1.Font.BorderLayout.addActionListener(this). p2. setLayout(new BorderLayout()). else if(e.getSource() == b5) { closeConnection(). p1.add(new Label(fieldNames[i])).addActionListener(this). setVisible(false). arr[i] = new TextField(). else if(e.add(b1).addActionListener(this).14)). b2. System.exit(0). p2. } b1.BOLD.5)).add(arr[i]).CENTER).add(b4).SOUTH).getSource() == b4) displayRecord(4). else if(e. for(i=0. b1 = new Button("First"). p2.BorderLayout. // display 1st record } public void actionPerformed(ActionEvent e) { if(e.getSource() == b2) displayRecord(2). else if(e. add(p2.setLayout(new GridLayout(1. p2.addActionListener(this).getSource() == b3) displayRecord(3). p2.2)). b5.getSource() == b1) displayRecord(1). Panel p2 = new Panel().addActionListener(this). b4 = new Button("Last").i++) { p1. p2. Panel p1 = new Panel(). b3.SATEESH N setFont(new Font("Sanserif".add(b3). } } 171 SATEESH N .add(b2).i<5. openConnection().

case 3: b = rs.next().i<5.previous().createStatement(ResultSet.last().println("Getting Connection.jdbc.out. con. stmt=con.println("Error: "+ex).first().job. } if(b == true) { for( i=0.CONCUR_READ_ONLY).forName("sun.odbc. try { switch(opt) { case 1: b = rs.JdbcOdbcDriver")."tiger").close().TYPE_SCROLL_INSENSITIVE. } } void displayRecord(int opt) { // move record pointer according to the pm boolean b = false.. break."). } catch(Exception ex) { System.close().SATEESH N void openConnection() { try { System.setText(rs.out.println("Error: "+ex).executeQuery("select empno..sal.i++) { arr[i]. Class.ResultSet. stmt. } } void closeConnection() { try { rs.deptno from emp"). } catch(Exception ex) { System.getConnection("jdbc:odbc:javaoracle". } } } catch(Exception ex) { System. break.ename. Connection con = DriverManager.println("Error: "+ex). break. break.out. case 4: b = rs.close(). rs = stmt.out. } } } 172 SATEESH N . case 2: b = rs.getString(i+1))."scott".

SATEESH N

Making Updates to Updatable Result Sets :

Creating an Updatable Result Set :
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

Updating a Result Set Programmatically : An update is the modification of a column value in the current row. Ex: stmt.executeUpdate("UPDATE EMP SET SAL = 10000 WHERE EMPNO = 7839);

The ResultSet.updateXXX methods generally take two parameters: the column to update and the new value to put in that column. As with the ResultSet.getXXX methods, the parameter designating the column may be either the column name or the column number. There is a different updateXXX method for updating each data type (updateString, updateFloat, updateInt, and so on). To make the update take effect in the database, we must call the ResultSet method updateRow.Suppose that you realize that the update you made is incorrect. You can restore the previous value by calling the cancelRowUpdates method if you call it before you have called the method updateRow. Once you have called updateRow, the method cancelRowUpdates will no longer work. ResultSet rs = stmt.executeQuery(“SELECT * FROM EMP”); rs.last( ); rs.updateFloat("SAL", 6000); rs.cancelRowUpdates( ); rs.updateFloat("SAL", 6000); rs.updateRow( );

Inserting and Deleting Rows Programmatically : Inserting a Row : int n = stmt.executeUpdate("insert into emp(empno,ename,job,sal,deptno) values ("+empno+",'"+ename+"', '"+job+"',"+sal+","+deptno+")" ); we can do the same thing without using any SQL commands by using ResultSet methods. After we have a ResultSet object with results from the table “emp” , we can build the new row and then insert it into both the result set and the table “emp” in one step. We build a new row in what is called the insert row, a special row associated with every ResultSet object. This row is not actually part of the result set; think of it as a separate buffer in which to compose a new row. First step will be to move the cursor to the insert row, which you do by invoking the method moveToInsertRow . The next step is to set a value for each column in the row. By calling the appropriate updateXXX method for each value. Finally, we call the method insertRow to insert the row you have just populated with values into the result set.

173

SATEESH N

SATEESH N

Ex: rs = stmt.executeQuery("select empno,ename,job,sal,deptno from emp"); rs.moveToInsertRow( ); rs.updateInt("EMPNO", 111); rs.updateString("ENAME", “Sateesh”); rs.updateString("JOB", “Analyst”); rs.updateFloat("SAL",7500); rs.updateInt("DEPTNO", 20); rs.insertRow( ); [ OR ] rs.moveToInsertRow( ); rs.updateInt(1,111); rs.updateString(2, “Sateesh”); rs.updateString(3, “Analyst”); rs.updateFloat(4,7500); rs.updateInt(5, 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); rs.deleteRow(); The fourth row has been removed from uprs and also from the database. // Moves the cursor to the fourth row

Seeing Changes in Result Sets :

Result sets vary greatly in their ability to reflect changes made in their underlying data. If you modify data in a ResultSet object, the change will always be visible if you close it and then reopen it during a transaction. In other words, if you re-execute the same query after changes have been made, you will produce a new result set based on the new data in the target table. This new result set will naturally reflect changes you made earlier. You will also see changes made by others when you reopen a result set if your transaction isolation level makes them visible. With a ResultSet object that is TYPE_SCROLL_SENSITIVE, you can always see visible updates made to existing column values. You may see inserted and deleted rows, but the only way to be sure is to use DatabaseMetaData methods that return this information. You can, to some extent, regulate what changes are visible by raising or lowering the transaction isolation level for your connection with the database. For example, the following line of code, where con is an active Connection object, sets the connection's isolation level to TRANSACTION_READ_COMMITTED: Ex: con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

With this isolation level, a TYPE_SCROLL_SENSITIVE result set will not show any changes before they are committed, but it can show changes that may have other consistency problems. To allow fewer data inconsistencies, you could raise the transaction isolation level to TRANSACTION_REPEATABLE_READ. The problem is that, in most cases, the higher the isolation level, the poorer the performance is likely to be. And, as is always true of JDBC drivers, you are limited to the levels your driver actually provides. Many programmers find that the best choice is generally to use their database's default transaction isolation level. You can get the default with the following line of code, where con is a newly-created connection: Ex: int level = con.getTransactionIsolation( );
174 SATEESH N

SATEESH N

Getting the Most Recent Data : Another new feature in the JDBC 2.0 API is the ability to get the most recent data. You can do this using the method refreshRow, which gets the latest values for a row straight from the database. Note that the result set should be sensitive; if you use the method refreshRow with a resultSet object that is TYPE_SCROLL_INSENSITIVE, refreshRow does nothing. Ex: // File name : rs.refreshRow();

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 ("+empno+",'"+ename+"','"+job+"',"+sal+","+deptno+")"; System.out.println(query); int n = stmt.executeUpdate(query); if(n==1) System.out.println("Record Saved"); else System.out.println("Record not Saved"); } catch(Exception ex) { System.out.println("Error: "+ex); } stmt.close(); con.close(); }
175 SATEESH N

emp(empno,ename,job,sal,deptno)

values

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 : import java.io.*; import java.sql.*; class prepstmt { public static void main(String args[]) { try { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Getting connection ...."); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger"); PreparedStatement ps = con.prepareStatement("insert into emp(empno,ename,job,sal,deptno) values (?,?,?,?,?)"); while(true) { try { System.out.println(); System.out.print("Employee Number: "); int empno = Integer.parseInt(stdin.readLine()); System.out.print("Employee Name: "); String ename = stdin.readLine(); System.out.print("Employee Job: "); String job = stdin.readLine(); System.out.print("Basic Salary: "); double sal = Double.parseDouble(stdin.readLine()); System.out.print("Department No: "); int deptno = Integer.parseInt(stdin.readLine()); System.out.println(); ps.setInt(1,empno); ps.setString(2,ename); ps.setString(3,job); ps.setDouble(4,sal); ps.setInt(5,deptno); int n = ps.executeUpdate();
176 SATEESH N

prepstmt.java

} System. new Double(1000).close().println("Record saved").out. new Double(2500)}. String query = "update emp set sal = ? where empno = ?".setInt(2. i < len. jobs holds the designations of employees. sals holds the employees salaries and deptnos holds the departments numbers. for(int i = 0.out. i++) { ps. String str = stdin. The arrays.println("Error: "+ex).readLine(). } 177 SATEESH N . empnos holds the employee numbers. else System. sals[i].setDouble(1. } } } 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.7900.length.println("Record not saved"). int [ ] empnos = {7839. The code fragment that follows demonstrates using a for loop to set values for parameters in the PreparedStatement object ps . empnos[i]). con.doubleValue( )). ps.close(). Double [ ] sals = {new Double(500).toUpperCase(). ps.executeUpdate(). } catch(Exception ex) { System.out. new Double(2000).startsWith("N")) break.out. ps = con. enames holds the employees names .out. new Double(1500). if(str. } catch(Exception ex) { System. PreparedStatement ps.7902}.print("Any more Records [y/n]: ").prepareStatement(query).SATEESH N if(n==1) System. int len = empnos.println("Error: "+ex). } ps.7876. 7844.

in))."). else tdisc:=(tamt * 5)/100.net. 178 SATEESH N . such as procedures and functions."scott".println( ). // 2. w. tnet:= tamt .a.out. // 1. if tamt >= 5000 then tdisc:=(tamt * 10)/100.sql SQL> Create or Replace Function getnetamt(qty in Number.JdbcOdbcDriver").io.println("Getting Connection.rate in Number) return Number Is tamt number(12.. 2.out.sql. class calstmt { public static void main(String args[]) { try { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.forName("sun. Class. while(true) { try { System.jdbc. tnet number(12.tdisc. File name : getnetamt. end if. 1."tiger").SATEESH N CallableStatement : The CallableStatement is used for calling stored procedures of the database. import java. File name : calstmt. end. double rate.*.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.java // to call the function of oracle and get net amount returned by oracle function import java.a function in oracle which takes quantity and rate and returns the amount. return tnet.*.getConnection("jdbc:odbc:javaoracle".2).2). w. Begin tamt:= qty * rate. Connection con = DriverManager..2). System. tdisc number(12.odbc.

or batch.rate).readLine()).out.getDouble(1). 179 SATEESH N . which is associated with a Statement object at its creation.println("Net Amount: "+net).out.?)}").close(). } System. } catch(Exception ex) { System. rate = Double. The list. in some situations.startsWith("N")) break..Types.println("Connection closed. cs.toUpperCase().printStackTrace().readLine().setInt(2. // 1st parameter System.parseDouble(stdin.out. be much more efficient than sending update statements separately.println("Enter Qty purchased: "). if(str.out.print("Any more Data [y/n]: "). String str = stdin..execute(). When you have finished adding statements to the list. System. You can add SQL commands to this list with the method addBatch and empty it with the method clearBatch.println("----------------------------------------"). // call the oracle function getnetamt net = cs.println("Error: "+ex). int qty = Integer.qty).DOUBLE).println("Error: "+ex).prepareCall("{? = call getnetamt(?. } } } ExecuteBatch( ) : A batch update is a set of multiple update statements that is submitted to the database for processing as a batch. cs.registerOutParameter(1.readLine()).parseInt(stdin.out. cs. System. ex.println("Enter Rate per unit: "). System.").out.out.close(). you call the method executeBatch to send them all to the database to be executed as a unit.trim(). System. Sending batch updates can.setDouble(3.SATEESH N CallableStatement cs = con. cs. cs. is initially empty. } catch(Exception ex) { //System. } con.out..

addBatch("INSERT INTO student VALUES (666. i++) { System. try { int[] updCnt = stmt.println("Statement["+i+"] :"+counts[i]). } dbCon.setAutoCommit(false)."tiger"). stmt.close(). 'GWK')").addBatch("INSERT INTO student VALUES (555. dbCon. 'GRD')").commit( ).getUpdateCounts(). 'SANJU'.sql. 'USHA’.createStatement().printStackTrace(). class batchupdate { public static void main(String args[])throws Exception { try { Class.OracleDriver"). 'SATEESH’.length. } catch(Exception ex) { ex.SATEESH N // File name: batchupdate.java import java.*. } } } } Commit : RollBack : SavePoint : Blob Clob ConnectionPooling: RowSets: 180 SATEESH N . stmt.addBatch("INSERT INTO student VALUES (111. stmt. 'MRN')").out.forName("oracle. stmt. Connection dbCon = DriverManager.getConnection ("jdbc:oracle:thin:@orasrv:1521:miracle". i<counts. } catch (BatchUpdateException be) { //handle batch update exception int[] counts = be. "scott".driver. Statement stmt= dbCon. for (int i=0.close().executeBatch( ).jdbc. dbCon.

java E:\adv\swings>appleviewer buttontest.event.html <applet code='buttontest. b2.*. Swing is an enhancement for the AWT which provides the same look and feel even when we run the program on multiple platforms.addActionListener(this). import javax. c. If the program is based on graphical interface then the components of the program such as buttons. import java. these components are known as heavy weight components.setLayout(new FlowLayout( )). As a result the look and feel of the program may change from one platform to another platform. b2 = new JButton("Second Button").awt.*. checkboxes etc..html 181 SATEESH N . Container c = getContentPane( ).swing. public class buttontest extends JApplet implements ActionListener { JButton b1. // File name: buttontest. } public void actionPerformed(ActionEvent e) { if(e. c.getSource( ) == b1) showStatus("First Button Clicked").awt.java import java. } } File name: buttontest.getSource( ) == b2) showStatus("Clicked on Second Button"). else if(e.*.add(b1).SATEESH N Swing : When we design a Java program we are able to run the program on different platforms without recompilation.class' width=500 height=200> </applet> E:\adv\swings>javac buttontest.b2. c. will be created according to the underline operating systems.add(b2). b1. public void init() { b1 = new JButton("First Button"). Because the components will be created from the operating system.addActionListener(this).

WindowsLookAndFeel"). import javax.java.awt.setBounds(100. c.add(t2).swing. } catch(Exception ex) { System.setLayout(new FlowLayout()).setTitle("Sample Frame"). b1 = new JButton("Copy Dwon").add(t1).b2. 182 SATEESH N E:\adv\swings>javac frametest.motif.*.t2.300.setLookAndFeel("com. c.add(courses).println("Cannot change the interface"). f. c.windows. } c = getContentPane(). } } class MyFrame extends JFrame implements ActionListener.ItemListener { JTextField t1. JComboBox courses.awt.plaf. JCheckBox cb1. f.java E:\adv\swings>java frametest . cb1 = new JCheckBox("Sample CheckBox"). JButton b1.*.java.sun. f. b2 = new JButton("Copy Up"). public class frametest { public static void main(String args[ ]) { MyFrame f = new MyFrame( ). courses = new JComboBox().setLookAndFeel("com.SATEESH N // File name: frametest. MyFrame( ) { try { UIManager. c.200). t1 = new JTextField(25).plaf.add(cb1).swing. t2 = new JTextField(25).add(b1). Container c.add(b2). c.swing. import java.MotifLookAndFeel"). c.setVisible(true).sun. // UIManager.*.100.out.java // changing the LookAndFeel import java.event. c.

motif.sun. cb1.swing. t1. } } } Change the LookAndFeel : UIManager.sun.addActionListener(this).java E:\adv\swings>java frametest public void itemStateChanged(ItemEvent e) { if(cb1.addActionListener(this).setText(t2. t2.swing. int hsp ) vsp : Vertical Scrollbar Policy hsp : Horizontal Scrollbar Policy 183 SATEESH N . } else if(e.MotifLookAndFeel “ ).isSelected() == true) { JOptionPane.showMessageDialog(null.getText()).getSource() == t2) { t1.WindowsLookAndFeel “ ).java.addItemListener(this). int vsp.addItem("Visual Basic"). t2. } } E:\adv\swings>javac frametest. JScrollPane : Provides scrolling effect for the given component.setLookAndFeel( “ com.plaf."CheckBox CHECKED ON"). t2. Ex: JScrollPane( Component c.setLookAndFeel( “ com.getSource() ==b2 || e.SATEESH N b1. courses.setText(t1. courses. UIManager.windows.plaf.addItem("Developer 2000")."CheckBox CHECKED OFF").getText()).showMessageDialog(null.requestFocus(). t1.addItem("C Language").addActionListener(this).getSource() == b1 || e.addActionListener(this).java. t1. } else { JOptionPane.setText(""). b2.requestFocus(). courses.getSource() == t1) { t2.setText(""). } public void actionPerformed(ActionEvent e) { if(e.

*.println("Cannot change the interface"). public class treetest1 extends JFrame { JTree tree. JScrollPane.SATEESH N vsp : 1.event. import javax.sun. : The scrollbar will always be displayed. } root = new DefaultMutableTreeNode("Details"). JScrollPane. JTree : JTree is used for displaying the information in a hierarchical format. int hsp = JScrollPane. 184 SATEESH N . treetest1() { try { UIManager. JScrollPane. HORIZONTAL _SCROLLBAR_AS_NEEDED : Scrollbar will be displayed depending on the requirement.VERTICAL_SCROLLBAR_AS_NEEDED. lang = new DefaultMutableTreeNode("Languages").pack.swing.plaf. int vsp = JScrollPane.awt. DefaultMutableTreeNode : // File name : treetest1. JScrollPane. 3.HORIZONTAL_SCROLLBAR_NEVER 2.*. pack = new DefaultMutableTreeNode("Packages").java import java. HORIZONTAL_SCROLLBAR_ALWAYS : Hides the scrollbar.tree.swing. root. hsp : 1. JTree( TreeNode root) : The TreeNode is an interface that can contain text and subnodes also.out.VERTICAL_SCROLLBAR_ALWAYS : Hides the scrollbar. JScrollPane. JScrollPane.java. import javax.awt.VERTICAL_SCROLLBAR_AS_NEEDED : Scrollbar will be displayed depending on the requirement. JScrollPane jsp. } catch(Exception ex) { System. To create a node the following class can be used.add(pack). root.*.windows.HORIZONTAL_SCROLLBAR_AS_NEEDED. 3.*.WindowsLookAndFeel").add(lang).setLookAndFeel("com. DefaultMutableTreeNode root. : The scrollbar will always be displayed.VERTICAL_SCROLLBAR_NEVER 2.lang. import java.swing.

hsp). } } // File name : emptree. f. DefaultMutableTreeNode root. } } class MyFrame extends JFrame { JTree tree.setLookAndFeel("com. class emptree { public static void main(String args[]) { MyFrame f = new MyFrame().200). pack.400.tree. import javax. JScrollPane jsp.setBounds(100.*.println("Cannot change the interface"). pack.VERTICAL_SCROLLBAR_AS_NEEDED. } 185 SATEESH N .300.add(new DefaultMutableTreeNode("Visual Basic")).100. import javax.SATEESH N lang.*.plaf. getContentPane().add(jsp).*.setVisible(true).setBounds(50.setVisible(true). Container c.*. } public static void main(String args[]) { Frame f = new treetest1( ). f. f. jsp = new JScrollPane(tree.add(new DefaultMutableTreeNode("Developer 2000")). import java.50.add(new DefaultMutableTreeNode("Java")).add(new DefaultMutableTreeNode("C ++")). f. tree = new JTree(root). lang.event.setTitle("Tree Test1").swing. import java.sun.swing.500). } catch(Exception ex) { System.java.windows.WindowsLookAndFeel").add(new DefaultMutableTreeNode("Power Builder")).awt. lang. MyFrame() { try { UIManager.out.*.awt.vsp. f.sql. int vsp = JScrollPane.java import java.HORIZONTAL_SCROLLBAR_AS_NEEDED. pack.add(new DefaultMutableTreeNode("C language")). int hsp = JScrollPane.swing.

} catch(Exception ex) { JOptionPane.showMessageDialog(null."scott".println("Getting Connection.odbc.add(new DefaultMutableTreeNode("Empno: "+empno)). con. while(rs.hsp). } } } 186 SATEESH N ."tiger").job. stmt.close().getString(2). empNode. c.deptno from emp").getInt(1). } rs..getInt(5).add(new DefaultMutableTreeNode("SAL : "+sal)).. empNode. int deptno = rs. String ename = rs. DefaultMutableTreeNode empNode = new DefaultMutableTreeNode(String.close().add(new DefaultMutableTreeNode("Ename: "+ename)).getConnection("jdbc:odbc:javaoracle".valueOf(empno)). root = new DefaultMutableTreeNode("Employee Details").close().add(new DefaultMutableTreeNode("JOB : "+job)).add(empNode).add(jsp). Statement stmt = con.sal.vsp.jdbc.getDouble(4).out.. Connection con = DriverManager. empNode."Error in getting data").next()) { int empno = rs. Class.JdbcOdbcDriver").ename. root.executeQuery("select empno.add(new DefaultMutableTreeNode("Dept : "+deptno)).SATEESH N c = getContentPane(). double sal = rs. tree = new JTree(root).getString(3). empNode."). String job = rs. } void createNodes() { try { System.createStatement(). createNodes(). ResultSet rs = stmt. jsp = new JScrollPane(tree. empNode.forName("sun.

*. Container c = getContentPane(). String msg ) : It displays the message in a separate window.showMessageDialog(null.setLayout(new FlowLayout()).awt.setFont(new Font("Sanserif". import java.java.setVisible(true). } } } 187 SATEESH N .awt. c. } public void actionPerformed(ActionEvent e) { if(e. b1. } } public static void main(String args[]) { Frame f = new ipdialogbox().plaf.java import javax.SATEESH N JOptionPane : This class is providing the following functions which are generally used for displaying taking input etc. c. } catch(Exception ex) { System.setBounds(50.200). c. like msgbox in VB.windows.getSource()==b1) { String msg = JOptionPane. f.swing. static void showMessageDialog( Component parent. import java.addActionListener(this). ipdialogbox() { changeLookAndFeel(). else JOptionPane.event. if(msg == null) JOptionPane.println("Cannot change the Interface").50. b1 = new JButton("Show Dialog")."Data: "+msg).*.300. f.showInputDialog("Enter a String: "). } void changeLookAndFeel() { try { UIManager.out."Invalid Data").WindowsLookAndFeel").Font.showMessageDialog(null.swing.setLookAndFeel("com.sun. class ipdialogand extends JFrame implements ActionListener { JButton b1.. static String showInputDialog( objecgt message ) : Accepts input from the user in a dialog box and returns that text.add(b1).BOLD. // File name: ipdialogandmsgbox.*.14)).

setVisible(true). Statement stmt.swing.Vector.awt. } } class MyFrame extends JFrame implements ActionListener { JLabel l1. JButton b1.event. int size( ) : Returns the number of elements in the list.*.sql. import java.*.*.awt. import javax.b2. Constructors : Vector( ) : creates a vector. import java. JTextArea query. f.table. W.P to accept a query and display the selected records in a table format. public class tabletest { public static void main(String args[]) { MyFrame f = new MyFrame().50. import javax. import java. JPanel p1. Vector heads ) : The “heads” contains the headings of the JTable.swing. query = new JTextArea().SATEESH N JTable : JTable is used for displaying the information in rows and columns. we can remove any object from the list.util. MyFrame() { l1 = new JLabel("Enter Query: "). // File name : tabletest.350.java import java. where each such vector contains one record data. void add( object obj ) : Adds the object to the list.A.*. f. We can add any number of objects to the list. Vector : Vector is an utility class which works similar to a linked list. “RowData” is a collection of vectors. f. Object elementAt( int index ) : Returns the element at the specified index. “ JTable “ can be added to “JScrollPane” for Scrolling effect. Connection con. Container c.200).setBounds(50.setTitle("Query Frame").*. 188 SATEESH N . JTable( Vector rowData. void Remove( object obj ) : Removes the object from the list.

p1. b1 = new JButton("Execute Query").BorderLayout. } } void closeConnection() { try { if(stmt!=null) stmt. con = DriverManager. System.createStatement(). c = getContentPane().setLayout(new FlowLayout()).close()."Error: "+ex). c.. b1.odbc. System.add(p1. } catch(Exception ex) { JOptionPane.addActionListener(this).exit(0).SOUTH).BorderLayout.close(). if(con!=null) con.println("Getting Connection . else if(e.add(b2).out. openConnection().NORTH). b2. System. p1. } void openConnection() { try { System.showMessageDialog(null.forName("sun. Class.addActionListener(this).JdbcOdbcDriver").Font.SATEESH N p1 = new JPanel().BOLD.println("Connection closed.out.."Error: "+ex)..add(query.")..showMessageDialog(null.14)). b2 = new JButton("Exit Program").jdbc.getConnection("jdbc:odbc:javaoracle".getSource() == b1) showData(). } } 189 SATEESH N . p1.add(l1."tiger"). } } public void actionPerformed(ActionEvent e) { if(e..setFont(new Font("SanSerif". query.getSource() == b2) { closeConnection().add(b1)."). } catch(Exception ex) { JOptionPane.out.CENTER)."scott". c.. c.BorderLayout. stmt = con..println("Ok").

setTitle(str). for(i=1. f.setVisible(true).showMessageDialog(null. f.add(rs. int i.getColumnLabel(i)).300). ResultSet rs = stmt. } // Getting Data into the rowData while(rs.executeQuery(str). ResultSetMetaData rsmd = rs. } catch(Exception ex) { JOptionPane. f.i<=n.close(). } DisplayFrame f = new DisplayFrame(rowData.VERTICAL_SCROLLBAR_AS_NEEDED.i++) { curRow.getText().setBounds(50.SATEESH N void showData() { try { String str = query. // Getting Headings into the 1st vector for(i=1.i<=n.getColumnCount().add(curRow). rs.trim(). } // Add the current row to the row data rowData.getString(i)).i++) { heads.next()) { Vector curRow = new Vector(). JTable table.HORIZONTAL_SCROLLBAR_AS_NEEDED.getMetaData(). int vsp = JScrollPane. } } } class DisplayFrame extends JFrame { JScrollPane jsp. 190 SATEESH N .add(rsmd.600. Vector heads = new Vector().heads). Vector rowData = new Vector().50."Cannot execute query").n. int hsp = JScrollPane. Container c. n = rsmd.

c.14)).BOLD. table.add(jsp).vsp.Vector heads) { c = getContentPane().setAutoResizeMode(JTable.Font.setFont(new Font("SanSerif". jsp = new JScrollPane(table.heads).hsp).AUTO_RESIZE_OFF).SATEESH N DisplayFrame(Vector rowData. table. table = new JTable(rowData. } } 191 SATEESH N .

http://apache.. tomcat doesn’t supports for EJB. GET POST HEAD A WEB Server after receiving the data from the WEB Browser should forward the same to the ssp in the following 3 corresponding methods..e. These ServerSidePrograms can be written in any language such as C.. and the current technologies the ServerSidePrograms are designed using ASP. Servlets etc. i.org BEA IBM 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. The WEB Browser receives the data and presents the data on the document. GET POST HEAD Environment variables Streams Commandline arguments 192 SATEESH N .jsp. UNIX Shell programming. process the data and returns the output back to the WEB Server which will be given to the WEB Browser.. 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. WEB Browser http://yahoo. perl. The ServerSideProgram receives the data from the WEB Server. C++.JSP etc.jakarta.com User Name Password Login ServerSideProgram Yahoo WEB Server checkmail delete Particular ID’s Mail Box will be opened Documents The following are the famous WEB servers : IIS (Internet Information Serverm )  PWS ( Personal WEB Server )  Apache  Tomcat  Java Web Server J2EE Weblogic Websphere JRun JBoss       MircroSoft  supports ASP MircroSoft  supports ASP Apache  only for HTML Jakarta  supports servlets.SATEESH N For many WEB applications server side processing is necessary.

Syntax : DoGet( ) : public void doGet(HttpServletRequest.IO Exception DoPost( ):public void doPost(HttpServletRequest. 4. tomcat www. 1..yahoo. The following 4 rules will be used by the WEB Browsers for URL coding. 3.  If the WEB Browser sends the data in the “Post” method then the “doPost( )” method of the servlet will be execued. will be converted to hexadecimal values prefixed with % symbol. All special characters such as +.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. then the “doGet( )” will be executed. which is known as URL coding. HttpServletResponse) throws ServletException. All the fields will be separated by & symbol. While exchanging data between the WEB Browser and WEB Server the following 2 objects are used: Request and Response.  If the WEB Browser doesnot specify any method. & etc.SATEESH N www. All spaces will be converted to + symbols. Ex: http://myserver. 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.com GET POST HEAD Environment variables user name : password : Login WEB Server Streams Commandline args Server Side Program 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.yahoo. Each field contains the name of the field and the value of the field separated by = symbol.com user name : password : Login request WEB Server response 193 Server Side Program SATEESH N . The server isde program receives the converted data undos the conversion and process the data.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.HttpServletResponse) throws ServletException. 2.

out. // w.println("<HTML>"). Cookie[ ] get Cookie( ) : Returns all the cookies that are received from the WebBrowser.http. out. Methods : String getParameter(String paramname) : Returns the value of the specified parameter.java import java. import javax. HttpSession getSession( ) : Returns the current HttpSession. } } 194 SATEESH N .setContentType("text/html").servlet.println("<BODY bgcolor=#0086b2 text=white>"). import javax. Methods : void setContentType(String mimeType) : Sets the content type as mime type.println("<H1 align =center>Welcome to Servlet Programming</H1>"). out. public class firstservlet extends HttpServlet { public void doGet(HttpServletRequest request. 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.println("</BODY>"). out.getWriter(). HttpServletResponse : For sending output to the WebBrowser. PrintWriter out = response.io. out. void addCookie(Cookie ck) : Sends a cookie to the WebBrowser.SATEESH N HttpServletRequest : For receiving input from the WebBrowser.*.servlet.println("<HR size=5 color=black>"). IOException { // send the output to the webbrowser response. out.Servlet to send the text to WebBrowser.println("</HTML>").a. // File name : firstservlet.HttpServletResponse response)throws ServletException. out. It returns null if the parameter is not available.println("<H3> First Servlet Program</H3>").*.*.

println("<th>Salary</th>"). out.deptno from emp").println("</table>"). import java. out.sql. out.getConnection("jdbc:odbc:javaoracle".println("<tr>").*. out.SATEESH N // w.</th>").next()) { out.println("<tr>").sal. out.println("</body></html>").*. // Connection con = DriverManager.println("<h2 style='background-color:green.jdbc.forName("oracle.println("</tr>"). con. public class getempdetservlet extends HttpServlet { public void doGet(HttpServletRequest request. } catch(Exception ex) { out.*. } } 195 SATEESH N .OracleDriver"). Connection con = DriverManager. out.HttpServletResponse response)throws ServletException.setContentType("text/html").forName("sun."scott". out. Class.close().getWriter().println("</tr>").close(). try { // getting data // Class.i<=5. import javax."scott".println("<td>"+rs.jdbc.odbc.getString(i)+"</td>").ename. // placing the records into table while(rs. rs."tiger").servlet. Statement stmt = con.servlet to send employee details to the WebBrowser.println("<th>Employee Name</th>").getConnection("jdbc:oracle:thin:@orasrv:1521:miracle".println("<th>Department No. } out.a. out.servlet.createStatement().io. } out.http.java import java. out. import javax. PrintWriter out = response.println("<table width=100% bgcolor=pink border=2 bordercolor=red cellspacing=0>").job.text-align:center'> Exployee Details </h2>").color:yellow.*. // File name : getempdetservlet.println("<th>Employee Number</th>"). for(int i=1.println("<th>JOB</th>").println("<br> Error: "+ex).executeQuery("select empno.println("<html><body bgcolor=white text=black>").i++) { out. ResultSet rs = stmt. } out."tiger").JdbcOdbcDriver"). stmt. //constructing table format out.close(). IOException { response.driver.

check boxes etc.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.SATEESH N HTML Forms : A HTML form is a collection of input fields such as text boxes. Each HTML form contains the following. IOException { response. Name : form name Method : GET || POST Action : The name of the server side program for processing the data.*.HttpServletResponse response)throws ServletException.iptoservletoptowb. Elements : One or more input fields.println("<html><body>"). String p3 = request.http.getParameter("JOB"). out.getParameter("ENAME"). HTML forms are used for sending data from the WebBrowser to the WebServer.*.getParameter("EMPNO"). import javax. // send the received details to the client 196 SATEESH N .servlet. public class iptoservletoptowb extends HttpServlet { public void doGet(HttpServletRequest request..*.html <!-.servlet.getWriter(). String p2 = request. import javax. SUBMIT button : A special button which sends the accepted data to the WebServer.java import java. // File name : iptoservletoptowb.s which accepts employee details from WebBrowser (html) and sends them to the WebServer (ssp). PrintWriter out = response.setContentType("text/html"). // w.a.io. The servlet after receiving the data should echo the details back to the WebBrowser. // read data from the request String p1 = request.

sql.executeQuery(). The servlet should return the corresponding employee details back to the WebBrowser.println("<h2> received details </h2>").empno).jdbc.job. IOException { response.println(" Employee JOB : "+p3+"</h3>"). ps = con.parseInt(request. ResultSet rs = ps. con = DriverManager.prepareStatement("select empno.println("<html><body>").setContentType("text/html"). out.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.println("<br>"). public class findempservlet extends HttpServlet { static Connection con.io. html file which accepts an employee number and sends the employee number to the servlet. import javax.JdbcOdbcDriver")."scott".*. 197 SATEESH N . out.http.getConnection("jdbc:odbc:javaoralce".deptno from emp where empno=?"). import javax.SATEESH N out. public void doGet(HttpServletRequest request.ename. out. out. out.getWriter().println("</body></html>").odbc.servlet. } } // w. out.println(" Employee Name : "+p2+"<br>").*. static PreparedStatement ps. import java.*. // Get the record try { Class. <!--findempservlet.forName("sun. ps.servlet.getParameter("EMPNO"))."tiger").println("<h3> Employee Number: "+p1+"<br>").a. PrintWriter out = response.*. // Receive the employee number int empno = Integer.sal.setInt(1.HttpServletResponse response)throws ServletException.

println("<br> Employee Name: "+rs. out.println("</body> </html>"). out.println(" <hr size=5 color=red> ").*.color:white.getString(5)). out.sql. out.getString(1)).println("<br> Department No: "+rs. import javax. out. The servlet after receiving the employee details should insert them into the database.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.getString(4)).java import java.a.println("<br> Error: "+ex).html'> Find Another </a>").SATEESH N if(rs.println("<br> Salary: "+rs. } else { out. <!--saveempservlet.next()) { out.*.html--> <html> <body> <h2 style=background-color:#0086b2. } out.getString(3)).servlet.*.println(" <h2> Record Not Found: "+empno+" </h2> ").http. } } // w.println("<br> Employee Number: "+rs. out. import java. 198 SATEESH N .println(" <a href = '/satclass/findempservlet.servlet. } } catch(Exception ex) { out.*.getString(2)).println(" <h2> RecordFound </h2> "). out.io. import javax.println("<br> JOB: "+rs. html file which accepts employee details and sends them to the servlet.

forName("sun.close(). PrintWriter out = response. ps.parseDouble(request. out. String job = request.?)").close().HttpServletResponse response)throws 199 SATEESH N .getParameter("ENAME").?. con. if(n==1) out.parseInt(request.println("</body> </html>"). } catch(Exception ex) { out.setContentType("text/html").odbc. ps.getParameter("DEPTNO"))."tiger").println(" <hr size=5 color=red> ").executeUpdate().getWriter().println("<h3> Record Not Saved </h3>"). int n = ps. ps = con.setDouble(4.SATEESH N public class saveempservlet extends HttpServlet { static Connection con.IOException { response. static PreparedStatement ps. con = DriverManager.job).ename).println("<br> Error: "+ex).setInt(5.sal. out.setInt(1.getParameter("JOB").println("<h3> Record Saved </h3>").prepareStatement("insert into emp(empno.deptno).empno). double sal = Double.sal).println(" <a href = '/satclass/saveempservlet.jdbc.setString(3.getParameter("EMPNO")).?.parseInt(request. // open the connection Class.println("<html><body>").html'> Save Another </a>").?.deptno) values(?. ps. int deptno = Integer. try { // Receive the employee details int empno = Integer. } out. String ename = request. ps. ps.ename. else out. out. ps.getConnection("jdbc:odbc:javaoracle".setString(2. public void doGet(HttpServletRequest ServletException.job.getParameter("SAL")).JdbcOdbcDriver")."scott". } } request.

out.sql.servlet. PrintWriter out = response.setContentType("text/html"). if(RNO!=null) { rno = Integer. 200 SATEESH N . } rno++..*.getWriter(). 1.*. whenever a WebBrowser sends a request to the WebBrowser.HttpServletResponse response)throws ServletException. // File name: nextempservlet. i. Some times we want the server side program to identify what values are given to the clients in the previous response. String RNO = request. IOException { response.*. try { // send the employee record openConnection().java // using hidden variables import java. import java.parseInt(RNO). public void doGet(HttpServletRequest request. Sessin management can achieve in three different ways.http. 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.getParameter("RNO").io.servlet. i. Hidden Variables 2.SATEESH N Session Management : HTTP is a stateless protocol. the WebServer provides a response to the WebBrowser and closes the connection. import javax. Whenever the user clicks on the submit button the value of the hidden variable will also be submitted along with the other input fields.e. int rno = 0.println("<html> <body> <h2> Employee Record </h2>").*.. the WebBrowser doesn’t store any information of WebBrowser. Session management is concept which makes a server side program to identify what values are given to the clients in the previous response. Cookies 3.e. public class nextempservlet extends HttpServlet { static Connection con = null. import javax.

sal.println(" <br> Student Number : " +rs. } rs.odbc.deptno from employee where empno = ?"). out.println("Getting Connection.getString(3) )..println("</form>"). out. out. } // send the latest rno from the webserver to webbrowser out.getString(4) ).println(" <br> Student Address: " +rs. } 201 SATEESH N .SATEESH N // PreparedStatement ps = con.JdbcOdbcDriver").ename.println(" <br> Basic Salary : " +rs."scott". Class.next() ) { out.prepareStatement("select empno.getString(5) ).").getConnection("jdbc:odbc:javaoracle". out. out. ResultSet rs = ps. out. if( rs.job.close().println(" <h3> Record Not Found: " +rno+ "</h3> "). PreparedStatement ps = con.println(" <br> Employee Number: " +rs.println(" <br> Student Name : " +rs.prepareStatement("select sno.out. } catch(Exception ex) { out.getString(2) ). out.. } catch(ClassNotFoundException ex) { throw new SQLException("Driver Class Not Found").jdbc.println(" <hr size = 5 color = red> "). out.println(" <input type=Hidden name=RNO value="+rno+"> ")..getString(1) ).getString(1) ). out. ps. out. ps. con = DriverManager.println(" <form name=EMPFORM method=GET action='http://localhost:8080/satclass/servlet/ nextempservlet'> ").println(" <br> Employee Name : " +rs.rno).setInt(1.println(" <br> Error: "+ex).getString(2) ).executeQuery().println(" <input type=Submit value='Next Record'> "). // // // // // out.println(" <br> Department No.saddr from student where sno = ?").close(). } void openConnection()throws SQLException { try { System.sname.println("</body></html>")."tiger"). out.getString(3) ).println(" <h3> Record Found: " +rno+ "</h3> "). } else { out.println(" <br> Employee Job : " +rs. : " +rs. out.forName("sun.

import java. Cookie(String name. import javax. Creating a Cookie : In java cookies are managed using the cookie class each contains a name.*. expire date and time etc.http. Each cookie contains a name and value.*. If a cookie with the same name is already existing on the WebBrowser it will bhe replaced by the latest value. 202 SATEESH N .servlet.setContentType("text/html"). Whenever the WebBrowser connects to the WebServer all the cookies of that WebServer will be given from the WebBrowser to the WebServer.servlet. 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.java // using cookies import java. Receiving the Cookies from the WebBrowser : HttpServletRequest : Cookie[ ] getCookies( ) : Returns all the cookies that are received from the WebBrowser. As a result the server side program can retrieve any values stored into cookie. A WebBrowser generally stores upto 20 cookies for each WebServer. In java cookies are managed using the cookie class. value. The WebBrowser stores the cookie in a separate memory area. public class nextempservlet2 extends HttpServlet { static Connection con = null.io.*. IOException { response. The WebBrowser receives the cookie and it will not be displayed on the document.SATEESH N catch(SQLException ex) { throw ex. import javax.HttpServletResponse response)throws ServletException. public void doGet(HttpServletRequest request.sql. // File name: nextempservlet2. } } } Cookies : A cookie is a piece of information created by the server and will be given to the clients WebBrowser. A cookie contains the name and value..*.

valueOf(rno)).jdbc.forName("sun. 203 SATEESH N .JdbcOdbcDriver").println("Getting Connection . out.getCookies().").out.getConnection("jdbc:odbc:javaoracle".println(" </body> </html> "). con = DriverManager."tiger").println("<html> <body> <h2> Employee Record </h2>").sal.getWriter(). } } } rno++.job.getName().out).ename.i<arr. // send the latest cookie to the webbrowser Cookie ck = new Cookie("RNO".. break.executeQuery(). Cookie arr[] = request.prepareStatement("select sno. } void sendRecord(int rno. out. response.sname.setInt(1.equals("RNO")) { rno = Integer."scott". // send the record of "rno" to "out" sendRecord(rno.length.SATEESH N PrintWriter out = response.. } // PreparedStatement ps = con.prepareStatement("select empno.deptno from emp where empno = ?"). Class. // find the cookie with the name "RNO" if(arr!=null) { for(int i=0..String. int rno = 0. PreparedStatement ps = con. out. ResultSet rs = ps.getValue()).saddr from student where sno = ?").rno). out.i++) { if(arr[i]..println(" <a href='http://localhost:8080/satclass/servlet/nextempservlet2'> Next Employee Record </a> ").addCookie(ck). ps.PrintWriter out)throws IOException { try { if(con==null) { System.println(" <hr size = 5 color = red> ").parseInt(arr[i].odbc.

ps.getString(1) ).println(" <h3> Record Found: " +rno+ "</h3> ").println(" <br> Department No.println(" <br> Student Address: " +rs.close().getString(2) ). : " +rs.getString(5) ).println(" <br> Student Number : " +rs.println(" <br> Basic Salary : " +rs. out.println(" <br> Employee Job : " +rs. out.println(" <br> Error: "+ex).getString(3) ). out.getString(2) ).SATEESH N if( rs.println(" <br> Employee Number: " +rs.getString(1) ). } catch(Exception ex) { out. out.getString(4) ).println(" <br> Student Name : " +rs. out.next() ) { out.close(). // // // // // out. out. } } } 204 SATEESH N .getString(3) ). } else { out.println(" <h3> Record Not Found: " +rno+ "</h3> "). } rs. out.println(" <br> Employee Name : " +rs.

int a = 10. %> <hr> Total is: <%= c %> <hr> Employee Number: <%= empno %> <br> Employee Name : <%= ename %> <br> </body> </html> Every “ jsp ” program contains the following objects by default. int b = 20.println(" <h3> First JSP Program </h3> "). int c = a+b. executed. out.jsp <!--test.println(" <br> Total is: "+c ). out request response : PrintWriter : HttpServletRequest : HttpServletResponse 205 SATEESH N . String ename = "abc".jsp--> <html> <head> <title> Test Program in JSP </title> </head> <body> <h2> Sample JSP Program </h2> <% out.SATEESH N JSP is an enhancement for the servlets. For the remaining requests the compiled version will be executed. 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. <% // java statements %> script let // File name: test. int empno = b. All the java statements in a jsp document must be given between the following tags.

executeQuery("select empno. stmt.close(). Connection con = DriverManager.createStatement().a.next()) { %> <tr> <td> <%=rs.println("Getting Connection.jsp --> <%@ page import = "java.jdbc. %> <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."tiger").. <!-.sal..forName("sun.JdbcOdbcDriver").SATEESH N session page application in : HttpSession : this : ServletContext : BufferedReader // w.out.deptno from emp").ename.getConnection("jdbc:odbc:javaoracle".odbc.*" %> <html> <head> <title> Employee Details </title> </head> <body> <h2 style='background-color:blue.getString(2) <td> <%=rs. Statement stmt = con. ResultSet rs = stmt.getString(5) </tr> <% } out. } %> </td> %> </td> %> </td> %> </td> %> </td> 206 SATEESH N . Class... text-align:center'> Employee Details </h2> <% try { System.jsp program which sends the employee details in a table format.getempdet.println("</table>")."scott".getString(3) <td> <%=rs.job."). rs. color:white.getString(4) <td> <%=rs.getString(1) <td> <%=rs.close().sql.

<!-.parseInt(request.getParameter("ename").a.SATEESH N catch(Exception ex) { out. String ename = request.html'> Another Record </a> </body> </html> 207 SATEESH N . } %> </body> </html> // w. html file to send the employee details from WebBrowser to jsp program.jsp --> <%@ page errorPage = "error. %> <br> Employee Number: <%= empno %> <br> Employee Name : <%= ename %> <br> Employee Job : <%= job %> <br> Employee Salary: <%= sal %> <br> Department No.html--> <html> <body> <h2> Enter Employee Details </h2> <form name = EMPFORM method=GET action='empecho.jsp <!-.getParameter("sal")). String job = request.getParameter("job").println("<br> Error: "+ex).empecho.parseInt(request. int sal = Integer.parseInt(request.getParameter("deptno")). : <%= deptno %> <hr size=5 color=red> <a href='empecho. after receiving employee details the jsp program send back the details to the WebBrowser. int deptno = Integer.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.empecho.jsp"%> <html> <body> <h2> Received Details </h2> <% int empno=Integer.getParameter("empno")).

JdbcOdbcDriver").getString(2)%> <br> Employee Job : <%=rs.close(). : <%=rs. Connection con = DriverManager."tiger").close()."scott".getConnection("jdbc:odbc:javaoracle".deptno from emp where empno=?").jsp'> Enter Employee Number <input type=text name=EMPNO size=15> <input type=submit value='Find Employee Record'> </form> </body> </html> // File name: findemp.getString(1)%> <br> Employee Name : <%=rs.getParameter("EMPNO")).empno). the jsp program receives the employee number and send the corresponding employee details back to WebBrowser. } catch(Exception ex) { out. if(rs.println("Error: "+ex). ps. } rs.setInt(1.jdbc.SATEESH N // w.jsp <!-.sql.a.println("<h3> Record Not Found </h3>").sal.next()) { %> <h3> Record Found </h3> <br> Employee Number: <%=rs. PreparedStatement ps = con.parseInt(request.html--> <html> <body> <h2> Find Employee Details </h2> <form name = EMPFORM method=GET action='http://localhost:8080/satclass/findemp. <!--findemp.ename.forName("sun.findemp. } %> <hr size=5 color=red> <a href='findemp. con.jsp --> <%@ page import = "java.close().*" %> <html> <body> <h2> Employee Details </h2> <% try { int empno=Integer.html'>Find Another Record</a> </body> </html> 208 SATEESH N . html file to accept an employee number and send that number to the jsp program. ps.odbc. ResultSet rs = ps.executeQuery(). Class.getString(5)%> <% } else { out.getString(4)%> <br> Department No.getString(3)%> <br> Employee Salary: <%=rs.job.prepareStatement("select empno.

<!-.error. Using a bean in a jsp program : To use a bean in a jsp program the “jsp: useBean” directory should be applied. ii.SATEESH N Error Page : name. i. which takes a jsp document Whenever an error occurs in the “ jsp “ program the control will be transferred to the specified error page. iii. which is a reusable component. Will perform the following action employee emp. emp = new employee(). The scope can be one among the following.jsp --> <% @ Page is ErrorPage = "true" %> <html> <body> <h2 style='background-color:blue.color:white. Application : For all the clients only one instance of the bean will be created and the bean will be created on the server. 209 SATEESH N . To create a “ bean “.employee” scope=”session”/> The above ex. create a “ class “ that follows the “ bean specification “. Request : For each request a bean will be created. Once a bean is created it can be used in any number of programs. Ex: <jsp:useBean id=”emp” class”emp.toString()%> </body> </html> Servlet Beans : A bean is a java class.getMessage()%></h3> <br> Error: <%=Exception.text-align:center'> <h3> Error: <%=exception. Page : For each page a bean will be created. Every java bean is a java class The bean must be placed in a package The bean should contain a zero argument constructor 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. The error page directive can be given in any “ jsp “ programs. iv. Session : For each client a separate bean will be created.

the old bean will be destroyed. public class ConnectionException extends Exception { String msg.jsp server server User1 User2 User n User1 User2 User n In application if all the users are connecting to the same jsp program all are connected to one bean only. When the connection is braked. // File name: ConnectionException.jsp Request : ex2. SATEESH N .SATEESH N Page : Bean ex2.jsp Bean ex1.jsp ex1.jsp server server User1 User2 User n User1 User2 User n In page and Request whenever user connects.jsp Bean Bean ex1.*. Application : Session : Bean Bean ex1. } 210 In session for each user a separate bean is created. public ConnectionException() { msg = "Connection Exception occurred". import java. the new bean is created.java package mycon.sql.

"tiger").. con = DriverManager.println("Getting connection.java package mycon.JdbcOdbcDriver"). } void openConnection() throws ConnectionException { try { System. public class mycon { Connection con..toString())."scott". import java.out. 211 SATEESH N . } catch(Exception ex) { throw new ConnectionException("Cannot Establish Connection"). } } public Statement createStatement() throws ConnectionException { try { if(con == null) openConnection().odbc.getConnection("jdbc:odbc:javaoracle".createStatement(). } catch(Exception ex) { throw new ConnectionException(ex..msg = msg.forName("sun. } public String toString() { return msg.jdbc. Class.*.SATEESH N public ConnectionException(String msg) { this. } } // File name: mycon. public mycon() { con = null.sql."). return con. } } public PreparedStatement prepareStatement(String sql) throws ConnectionException { try { if(con == null) openConnection().

jsp <!-. } 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 Salary</th><th>Department No.getString(2) %> </td> <td> <%=rs. } } } // File name: empusebean.next()) { %> <tr> <td> <%=rs.prepareStatement(sql).getString(5) %> </td> 212 Job</th> <th>Basic SATEESH N .getString(3) %> </td> <td> <%=rs.ename.getString(4) %> </td> <td> <%=rs. try { stmt = con.SATEESH N return con.</th> </tr> <% if(rs!=null) { while(rs.color:white.jsp" %> <jsp:useBean id="con" class="mycon.empusebean.executeQuery("select empno. } catch(Exception ex) { throw new ConnectionException(ex. Statement stmt=null.deptno from emp").*" %> <%@ page errorPage = "error.jsp --> <%@ page import = "java.sql. rs= stmt.toString()).sal.createStatement().mycon" scope="application"/> <html> <head> <title> Employee Details </title> </head> <body> <h2 style='background-color:blue.job.getString(1) %> </td> <td> <%=rs.text-align:center'> Employee Details </h2> <% ResultSet rs=null.

DisplaySelectedEmployee.color:white.job.deptno from emp").println("</table>"). ResultSet rs = null. UpdateEmployee.text-align:center'> Employee Details </h2> <% Statement stmt = null.executeQuery("select empno. } catch(Exception ex) { %> <%=ex %> <% } %> <table width=100% bgcolor=cyan border=2 bordercolor=blue> <tr> <th> EmpNo </th> <th> Employee Name</th> <th> Job </th> <th> Salary </th> 213 SATEESH N .jsp DiplayAllEmployees. } %> </body> </html> // write the following set of programs 1. try { stmt = con.ename.jsp <!-.close().jsp--> <%@ page import = "java. rs.jsp which should open the selected record for editing.DiplayAllEmployees. rs = stmt.sql.mycon" scope="application"/> cont… <html> <body link=blue vlink=pink alink=red> <h2 style='background-color:blue. DisplayAllEmployees.jsp should update the data in the datbase. stmt.jsp 3.*" %> <%@ page errorPage = "error. Whenever the user click on any employee number the selected employee number should be forwarded to the DisplaySelected Employee.jsp 2.jsp should display all the employee records in a table format.jsp" %> <jsp:useBean id="con" class="mycon.sal. After the user modifies the employee record the last program UpdateEmployee.createStatement().SATEESH N </tr> <% } // end of while out. // File name: DisplayAllEmployees.close().

getString(4) %> </td> <td> <%=rs.close().setInt(1.deptno from emp where empno=?").sql.prepareStatement("select empno.jsp <!-.mycon" scope="application" /> <html> <body link=blue vlink=green alink=red> <h2 style='background-color:blue.next()) { int empno = rs.job. } catch(Exception e) { %> <%=e%> <% } 214 SATEESH N .getInt(1).getString(5) %> </td> </tr> <% } // end of while out. PreparedStatement ps =null.parseInt(request. stmt.jsp?EmpNo=<%=empno%>'> <%=empno %> </a> </td> <td> <%=rs.getString(2) %> </td> <td> <%=rs. ps.getParameter("EmpNo")).ename. ResultSet rs = null.jsp" %> <jsp:useBean id = "con" class="mycon.SATEESH N <th> DeptNo </th> </tr> <% if(rs!=null) { while(rs.*" %> <%@ page errorPage = "error.jsp --> <%@ page import = "java.empno).color:white.close().getString(3) %> </td> <td> <%=rs. rs = ps.DisplaySelectedEmplee. %> <tr> <td align=center> <a href='DisplaySelectedEmployee. try { ps = con.text-align:center'> SelectedEmployee Details </h2> <% int empno = Integer.executeQuery().sal. rs.println("</table>"). } // end of if %> </body> </html> // File name: DisplaySelectedEmployee.

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(4) %>'> </td> <tr> <tr> <td> Employee DepartmentNumber </td> <td> <input type = text name=DEPTNO size=5 value='<%=rs.close().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. } rs.next()) { %> <form name=EMPFORM method = GET action='UpdateEmployee. ps.println("<h2> Record Not Found ! </h2>").close().jsp'> All Employee Details </a> </body> </html> 215 SATEESH N .SATEESH N if(rs.getString(3) %>'> </td> <tr> <tr> <td> Employee Salary </td> <td> <input type = text name=SAL size=15 value='<%=rs. %> <hr size=5 color = red> <a href='DisplayAllEmployees.getString(2) %>'READONLY> </td> <tr> <tr> <td> Employee Job </td> <td> <input type = text name=JOB size=15 value='<%=rs.getString(1) %>'READONLY> </td> <tr> <tr> <td> Employee Name </td> <td> <input type = text name=ENAME size=15 value='<%=rs.

parseInt(request.*" %> <%@ page errorPage = "error.deptno=? where empno=?").SATEESH N // File name: UpdateEmployee. ResultSet rs = null. double sal= Double.getParameter("DEPTNO")).empno). PreparedStatement ps =null.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. } catch(Exception e) { %> <%=e%> <% } if(rs. ps.deptno from emp where empno=?").jsp" %> <jsp:useBean id = "con" class="mycon.job. String job = request. rs = pss.getParameter("ENAME").prepareStatement("update emp set job=?.setDouble(2.executeUpdate().ename. ps.sql.next()) { %> <form name=UPDATEFORM method = GET action='DisplayAllEmployee.deptno).jsp <!-.sal.jsp --> <%@ page import = "java.setString(1.parseInt(request. String ename = request.parseDouble(request.setInt(1.getParameter("SAL")).executeQuery().color:white.getInt(1) %>'READONLY> </td> <tr> <tr> <td> Employee Name </td> <td> <input type = text name=ENAME size=15 value='<%=rs.getParameter("JOB").text-align:center'> Updated Employee Details </h2> <% int empno = Integer. PreparedStatement pss =null.setInt(4.mycon" scope="application" /> <html> <body link=blue vlink=green alink=red> <h2 style='background-color:blue. ps. ps.getParameter("EMPNO")).job). int deptno = Integer.getString(2) %>'READONLY> </td> <tr> 216 SATEESH N .empno).sal=?.setInt(3.sal). pss = con.prepareStatement("select empno. try { ps = con.UpdateEmployee. pss. ps.

SATEESH N <tr> <td> Employee Job </td> <td> <input type = text name=JOB size=15 value='<%=rs.close().close(). void getAttribute(String name) : Retrieves the value from the session. the WebBrowser sends the session-id to the WebServer. void setAttribute(String name. Integer( int val ) : It is a class to store the integer value. the server side program receives the session-id and is able to open the session of the corresponding WebBrowser.getFloat(4) %>'READONLY> </td> <tr> <tr> <td> Employee DepartmentNumber </td> <td> <input type = text name=DEPTNO size=5 value='<%=rs. Object obj ) : Adds an object to the session. Each session contains a unique id & such unique-id is given to the WebBrowser.getInt(5) %>'READONLY> </td> <tr> </table> </form> <% } // end of if else { out. ps.println("<h2> Record Not Found ! </h2>"). int intValue( ) : It is a function to retrieve the value. As a result.jsp'> All Employee Details </a> </body> </html> Sessions : A session is a piece of memory allocated by the WebServer for each WebBrowser.getString(3) %>'READONLY> </td> <tr> <tr> <td> Employee Salary </td> <td> <input type = text name=SAL size=15 value='<%=rs. HttpSession : Methods : String getId( ) : Returns the session ID. The server side program can store any value in that WebBrowser’s session. } rs. The WebBrowser stores the session-id in the form of a cookie and whenever the WebBrowser connects to the same WebServer. %> <hr size=5 color = red> <a href='DisplayAllEmployees. In a jsp program the current session can be accessed using the session Object. 217 SATEESH N .

%> <%=rno%> <% } catch(Exception e) { %> <%=e%> <% } %> <table width=100% bgcolor=cyan border=2 bordercolor=blue cellspacing=0> <% if(rs.*" %> <%@ page errorPage = "error. try { ps = con.jsp --> <%@ page import = "java.getAttribute("RNO"). PreparedStatement ps=null. ps.getString(2) %> </td> </tr> 218 SATEESH N . session.job.getString(1) %> </td> </tr> <tr> <td> Employee Name </td> <td> <%=rs.deptno from emp where empno=?").rno). if(integer != null) { rno = integer.setAttribute("RNO".mycon" scope="application"/> <html> <body> <h2 style='background-color:blue.ename.integer).text-align:center'> Employee Details </h2> <% int rno = 0.jsp <!-.jsp" %> <jsp:useBean id="con" class="mycon.sal.SATEESH N // File name: Nextemp.color:white.executeQuery().setInt(1. // Retrieve the record for rno ResultSet rs=null. Integer integer = (Integer)session. } rno++.Nextemp. // put the latest value into the session integer = new Integer(rno).next()) { %> <tr> <td> Employee Number </td> <td> <%=rs.prepareStatement("select empno.sql. rs= ps.intValue().

ps.jsp --> <%@ page import = "java.getString(3) %> </td> </tr> <tr> <td> Employee Salary </td> <td> <%=rs.parseInt(OPT).parseInt(RNO). 219 SATEESH N .*" %> <%@ page errorPage = "error. String OPT = request.NavigateRecords.jsp" %> <jsp:useBean id="con" class="mycon. if(RNO != null) { rno = Integer. } rs.color:white. if(OPT != null) { opt = Integer.getParameter("OPT").close().getString(4) %> </td> </tr> <tr> <td> Department Number </td> <td> <%=rs.SATEESH N <tr> <td> Employee Job </td> <td> <%=rs.mycon" scope="application"/> <html> <body> <h2 style='background-color:blue.sql.jsp <!-. %> <hr size=5 color=red> <a href='Nextemp. } int opt = 0.getAttribute("RNO").close(). String RNO = (String)session.getString(5) %> </td> </tr> </table> <% } // end of if else { out.println("<h3> Record Not Found !</h3>").jsp'>Next Employee Record</a> </body> </html> // File name: NavigateRecords.text-align:center'> Employee Records </h2> <% int rno = 0.

String. case 4: rno=14. if(rno==15) rno=14. rs= ps.valueOf(rno)).getString(2) %> </td> </tr> <tr> <td> Employee Job </td> <td> <%=rs. case 2: rno--.setInt(1. break.ename. break.rno).next()) { %> <tr> <td> Employee Number </td> <td> <%=rs.job. break. try { ps = con. if(rno==0) rno=1.executeQuery().getString(1) %> </td> </tr> <tr> <td> Employee Name </td> <td> <%=rs. break. // to start from 1st record } // put the latest value RNO into the session session. %> <%=rno %> <% } catch(Exception e) { %> <%=e%> <% } %> <table width=100% bgcolor=cyan border=2 bordercolor=blue cellspacing=0> <% if(rs. // Get the record and display it ResultSet rs=null. ps.sal. } } else { rno++.deptno from emp where empno=?").SATEESH N switch(opt) { case 1: rno=1.prepareStatement("select empno.getString(3) %> </td> </tr> <tr> <td> Employee Salary </td> <td> <%=rs.setAttribute("RNO". PreparedStatement ps=null.getString(4) %> </td> </tr> 220 SATEESH N . case 3: default: rno++.

} rs. } 221 SATEESH N .close().getString(5) %> </td> </tr> </table> <% } // end of if else { out. } public void setEmail( String value ) { email = value.jsp?OPT=1'>FIRST</a> <a href='NavigateRecords.java GetData.jsp?OPT=4'>LAST</a> </body> </html> // w. public void setUsername( String value ) { username = value.jsp // File name : UserData. %> <hr size=5 color=red> <a href='NavigateRecords. String email.jsp?OPT=2'>PREVIOUS</a> <a href='NavigateRecords. int age. } public String getUsername() { return username.jsp SaveName. public class UserData { String username.jsp NextPage.SATEESH N <tr> <td> Department Number </td> <td> <%=rs.java package mycon. 2. ps. } public void setAge( int value ) { age = value. 3.println("<h3> Record Not Found !</h3>"). 4. UserData.jsp?OPT=3'>NEXT</a> <a href='NavigateRecords.close().an application using setProperty 1.

jsp <jsp:useBean id="user" class="mycon.jsp <jsp:useBean id="user" class="mycon.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.getEmail() %> <br> Age: <%= user.getUsername() %> <br> Email: <%= user.UserData" scope="application"/> <html> <body> You entered <br> Name: <%= user.getAge() %> <br> </body> </html> 222 SATEESH N .SATEESH N public String getEmail() { return email.jsp">Continue</a> </body> </html> // File name: NextPage.jsp <html> <body> <form method=post action="SaveName. } public int getAge() { return age. } } // File name: GetName.UserData" scope="application" /> <jsp:setProperty name="user" property="*"/> <html> <body> <a href="NextPage.

param : The param object contains all the parameters in the request object.tld : ( Tag Library Discriptor ) . The following objects can be available in jstl. The JSTL should be downloaded separately in a compressed format.println. page etc. *. Tlds : Jars : c. out : Takes a value and sends the value to the WEB Browser.tld x. EL (Expression Language) : EL is a new technology which can be embedded within jsp programs to execute the given expressions. request. This is equal to the out. session. JSTL is a collection of predefined tages which can be placed into the JSP programs.tld *. After uncompressing we can find the following types of files. The x. param. The JSTL package is containing the following files. The tld should be imported into the required jsp programs before using them for each such import a prefix is also require..forEach etc.SATEESH N JSP Standard Tag Library ( JSTL ) JSTL is an enhancement of JSP which allows us to place custom tags into the jsp programs.tld contains the tags for xml access etc. The fmt..tld jstl.jar sql..jar : ( Java Archieve Files ) The tld file contains the names of the tags and their params that can be applied in JSP programs. For any custom tags 2 types of programs are required.out.. Using a custom tag : In order to use a custom tag the tld file should be imported to jsp program.tld contains the tags for sql access etc. The tld file is text file which contains the tag name and that params.tld contains the tags for formatting. The jar file contains the tag classes. date data etc.jar fmt. A prefix is also required. . Place all the jar files in the lib sub directory. All the expressions must be given within a block prefix with a ${ } ..tld contains the core tags such as if.tld The c.jar *.class After downloading the tld file and the jar files place all the tld files in the satclass\WEB-INF sub directory. The sql.tld standard.choose. 223 SATEESH N . Whenever a custom tag was used in a jsp program the corresponding tag class will be called from the jar file.

If any exception occurs it will be stored in a given variable. 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.tfee}” pattern=”##.jstlc1.20. </c:when> ---------<c:otherwise> // statement(s).jsp --> <%@ taglib uri="/WEB-INF/tlds/c.40. Syntax: <c:choice> <c:when test=”${condition1}” // statemnt(s).00” /> <!-. </c:catch> fmt : The following tag of fmt.SATEESH N Creating a variable : To create a variable the SET will be used.tld is used for formatting numbers.30. </c:otherwise> </c:choose> for : Ex: Ex : <c:forEach var=”i” items=”10. Ex: <c:catch var=”ex”> // statement(s). Ex: <fmt:formatNumber value=”${param.tld" prefix="c" %> <html> <body> <h2> sample program on JSP Tag Library </h2> <c:out value="sateesh"> </c:out> <br> <c:out value="testing"/> </c:out> </body> </html> 224 SATEESH N .##0.50”> <c:forEach vari=”i” begin=”10” end=”25” step=”2”> catch : Executes statement in a try block. Along with the choose we should also apply the when.

-" /> <br> Salary : <c:out value="${param.ename}" default=".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> <!-.sal}" default=".jsp --> <%@ taglib uri="/WEB-INF/tlds/c.empno}" default=".job}" default=".-" /> <br> </form> <br> </body> </html> 225 SATEESH N ..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..-" /> <br> Job: <c:out value="${param.jstlc2.deptno}" default=".empecho..-" /> <br> Employee Name: <c:out value="${param.-" /> <br> Department no.SATEESH N <!-.jstlc3..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> <!-.: <c:out value="${param.html --> <html> <body> <h2> Enter Employee Details </h2> <form name = EMPFORM method=GET action='http://localhost:8080/satclass/jstlc3.

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> <!-.SATEESH N <!-.jstlc7.jstlc6.jstlc5.jsp --> <%@ taglib uri='/WEB-INF/tlds/c.jsp --> <%@ taglib uri='/WEB-INF/tlds/c.jsp --> <%@ taglib uri='/WEB-INF/tlds/c.jsp --> <%@ taglib uri='/WEB-INF/tlds/c.jstlc4.tld' prefix="c" %> <html> <body> <c:set var="ch" value="3"/> <c:choose> <c:when test="${ch==1}"> <c:out value="one"/> </c:when> <c:when test="${ch==2}"> <c:out value="two"/> </c:when> 226 SATEESH N .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> <!-.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> <!-.

jsp --> <%@ taglib uri='/WEB-INF/tlds/fmt.##0.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> <!-.tld' prefix="c" %> <html> </body> <c:set var="n" value="1023" /> Format number : <fmt:formatNumber value="${n}" pattern="##.jsp --> <%@ taglib uri='WEB-INF/tlds/c.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.00"/> <br> <br> <c:out value="${n}" /> </c:forEach> </body> </html> 227 SATEESH N .jstlf1.tld' prefix="fmt" %> <%@ taglib uri='/WEB-INF/tlds/c.

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.studandemp.jsp'> <input type=hidden name=OPT value=2> <table width=100% bgcolor='#D5D5AA'border=0> <tr> <td> Enter EMployee Number </td> <td> <input type=text name=empno size=15> </td> </tr> <tr> <td> Enter Employee Name </td> <td> <input type=text name=ename size=25> </td> </tr> 228 SATEESH N .html --> <html> <body> <h2> STUDENT DETAILS </h2> <form name=STUDFORM method=POST action="http://localhost:8080/satclass/exjstl.SATEESH N <!-.

tld" prefix="c" %> <html> <body> <h2> Received Student Details </h2> Student Number: <c:out value="${param...jsp --> <%@ taglib uri="/WEB-INF/tlds/c..jsp'/> </c:if> <c:if test="${param.sname}" default=".OPT==2}"> <jsp:forward page='http://localhost:8080/satclass/empjstl.empjstl.studjstl.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> <!-.jsp --> <%@ taglib uri="/WEB-INF/tlds/c.tld" prefix="c" %> <html> <body> <h2> Received Employee Details </h2> <form action=""> Employee Number: 229 SATEESH N .-" /> <br> Student Name: <c:out value="${param.-" /> <br> Total Fee : <c:out value="${param.jsp'/> </c:if> </html> <!-.sno}" default=".OPT==1}"> <jsp:forward page='http://localhost:8080/satclass/studjstl.-" /> <br> </body> </html> <!-.tld' prefix="c" %> <html> <c:if test="${param.jsp --> <%@ taglib uri='/WEB-INF/tlds/c.tfee}" default=".exjstl.

..ename}" default=".SATEESH N <c:out value="${param.-" /> <br> </form> </body> </html> 230 SATEESH N .-" /> <br> Salary : <c:out value="${param.empno}" default="..sal}" default=".-" /> <br> Employee Name: <c:out value="${param.

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. 1. Define the Remote Interface : The remote interface contains the signatures of all the remote methods that a client application can call. Ex: public interface account extends Remote { public int getAccno( ) throws RemoteException. 5. Design the server program. Inorder to make the RMI possible two special programs are used which are known as stub & skeleton. Steps for designing the RMI program : 1. Create an interface that extends the Remote Interface and provide the signatures of all the remote methods. public void deposit(double int) throws RemoteException. 3. All the remote methods should throw RemoteException. Design the client program.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. C S Stub Java & RMI System Skeleton Java & RMI System NetWork Whenever object c calls a method of object s object c actually calls a method of stub. } 231 SATEESH N . Object s is a remote object to object c . Any returned value of such function will be given back to object c on the same style. The methods of s will become as remote methods to object c . 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. Generate the stub and skeletons. For example object c on machine one can call method f1 of object s which is on machine two. Create the implementation class. Define the Remote Interface. 2. 4.

a2 ). public public public public static static static static void bind( String name.bind(“ Second Account”. double balance. } } 3. Generate the stub and skeletons : Compile the implementation class using the rmi compiler rmic. Design the Server program : The server program should create an instance of the implementation class and should bind with a suitable name. Remote obj ) : Binds the remote object with the given name. } } 232 SATEESH N . 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 void deposit( doublel amt ) throws RemoteException { balance + = amt. The class should also contain a constructor that also throws RemoteException. Create a implementation class : The implementation class contain the definition of the remote method. Remote lookup( String url ) : Locate the remote object & returns its reference.SATEESH N 2. accountimpl a2 = new accountimpl( 102. 3000 ) . 4. Remote obj ) : unbind + bind. 5000 ) . void rebind( String name. void unbind( String name) : Unbinds the remote object. a1 ). create a class that extends UnicastRemoteObject and implements the interface of the step1 and overrides all its methods. } // overriding Remote interface methods public int getAccno( ) throws RemoteException { return accno. Naming. public accountimpl( ) throws RemoteException { accno = 101.bind( “First Account”. Ex: class server { public static void main( String args[ ] ) { accountimpl a1 = new accountimpl( 101. Naming. balance = 5000. Ex: public class accountimpl extends UnicastRemoteObject implements account { int accno.

lookup( “rmi://myserver/firstaccount” ). r. Ex: class client { public static void main( String args[ ] ) { // Find the remote objects account r = Naming. Distributed Programming with Java. } } Note : Before running the server program start the rmi registry. 1099 and provides communication between stub and skeletons. Each could be replaced with other implementations without affecting the others. The RMI Architecture [diagram from Qusay Mahmoud. The Transport Layer At the present time this is the standard TCP layer on IP. The Client program : The client program locates the remote object with the binded name and is able to call the remote methods.deposit(2000). // Remote method r = Naming. Manning.deposit(3000). It can access the remote object using naming lookup.SATEESH N 5. E:\adv\rmi>start rmiregistry rmiregistry works on portno.lookup( “rmi://myserver/secondaccount” ). Each implements its own interface and protocol. r. 233 SATEESH N . 2000] These layers are independent of one another.

The stub is a proxy at the client side for a remote object. Therefore. Objects are effectively "pass by reference" because using the (copy) of the reference. The skeleton represents information about the client at the server side. (One of the most annoying bugs in RMI programming is losing track of the stub!). 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 stubs and skeletons are not written by the programmer. the skeleton. what arrives at the server are copies of the actual objects referered to. They are generated by a special compiler called rmic. and various other purposes. the method receives copies of the actual parameters. However. you can change the public members of the actual object. 234 SATEESH N . as would be the case for a local call. as in C.Remote Reference Layer SATEESH N This middle layer sets up connections to remote address spaces. listens for incoming calls. Local Method Invocation Local method invocation Arguments to a method are always "pass by value". The only way to get a change back from the remote method is via the return value of the method. not the references to those objects. changes made to the object on the remote server are not reflected by on the original object still sitting on the client machine. in many cases. That is. these arguments are references to objects.    unmarshals incoming arguments calling the actual remote object implementation marshaling return values for transport to the client Remote vs. manages connections. The situation is more like it would be in a functional language such as Scheme or ML. Stub and Skeleton Layer The RMI programmer does not see the transport and remote reference layers. Stubs and skeletons represent the interface between the RMI system and the application programs. Remote method invocation With RMI. even if the arguments for a remote method (on the server) are references to (local on the client) objects. The object itself is not copied. The stubs and skeletons do appear to the programmer.

// Example RMI program // File name: account. Sometimes the registry is referred to as a "boostrap" registry because. for example. public interface account extends Remote { public int getAccno() throws RemoteException. However if you create your own class to be sent across the network. This is not a problem on small programs. strictly speaking. The serializable interface is just a marker. public void withdraw(double amt) throws RemoteException. it is "marshaled". it is only necessary for a first contact between client and server. When a serialized object is to be sent across the network. say. The object is converted into a byte stream for transmission. // These accounts can be accessible from remote locations. public void deposit(double amt) throws RemoteException.*. This runs on the same host as the RMI server. All the objects from which your object are composed must also be serializable. Charlie" ins Star Trek. 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.Serialization SATEESH N Objects sent as arguments or returned as results across the network must be serializable. ( References to such non-serializable objects can be declared transient to avoid this problem.java // Remote Interface // In the following program three accounts are binded on the remote server. public double getBalance() throws RemoteException. you must do if you implement. Object. They use that reference to invoke the remotely accessible methods of the server object. Client programs lookup the registered name on the server and get a reference to the remote object in return. Each object on the server host which which wishes to publicize its remotely accessible methods registereds by name on the registry. ("Beam me up. they must implement the Serializable interface. } 235 SATEESH N . Another problem can sometimes arise when you serialize your own object creations. public String getAccname() throws RemoteException. or flag. say. they can access each other without the help of the registry. There is no way provided to guarantee that the same name will not be registered twice. or your object cannot move down the net. Name clashes The RMI registry is quite simple. A class that implements the Serializable interface need not implement any special methods (as. the Runnable interface). you must declare it as implementing the serializable interface. At the receiving end it is "unmarshaled". That is.) The RMI Registry How does a client find a remote object that it wishes to invoke? RMI provides a simple name server called rmiregistry. import java. The object is reconstructed in its structured form from the incoming byte stream.rmi. all its subclasses inherit this property. and it is only a subclass of.) Marshaling The term marshaling applies to the process of serializing. Once client and server are in touch. Note that if a class is serializable.

accname = accname. System. String accname. public class accountimpl extends UnicastRemoteObject implements account { int accno. System.println("Account: "+accno+" Created"). } public String getAccname()throws RemoteException { return accname.*. this. } // Overriding Remote Interface Methods: 5 public int getAccno() throws RemoteException { return accno. double balance.*.accno = accno.SATEESH N // File name: accountimpl. } public double getBalance()throws RemoteException { return balance.println("Withdrawn: "+amt+" into Accno: "+accno).server. } public void withdraw(double amt)throws RemoteException { if(amt>balance) throw new RemoteException("Insufficient Funds").rmi. import java. } public void deposit(double amt)throws RemoteException { balance +=amt. double opeBalance)throws RemoteException { this.java import java.out. // current balance public accountimpl(int accno. String accname.out. this. System.balance = opeBalance. } } 236 SATEESH N .out. balance -=amt.rmi.println("Deposited: "+amt+" into Accno: "+accno).

io. and to operate on them import java.").bind("102". System.println("Finished .rmi.out.out. Naming. // creating 3 accounts accountimpl acc1 = new accountimpl(101. Naming.*. Naming."Sateesh N".bind("101"."Sateesh M"..out. System. accountimpl acc2 = new accountimpl(102..out.*.unbind("102"). // File name: accountclient.bind("103".java //server program. } catch(Exception ex) { System.SATEESH N // File name: accountserver. public class accountclient { static account r.acc2). System. public class accountserver { public static void main(String args[]) { try { System.java // to get the remote objects.25000). import java.. System. System. } } } D:\adv\rmi>java accountserver starting server….println("Press Enter to close: ").10000).println().unbind("103").exit(0).println("Error: "+ex)..acc1). Naming.out. accountimpl acc3 = new accountimpl(103.println("starting Server.println("Binding Accounts").5000). System. Naming.unbind("101").read().")."Sateesh S"...acc3)..*.in. Naming.rmi. Account: 101 created Account: 102 created Account: 103 created Binding Accounts Finished….to place 3 accounts which can be accessible from Remote location import java.out. public static void main(String args[]) { 237 SATEESH N .

// Accept choice MENU 1. String host = "localhost". Account Found case 2: System.print("Enter u r choice: ").Details { 3. Enter u r choice: 1 System. System.println("1.Open switch(ch) 2.Exit Enter u r choice: 101 Sateesh 25000.out.SATEESH N try { double amt.out.deposit(amt).print("Enter Withdraw Amount: "). System.getAccname()).parseInt(stdin.println("Invalid choice").out.Deposit case 1: // opens the given account 4.getBalance()). break.println("------------------------------").Open 2.out.parseDouble(stdin.out.out. case 5: break.Exit\n"). D:\adv\rmi>java accountclient System.parseDouble(stdin. Finding: rmi://localhost/101 System.readLine()).Deposit \n4.out. break.0 .println("Error: "+ex).out. break. if(args.out.Withdraw \n5. } // end of switch } // end of try catch(Exception ex) { System. System. default: System.println(). while(ch!=5) { try { System.lookup(url). String url = "rmi://"+host+"/"+accno.readLine()).println("Account Name : "+r.out. case 3: System.Withdraw 5. BufferedReader stdin = new BufferedReader(new InputStreamReader(System. ch = Integer.print("Enter Deposit Amount: ").println("Account Number : "+r. r. 5.out. System.Details \n3.println("Finding: "+url). System.withdraw(amt). amt = Double.parseInt(stdin.println("Done").println("\nMENU").println("Done").Exit int accno = Integer.getAccno()).out. System. System.Open \n2. case 4: System.println("Account Found").out.readLine()).out. break.Withdraw System. } 238 SATEESH N DETAILS Account Number: Account Name : Current Balance: MENU 1. int ch = 1.out.println("Current Balance: "+r. Enter an account number to open: 1 r = (account)Naming.readLine()).out. amt = Double.out.print("Enter an Account Number to open: ").in)).out.Deposit 4.length >=1) host = args[0].Details 3.println(" DETAILS "). r. System.

out.println("Error: "+ex).SATEESH N } // end of while } catch(Exception ex) { System. } } // end of main } // end of client 239 SATEESH N .

Sign up to vote on this title
UsefulNot useful