Sei sulla pagina 1di 219

.

E-Commerce Electronic Commerce -> Business thru Internet Three Types 1. Business to Business (B2B) (Intel Corporation - HCL) 2. Business to Customer (B2C) (Chennaisilks.com) 3. Customer to Customer. (C2C) (Bazee.com) Web Technology Designing-> SGML, HTML, DHTML, Frontpage, Dreamweaver, Photoshop (Static Pages) Client side scripting -> Javascript, VBScript, JScript Server Side scripting -> Servlets, ASP, JSP Storage -> Oracle, SQL - Server, Access Communication -> RMI,CORBA,DCOM, XML (Distributed Applications - Banking, Financial, Telecom) Java Components and Related Softwares Java & RMI(Remote Method Invocation) -> jdk1.2 (Java Development Kit) CORBA - Common Object Request Broker Architecture - jdk1.3 Java Servlets -> JSDK2.0 (Java Servlet Development Kit) JSP(Java Server Pages) - Java Web Server 2.0, Tomcat, Apache Server Java Bean - bdk2.0 (Bean Development Kit) EJB (Enterprise Java Beans)- Weblogic or Websphere or J2EE Server J2EE Server -> All the above components are integrated. Architecture Presentation layer -> Input and Output forms Business logic -> Validations Data layer -> Storing Data Four types of Architecture 1. Single Tier -> Foxpro, Clipper Single User application 2. Two Tier (or) Client/Server Technology-> VB and Oracle VB and SQL - Server Power Builder - SQLServer VB -> Presentation and Business Logic (Client) Oracle -> Data layer (Server) Multi User application

3. Three Tier -> HTML, ASP, Oracle (B2C, C2C) B2B Communication is not possible Intel Corporation HCL Java XML VB 4. Multi Tier (or) MVC Architecture (Model View Controller) HTML Javascript Servlets -> Act as a controller which redirects to components and pages JSP -> View (Input and Output forms, Integrates HTMl and Javascr EJB -> Model (Business logic) Oracle XML -> Communication JSP Servlets EJB MVC - Model View Controller Architecture (JSP, Servlets, EJB) Java Programming Java is an object oriented,multi-threaded programming language developed by Sun Microsystems in 1991. It is designed to be simple,small and portable across both platforms as well as Operating Systems. Java Development Environment (JDE) Java Compiler - generates bytecode - javac (Bulk code conversion) Java Interpreter - Execute the Bytecode - java (Line by Line Conversion) JVM -> Java Virtual Machine Source code | Compile -> Byte code -> .class file | Load the .class file into JVM | Execute the class file from JVM Disadvantage Execution speed is slow because of using bytecode and JVM Java Programming Types Application -> Console Based application (Worked in Command

Prompt) Datatypes, Operators, Identifiers, Character set Control Statements Arrays and Strings Class Concepts Inheritance Interface and package Exception Handling Streams Thread Networking Applet -> Web based application (worked in browser) Graphics (GDI Graphical Device Interface Applications) AWT(Abstract Window Toolkit) Components (Heavy Weight components) -> Components ar+ e developed by using c or c++; Menu Frame Panel Layouts Dialogs JFC/Swing --> Java Foundation Class (Light Weight Components -> ie, the components are developed by using Java Java Program Development Java development kit - jdk d:\>set path=%path%;d:\jdk1.3\bin; +d:\>path d:\>notepad first.java sample program class first { public static void main(String args[]) { System.out.println("My First Java Program"); } } d:\demo\DemoJava> javac first.java d:\demo\DemoJava> java first Note: Java program must be within a class java class name and the filename may be same

Description of Java program public - access specifier of the method main static - without creating object for class we can access the main method defined in the class using class name void - return type of main method main - method name String args[] - for passing arguments to main method. The argument type is String class. System - Package (Set of Predefined Classes) out - Class of System static method - println - Method of out System.out.println("Welcome to Java Programming"); System.out.print("Hello World"); Datatypes primitive datatypes char float long double int boolean Integer Type Size Range byte 1 byte -128 to +127 short2 bytes -32,768 to +32,767 int 4 bytes -2,147,483,648 to +2,147,483,647 long 8 bytes -9223372036854775808 to +9223372036854775807 character char 2 bytes unicode characters. boolean boolean 1 byte true or false float float 4 bytes - 3.4e38 to + 3.4e38 double 8 bytes -1.7e308 to +1.7e308 variables which holds some values Three kinds of variables 1. Instance variable

2. Local variable 3. class variable Instance variables are used to define attributes or the state of particular object. Local variables are used inside blocks as counters or in methods as temporary variables. class variables are global to a class and to all the instances of the class Declaring variables datatype var_name; Naming Conventions var_name must be starting with character special symbols are not allowed white spaces are not allowed only underscore allowed. int a; int emp_no; int emp no; //error int e1; int 1e; //error char s$; //error eg: int a; short b; float f; char c; (Variables) String str; (Instance (or) Object) Eg: //Non-static method class VarDecl { void pr(String s) { System.out.println(s); } public static void main(String args[]) { short a = 10;

float b = 3.14f; char c = 'a'; boolean d = true; String str = "Hello"; VarDecl vd=new VarDecl(); vd.pr("Short Value : " + a); vd.pr("Floating Value : " + b); vd.pr("Character Value : " + c); vd.pr("Boolean Value : " + d); vd.pr("String value : " + str); } } Eg: //Static Method class VarDecl { static void pr(String s) { System.out.println(s); } public static void main(String args[]) { short a = 10; float b = 3.14f; char c = 'a'; boolean d = true; String str = "Hello"; pr("Short Value : " + a); pr("Floating Value : " + b); pr("Character Value : " + c); pr("Boolean Value : " + d); pr("String value : " + str); } } Operators Arithmetic Relational +-*/% >, <, >=, <=, ==, !=

Logical &&, ||, ! Increment and ++ Decrement -Conditional ?: Assignment = Bitwise &, |, ^, <<, >> Arithmetic Assignment +=, -=, *=, /=, %= Programming Constructs types 1. Conditional Conditional if statements switch case while loop do while for break continue if statement if (condition) { statements; } if..else if (condition) { true statements; else { false statements if..else if if (condition) { true statements } else if(condition) { true statements } else { false statements; } nested if

} }

if (condition) { if (condition) { true statements } else { false statements } } else { false statements } Looping while loop while (condition) { statements } do while do { statements }while(condition); for loop for(initialization;condition; inc or dec) { statements } switch case switch(expression) { case 1: statements; break; case n: statements; break; default: statements; }

Eg: class CmdLine { public static void main(String args[]) { if (args.length < 2) { System.out.println("Invalid Command Line Arguments"); System.exit(0); } int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println("a = " + a); System.out.println("b = " + b); } } Eg: class CmdLine1 { public static void main(String args[]) { for(int i=0;i<args.length;i++) { System.out.println(args[i]); } } } Factorial,Fibonacci Series,Armstrong Number,Sum of Number OOPS Concept Object Oriented Programming System Five Characteristics 1. Classes and Objects 2. Overloading 3. Inheritance 4. Polymorphism 5. Data Abstraction and Data Encapsulation. Classes and Objects Class -> Collection of member variables and member functions.

Object (or) Instance -> To access the class member variable and functions. Syntax: class class_name { access_specifier datatype var_name access_specifier return_type function_name(arguments); } classname ins_name = new class_name; new -> Memory allocation for instance. ins.memberfunction(); Access Specifier private -> With in a class public -> Class, Subclass and main function(thru object) protected -> Class and Subclass no modifier -> similar to public ( Differed in package concept). Note: By default, the variables and functions are no modifier. 1. Defining class and object class students { private int sno; private String sname; public void setstud(int no,String name) { sno = no; sname = name; } public void dispstud() { System.out.println("Student No : " + sno); System.out.println("Student Name :" + sname); } public static void main(String args[]) { if(args.length < 2) { System.out.println("Invalid Arguments"); System.exit(0); } students s = new students();

int no = Integer.parseInt(args[0]); String name = args[1]; s.setstud(no,name); s.dispstud(); } } 2. Passing arguments and returning values. class circle { private int radius; public void setradius(int r) { radius = r; } public float calculate() { return 3.14f * radius * radius; } public static void main(String args[]) { if (args.length < 1) { System.out.println("Invalid Arguments"); System.exit(0); } circle c = new circle(); c.setradius(Integer.parseInt(args[0])); float area = c.calculate(); System.out.println("Radius : " + args[0]); System.out.println("Area : " + area); } } 3. Passing object as arguments. return type function name(arguments) int add(int,int); class rect { int len,bre; int totlen(rect r1,rect r2); rect combine(rect r1,rect r2);

int add(int x,int y); } Eg: class rectangle { private int len,bre; public void setrect(int l,int b) { len = l; bre = b; } public int totlen(rectangle t) { return len + t.len; } public int totbre(rectangle t) { return bre + t.bre; } rectangle combine(rectangle t) { rectangle temp = new rectangle(); temp.len = len + t.len; temp.bre = bre + t.bre; return temp; } public void disp() { System.out.println("Length : " + len + "\t Breadth : " + bre); } public static void main(String args[]) { rectangle r1 = new rectangle(); rectangle r2 = new rectangle(); rectangle r3 = new rectangle(); r1.setrect(2,3); r2.setrect(4,5); int tlen = r1.totlen(r2); int tbre = r1.totbre(r2); r3 = r1.combine(r2);

System.out.println("Total length : " + tlen); System.out.println("Total Breadth : " + tbre); r1.disp(); r2.disp(); r3.disp(); } } 4. Function overloading Function name similar but passing arguments are different. Eg: class exam { private int m1,m2,total; public void setmarks(int ma1,int ma2) { m1 = ma1; m2 = ma2; } public void setmarks() { m1 = 80; m2 = 100; } void calculate() { total = m1 + m2; } void disp() { System.out.println("Mark1 : " + m1 + "\t Mark2 " + m2 + "\t Total " + total); } public static void main(String args[]) { exam e1 = new exam(); exam e2 = new exam(); e1.setmarks(); e2.setmarks(70,80); e1.calculate(); e2.calculate();

e1.disp(); e2.disp(); } } Eg: class fun1 { public void disp(char a,int n) { System.out.println("Character : " + a); System.out.println("Number : " + n); } public void disp(int n,float f) { System.out.println("Number : " + n); System.out.println("Float : " + f); } public static void main(String args[]) { fun1 f = new fun1(); f.disp('a',10); f.disp(20,3.41f); } } Static Variables and Methods Static Variable * Variables are not reinitialized * Only one copy of the variable is created and shared by all objects * By default, Initialized with zero. No other initialization is permitted. Static Methods * If a method is declared as static, without creating object the method is accessed. Eg: class Rect { int length; int breadth; int area;

static int count; Rect(int a,int b) { length = a; breadth = b; count++; } Rect() { length = 0; breadth = 0; count++; } void calc() { area = length * breadth; } void display() { System.out.println("Length : " + length); System.out.println("Breadth : " + breadth); System.out.println("Area : " + area); } } class Rect1 { public static void main(String args[]) { System.out.println("No of object : " + Rect.count); Rect r1 = new Rect(10,20); r1.calc(); System.out.println("No of object : " + Rect.count); Rect r2 = new Rect(); r2.calc(); System.out.println("No of object : " + Rect.count); r1.display(); r2.display(); } } Eg:

class Rectangle { int length; int breadth; private static int count; static void displaycount() { System.out.println("No of Object : " + count); } Rectangle(int a,int b) { length = a; breadth = b; count++; } Rectangle() { length = 0; breadth = 0; count++; } void display() { System.out.println("Length : " + length); System.out.println("Breadth : " + breadth); } public static void main(String args[]) { Rectangle.displaycount(); Rectangle r1 = new Rectangle(10,20); Rectangle.displaycount(); Rectangle r2 = new Rectangle(); Rectangle.displaycount(); r1.display(); r2.display(); } } this keyword refers current object.

Eg: class point { int x,y; void init(int x,int y) { this.x = x; this.y = y; } void display() { System.out.println("x = " + x); System.out.println("y = " + y); } } class point1 { public static void main(String args[]) { point pp = new point(); pp.init(4,3); pp.display(); } } Eg: class load { String firstname; String lastname; int age; String profession; load assign(String firstname,String lastname,int age,String profession) { this.firstname = firstname; this.lastname = lastname; this.age = age; this.profession = profession; return this; }

load assign(String fn,String ln) { firstname = fn; lastname = ln; return this; } load assign(String fn,String ln,String prof) { firstname = fn; lastname = ln; profession = prof; return this; } load assign(String fn,int ag) { firstname = fn; age = ag; return this; } void print() { System.out.println(firstname + " " + lastname + " " + age + " " + profession); } public static void main(String args[]) { load fl = new load(); fl.assign("Naveen","Kumar",23,"Programmer"); fl.print(); fl.assign("Raj","Prabhu"); fl.print(); fl.assign("Chitra","Devi","Analyst"); fl.print(); fl.assign("Nithya",34); fl.print(); } } Wrapper Classes

Integer.parseInt() Float.parseFloat() Double.parseDouble() Byte.parseByte(); Constructor To initialize the object. syntax: class class_name { class_name() { statements; } } eg Overloading Constructor import java.io.*; class Const1 { private int sno; private String sname; Const1() { System.out.println("Constructor Called"); sno = 0; sname = ""; } void getdetails() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; System.out.print("Enter Sno : "); line = br.readLine(); sno = Integer.parseInt(line); System.out.print("Enter Sname : "); sname = br.readLine(); }

void putdetails() { System.out.println("Sno : " + sno); System.out.println("Sname : " + sname); } public static void main(String args[]) throws IOException { Const1 c1 = new Const1(); c1.putdetails(); c1.getdetails(); c1.putdetails(); } Constructor name are similar, but the passing arguments are different. Default Constructor classname() {} Copy Constructor An object is initialized with another object. exam(int n1,int n2){ } exam(exam e1) {} exam e1(10,20),e2(e1); eg import java.io.*; class students { private int sno; private String sname; private int mark1,mark2,total; students() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Student No : "); sno = Integer.parseInt(br.readLine()); System.out.print("Enter Student Name : "); sname = br.readLine(); System.out.print("Enter mark1 and mark2 : "); mark1 = Integer.parseInt(br.readLine()); mark2 = Integer.parseInt(br.readLine());

} students(int no,String name,int m1,int m2) { sno = no; sname = name; mark1 = m1; mark2 = m2; total = mark1 + mark2; } void putstud() { System.out.println("Sno : " + sno); System.out.println("Sname : " + sname); System.out.println("Mark1 : " + mark1); System.out.println("Mark2 : " + mark2); System.out.println("Total : " + total); } public static void main(String args[]) throws Exception { students s1 = new students(); students s2 = new students(100,"Kirthika",90,80); s1.putstud(); s2.putstud(); } } eg class marks { private int mark1,mark2,total; marks() {} marks(int m1,int m2) { mark1 = m1; mark2 = m2; } marks(marks m1) { mark1 = m1.mark1; mark2 = m1.mark2; }

void calc() { total = mark1 + mark2; } void putdetails() { System.out.println("Mark1 : " + mark1); System.out.println("Mark2 : " + mark2); System.out.println("Total : " + total); } public static void main(String args[]) { marks m1 = new marks(90,80); marks m2 = new marks(m1); marks m3 = new marks(); m1.calc(); m2.calc(); m1.putdetails(); m2.putdetails(); m3.putdetails(); } } Arrays Collection of like Data Types two types 1. single dimension 2. multi dimension single dimension Syntax: datatype var[] = new datatype[size]; Eg: int a[] = new int[10]; Initialization int a[5] = {1,2,3,4,5}; a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 a[4] = 5 char c[] = new char[10]; //character Array

Eg: import java.io.*; class Arr1 { public static void main(String args[]) throws IOException { int a[] = new int[10]; int n,i; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the value of n : "); n = Integer.parseInt(br.readLine()); for(i=0;i<n;i++) { System.out.print("Enter a[" + i + "] : "); a[i] = Integer.parseInt(br.readLine()); } System.out.println("The Given Values are"); for(i=0;i<n;i++) System.out.println(a[i]); } } Eg: import java.io.*; class Sort { public static void main(String args[]) throws Exception { int a[] = new int[10]; int n,i,j,temp; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the value of n : "); n = Integer.parseInt(br.readLine()); System.out.println(n); for(i=0;i<n;i++) { System.out.print("Enter a[" + i + "] : "); a[i] = Integer.parseInt(br.readLine()); }

for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } System.out.println("Sorted Values are"); for(i=0;i<n;i++) System.out.println(a[i]); } } MultiDimension * Java doesn't support multidimensional array. * However an array of Array is used. int a[] = new int[3]; a[0] = new int[3]; (a(0,0),(0,1),(0,2)) a[1] = new int[3]; (a(1,0),(1,1),(1,2)) a[2] = new int[3] (a(2,0),(2,1),(2,2)) Syntax: datatype var[][] = new datatype[row][col]; Eg: int a[][] = new int[3][3]; Eg: import java.io.*; class Matrix1 { public static void main(String args[]) throws Exception { int row,col; int a[][] = new int[3][3]; int i,j; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the Row and Column Value : ");

row = Integer.parseInt(br.readLine()); col = Integer.parseInt(br.readLine()); for(i=0;i<row;i++) { for(j=0;j<col;j++) { System.out.print("Enter a[" + i + "][" + j + "] : "); a[i][j] = Integer.parseInt(br.readLine()); } } System.out.println("The Given Matrix is "); for(i=0;i<row;i++) { for(j=0;j<col;j++) { System.out.print(a[i][j] + "\t"); } System.out.println(); } } } Inheritance * Reusability of code * Extensibility of code. Types of inheritance 1. Single 2. Multiple -> Java Does'nt support 3. Multilevel 4. Heirarchical 5. Hybrid -> Doesn't Support Single Base | Derived Multiple Base1 Base2 | | --------------------------|

Derived1 Multilevel Base1 | Derived1 | Derived2 Base1 -> Base class Derived1 -> Base1 -> BaseClass Derived2 -> Derived1 -> Immediate Class Derived2 -> Base1 -> Indirect Base Class Heirarchical Base | ----------------------------------------| | Derived1 Derived2 | | -------------------------------------------------------------------| | | | Derived11 Derived12 Derived21 Derived22 Hybrid Combination of Multiple and Multilevel Base | Derived1 Base2 | | | | --------------------------| Derived2 Single Inheritance Base | Derived Syntax: class base { statements;

} class derived extends base { statements; } Note: * Private members are not inherited * public and protected members are inherited * Constructor and finalizer are not inherited. Eg: class employee { private int eno; private String ename; public void setemp(int no,String name) { eno = no; ename = name; } public void putemp() { System.out.println("Empno : " + eno); System.out.println("Ename : " + ename); } } class department extends employee { private int dno; private String dname; public void setdept(int no,String name) { dno = no; dname = name; } public void putdept() { System.out.println("Deptno : " + dno); System.out.println("Deptname : " + dname); } public static void main(String args[])

{ department d = new department(); d.setemp(100,"aaaa"); d.setdept(20,"Sales"); d.putemp(); d.putdept(); } } super () -> Keyword used to call the base constructor; Eg: class emp1 { private int eno; private String ename; emp1(int no,String name) { System.out.println("Base Constructor"); eno = no; ename= name; } public void putemp() { System.out.println("Empno : " + eno); System.out.println("Empname : " + ename); } } class dept1 extends emp1 { private int dno; private String dname; dept1(int no,String name,int eno,String ename) { super(eno,ename); System.out.println("Derived Constructor"); dno = no; dname = name; } public void putdept() { System.out.println("Deptno : " + dno);

System.out.println("Deptname : " + dname); } public static void main(String args[]) { dept1 d = new dept1(20,"Sales",100,"Kirthika"); d.putemp(); d.putdept(); } } Multilevel Base | Derived1 | Derived2 Derived1 -> Base -> Direct Base class Derived2 -> Derived1 -> Direct Base class Derived2 -> Base -> Indirect Base class Syntax: class base { statements; } class derived1 extends base { statements; } class derived2 extends derived1 { statements; } Eg: class students { private int sno; private String sname; public void setstud(int no,String name) { sno = no;

sname = name; } public void putstud() { System.out.println("Student No : " + sno); System.out.println("Student Name : " + sname); } } class marks extends students { protected int mark1,mark2; public void setmarks(int m1,int m2) { mark1 = m1; mark2 = m2; } public void putmarks() { System.out.println("Mark1 : " + mark1); System.out.println("Mark2 : " + mark2); } } class finaltot extends marks { private int total; public void calc() { total = mark1 + mark2; } public void puttotal() { System.out.println("Total : " + total); } public static void main(String args[]) { finaltot f = new finaltot(); f.setstud(100,"Nithya"); f.setmarks(78,89); f.calc(); f.putstud();

f.putmarks(); f.puttotal(); } } Eg: //multilevel with constructor class students1 { private int sno; private String sname; students1(int no,String name) { sno = no; sname = name; } public void dispstud() { System.out.println("Student No : " + sno); System.out.println("Student Name : " + sname); } } class marks1 extends students1 { protected int mark1,mark2; marks1(int n1,int n2,int sno,String sname) { super(sno,sname); mark1 = n1; mark2 = n2; } public void dispmarks() { System.out.println("Mark1 : " + mark1); System.out.println("Mark2 : " + mark2); } } class finaltot1 extends marks1 { private int total; finaltot1(int n1,int n2,int no,String name)

{ super(n1,n2,no,name); total = mark1 + mark2; } public void disptotal() { System.out.println("Total : " + total); } public static void main(String args[]) { finaltot1 f = new finaltot1(90,89,100,"Kirthika"); f.dispstud(); f.dispmarks(); f.disptotal(); } } Interfaces Interface is nothing but java's Multiple Inheritance. Interface contains the declaration of the methods, and its implementation is made in another class. Syntax access interface interface_name { return_type method-name1(parameter list); return_type method-name2(parameter list); type final-varname1=value; type final-varname2=value; ..... return_type method-nameN(parameter list); type final-varnameN=value; } here access is either public or not used. Implementing interface access class class_name[extends superclass] [implements interface[interface...]] { //class body } Eg: Callback.java interface Callback {

public void call(int param); } Client.java class Client implements Callback { public void call(int p) { System.out.println("Interface Method = " + p); } public void nonIfaceMeth() { System.out.println("Non Interface method is also used"); } public static void main(String args[]) { Callback c = new Client(); c.call(5); // c.nonIfaceMeth(); } } Eg: AnotherClient.java class AnotherClient implements Callback { public void call(int p) { System.out.println("Square Value is : " + (p*p)); } public static void main(String args[]) { Callback c = new AnotherClient(); c.call(5); } } Eg:

IntStack.java interface IntStack { void push(int item); int pop(); } FixedStack.java class FixedStack implements IntStack { private int stack[]; private int tos; FixedStack(int size) { stack=new int[size]; tos=-1; } public void push(int item) { if(tos==stack.length-1) System.out.println("stack is full"); else stack[++tos]=item; } public int pop() { if(tos<0) { System.out.println("stack underflow"); return 0; } else return stack[tos--]; } public static void main(String args[]) { FixedStack mystack1=new FixedStack(5); FixedStack mystack2=new FixedStack(8); for(int i=0;i<6;i++) mystack1.push(i); for(int i=0;i<9;i++) mystack2.push(i); System.out.println("stack in mystack1"); for(int i=0;i<6;i++) System.out.println(mystack1.pop()); System.out.println("stack in mystack2");

for(int i=0;i<9;i++) System.out.println(mystack2.pop()); } } Packages Collection of Classes placed in a folder. Predefined Packages import java.io.* import java.util.Date import java.util.Vector import java.sql.* import java.swing.* import java.awt.*; Userdefined packages package package_name; class { } javac -d . filename.java -d -> Create a new directory with the name of package_name . -> refers current path Private Public Protected No Modifer Same package Same Class Yes Yes Yes Yes Same Package Sub Class Same Package Non Subclass Different Package Subclass Different Package Non Subclass Protection.java No No No No Yes Yes Yes Yes Yes No Yes No Yes Yes No No

package p1; public class Protection { int n=10; private int n_pri = 20; public int n_pub = 30; protected int n_pro = 40; public Protection() { System.out.println("Base Constructor"); System.out.println("n = " + n); System.out.println("n_pri = " + n_pri); System.out.println("n_pub = " + n_pub); System.out.println("n_pro = " + n_pro); } } javac -d . Protection.java Derived.java package p1; public class Derived extends Protection { public Derived() { System.out.println("Same Package Subclass"); System.out.println("n = " + n); System.out.println("n_pub = " + n_pub); System.out.println("n_pro = " + n_pro); } } javac -d . Derived.java SamePackage.java package p1; public class SamePackage { public SamePackage() { Protection p1 = new Protection(); System.out.println("Same Package Non Subclass"); System.out.println("n = " + p1.n); System.out.println("n_pub = " + p1.n_pub);

} } javac -d . SamePackage.java Demo.java import p1.Protection; import p1.Derived; import p1.SamePackage; class Demo { public static void main(String args[]) { Protection ob1 = new Protection(); Derived ob2 = new Derived(); SamePackage ob3 = new SamePackage(); } } javac Demo.java Protection2.java package p2; public class Protection2 extends p1.Protection { public Protection2() { System.out.println("Different Package Sub Class"); System.out.println("n_pub = " + n_pub); System.out.println("n_pro = " + n_pro); } } javac -d . Protection2.java OtherPackage.java package p2; public class OtherPackage { public OtherPackage() { p1.Protection ob = new p1.Protection(); System.out.println("Different Package Non subclass"); System.out.println("n_pub = " + ob.n_pub); } }

javac -d . OtherPackage.java Demo1.java import p2.Protection2; import p2.OtherPackage; class Demo1 { public static void main(String args[]) { Protection2 ob1 = new Protection2(); OtherPackage ob2 = new OtherPackage(); } } javac Demo1.java Advantages 1. Class Files are placed in a single directory 2. The packages are used in anywhere. String Class Collection of characters String constructors default constructor 1. String s=new String() char cs[]={'a','b','c'}; 2. String s = new String(cs); 3. String(char chars[],int startindex,int numchars) char cs[]={'a','b','c','d','e','f'}; String s=new String(cs,2,3); cde Hash Table A hash table stores information using a special calculation on the object to be stored. A hash code is produced as a result of a calculation. The hash code is used to choose the location in which to store the object. When the information needs to retrieved, the same calculations is performed, the hash code is determined and a lookup of that location in the table results in the value that was stored there previously. String Arithmetic '+' - Concatenation toString() - convert into String += Operator will also work for strings. Str1+=Str2; (str1=str1+str2)

String Class Methods length() - number of characters in String. String s1="hello" int len=s1.length(); len=5 charAt(int) - The character at a location in the String String s1="hello world" char a = s1.charAt(2) a=l getChars() , getBytes() - copy chars or bytes in an external array. String s1 = "Hello World"; char c[] = {'a','b','c'}; s1.getChars(0,s1.length,c,3); s1.getChars(int,int,char[],int) c[] = {'a','b','c'}; toCharArray() - produces a char[] containing the characters in the string toByteArray() - Produces a byte[] containing the characters in the string. equals() , equalsIgnoreCase() - An equality check on the contents of the two strings str1="hello" str2="Hello" str1.equals(str2) = false str1.equalsIgnoreCase(str2) = true CompareTo() - Result is negative,zero or positive depending on the lexiographical ordering of the string and the argument.Uppercase and Lowercase are not equal. str1 > str2 = +ve value str1 < str2 = -ve value str1 == str2 = 0 startsWith() - Boolean result indicates if the string starts with the argument String s1="hello" s1.startsWith("h");=true s1.startsWith("H"); = false endsWith() - Boolean result indicates if the string ends with the argument String s1="Hello"; s1.endsWith("o"); - True s1.endsWith("h");- false

indexOf , lastIndexOf() -Returns -1 if the argument is not found within this string, otherwise returns the index where the argument starts. lastIndexOf searches backwards from end. String s1="This is a sample String for indexOf Method"; s1.indexOf('s') = 3 s1.indexOf('s',5)=6 s1.lastIndexOf('s') = 10 s1.lastIndexOf('s',9) = 6 subString() - Returns a new String containing the specified character set. subString(startindex,endindex) String s1 = "Welcome"; s1.subString(2,4) - lc concat() - Returns a new string object containing strings characters followed by the characters in the argument String s1="hello" String s2="world" s1.concat(s2); -> helloworld replace() - Returns a new String object with the replacements made. uses the old string if no matches found. replace('Oldchar','newchar') String s1="hello" s1.replace('l','w') = hewwo toLowerCase(),toUpperCase() - returns a new string object with case of all letters changed. uses the old string if no changes to be made. String s1 = "HELLO"; s1.toLowerCase(); String s2 = "hello"; s2.toUpperCase(); trim() - Returns a new string object with the Whitespace removed from each end. trim(" hello ") -> hello Eg: class Arith { String fname="Aswath"; String lname="Narayanan";

void show() { System.out.println("The fullname is " + fname + " " + lname); } public static void main(String args[]) { Arith a1=new Arith(); a1.show(); } } Eg: class hash { public static void main(String args[]) { String s1="world"; String s2="Hello"; System.out.println("The hash code for " + s1 + " is " + s1.hashCode()); System.out.println("The hash code for " + s2 + " is " + s2.hashCode()); } } Eg: class equaldemo { public static void main(String args[]) { String s1="Hello"; String s2="Hello"; String s3="Good bye"; String s4="HELLO"; System.out.println(s1 + " equals " + s2 + " is " + s1.equals(s2)); System.out.println(s1 + " equals " + s3 + " is " + s1.equals(s3)); System.out.println(s1 + " equals " + s4 + " is " + s1.equals(s4)); System.out.println(s1 + " equals " + s4 + " is " + s1.equalsIgnoreCase(s4)); } } Eg: class Strings { int i; String name[]={"Aswath","Aswin","Anand","Aditya","Anirudh"}; void show() { System.out.println("My favourite names are "); for(i=0;i<5;i++) { System.out.println(name[i]); }

} public static void main(String args[]) { Strings s=new Strings(); s.show(); } } Eg: class StringMeth { public static void main(String args[]) { String s1 = "This is a sample String"; String s2 = " Hello "; String s3 = "Hello World"; String s4 = "Hello"; String s5 = "HELLO"; System.out.println(s1 + ".length() : " + s1.length()); System.out.println(s1 + ".charAt(2) : " + s1.charAt(2)); System.out.println("Character Array"); char c[] = new char[s1.length()+3]; c[0] = 'a';c[1] = 'b';c[2] = 'c'; s1.getChars(0,s1.length(),c,2); for(int i=0;i<c.length;i++) System.out.print(c[i] + " "); System.out.println(); System.out.println("Byte Array"); byte b[] = new byte[s3.length()]; s3.getBytes(0,s3.length(),b,0); for(int i=0;i<b.length;i++) System.out.print(b[i] + " "); System.out.println(); System.out.println(s4 + ".compareTo(" + s3 + ") = " + s4.compareTo(s3)); System.out.println(s3 + ".startsWith(H) = " + s3.startsWith("H")); System.out.println(s3 + ".endsWith(u) = " + s3.endsWith("u")); System.out.println(s3 + ".indexOf(o) = " + s3.indexOf('o')); System.out.println(s3 + ".indexOf(o,5) = " + s3.indexOf('o',5)); System.out.println(s3 + ".lastIndexOf(o) = " + s3.lastIndexOf('o'));

System.out.println(s3 + ".lastIndexOf(o,6) = " + s3.lastIndexOf('o',6)); System.out.println(s3 + ".substring(2,7) = " + s3.substring(2,7)); System.out.println(s1 + ".concat(s2) = " + s1.concat(s2)); System.out.println(s4 + ".replace(l,w) = " + s4.replace('l','w')); System.out.println(s4 + ".toUpperCase() = " + s4.toUpperCase()); System.out.println(s5 + ".toLowerCase() = " + s5.toLowerCase()); System.out.println(s2 + ".trim() = " + s2.trim()); } } StringBuffer StringBuffer is a peerclass of string that provides much common use functionality of strings. String represents fixed-length-character sequences. Stringbuffer represents varied length character sequences. StringBuffer may have characters and substrings inserted in the middle or appended at the end. The compiler automatically creates a stringbuffer to evaluate certain expressions, in particular when the overloaded operators + and += operator are used with the string objects. Constructor StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer(16); String s; StringBuffer sb = new StringBuffer(s); StringBuffer Methods toString() - Creates a string from this stringbuffer or convert to string length() - returns the number of character in the stringbuffer capacity() - returns current number of spaces allocated. boolean ensureCapacity() - makes the stringbuffer hold atleast the desired no. of spaces. setLength() - truncates or expand the previous character string. if expanding pads with nulls. charAt(int) - returns the char at that location in the buffer setCharAt(int,char) - modifies the value of that location. StringBuffer sb = "Hello"; sb.setCharAt(2,'w'); Hewlo;

getChars() - copy chars into an external array. There isno getBytes() as in string append() - The argument is converted to a string and appended at the end of the current buffer insert() - The second arg is converted to a string and inserted into the current buffer beginning at the offset. reverse () - The order of the character in the buffer is reversed. Eg: class StringBuf { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello World"); System.out.println(sb + ".capacity() = " + sb.capacity()); System.out.println(sb + ".length() = " + sb.length()); System.out.println(sb + ".insert(5,aaa) = " + sb.insert(5,"aaa")); System.out.println(sb + ".capacity() = " + sb.capacity()); System.out.println(sb + ".length() = " + sb.length()); System.out.println(sb + ".append(bbbb) = " + sb.append("bbbb")); System.out.println(sb + ".reverse() = " + sb.reverse()); } } Exception Handling An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause the system to crash. Types of Errors Compilation time errors Runtime Errors Compile Time errors * Missing Semicolons * Missing or mismatch of brackets in classes and methods * Mispelling of identifiers and keywords * Missing double quotes in string * use of undeclared variables. * Incompatible types in assignments/intialization

* Bad references to objects * and so on Runtime Errors * Dividing an integer by zero * Accessing an element that is out of the bounds of an array * Trying to store a value into an array of an incompatible class or type. * Trying to cast an instance of a class to one of its subclasses * Passing a parameter that is not in a valid range. * Trying to illegaly change the state of a thread. * Attempting to use the negative size for an array. * Using a null object references as a legitimate object references to access a method or variable. * Converting invalid string to a number * Accessing a character that is out of bounds of a string Exception An exception is a condition that is caused by a run-time error in the program. When the java interpreter encounters an error such as dividing an integer by zero, it creates an exception objects and throws. Common Java Exceptions ArithmeticException - caused by math erros that is divide by zero ArrayIndexOutOfBoundsException - caused by bad array indexes +ArrayStoreException - caused when a program tries to store the wrong type of data in an exception. FileNotFoundException - caused by an attempt to access a nonexistent file. IOException - caused by general I/O failures such as inability to read from a file. NullPointerException - Caused by referencing a null object NumberFormatException - Caused when a conversion between strings and number fails. OutOfMemoryException - caused when ther's not enough memory to allocate a new object SecurityException - caused when an applet tries to perform an action not allowed by the browsers security setting StringIndexOutOfBoundsException - caused when a program attempts to access nonexistent character position in a string NegativeArraySize Exception - declare the array size as negative Syntax: try { statement;//generates an exception

} catch(Exception-type e){ statement; } finally { statements; } Multiple Catch statements Syntax: try { statement; }catch(Exception-type1 e) { statement; }catch(Exception-type2 e) { statement; }..... }catch(Exception-typeN e) { statement; } Throwing our own exceptions throw new Throwable_subclass; throw new ArithmeticException(); throw new NumberFormatException(); Exception is a subclass of Throwable and Therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught. class MyException extends Throwable { .... } class MyException extends Exception { statements; throw new MyException("String"); } throws - Exception handler throws the exception outside the program throw - throw a generated exception to anywhere of the program. Eg: class Exp1 { public static void main(String args[]) {

int c; try { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); c = a/b; System.out.println("c = " + c); }catch(ArithmeticException e) { System.out.println("Arithmetic Exception Raised"); c=0; }catch(ArrayIndexOutOfBoundsException e) { System.out.println("Invalid Arguments"); } catch(NumberFormatException e) { System.out.println("String Not allowed"); }finally { System.out.println("Finally Block"); } System.out.println("End of Main Program"); } } Eg: import java.io.*; class MyException extends Exception { private int a; MyException(int b) { a = b; } public String toString() { return "MyException [" + a + "]"; } }

class UserDefException { int x; final int k=5; String line; void getInt() { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Do some guess work to generate your own exception"); System.out.println("Enter number between 1 and 10"); while((line = br.readLine()) != null) { x = Integer.parseInt(line); if(x == k) { System.out.println("Congrats!! you have generated an Exception!!"); throw new MyException(x); } else { System.out.println("Wrong guess! Try Again"); continue; } } }catch(MyException m) { System.out.println("Generated Exception : " + m); } catch(NumberFormatException e) { System.out.println("Sorry No Characters"); System.out.println("Exiting..."); } catch(IOException e) {}

} public static void main(String args[]) { UserDefException e = new UserDefException(); e.getInt(); } } Eg: cc Multitasking Multithreading - A single Program can perform multiple task Thread A thread is a smallest unit of dispatchable code. Time slicing method First Process - 5seconds Second process - 5 seconds Third Process - 5seconds Queue - The Process are stored in a queue. (First in First Out) Thread Priorities Min Priority - 1 Norm Priority - 5 Max Priority - 10 Creating a Thread Two ways 1. Using Runnable Interface 2. Extending Thread Class States of Thread Four states associated with a thread namely new runnable dead blocked Thread obj; //new born state obj.start(); run(); //runnable state sleep(1000) //blocked wait(); //blocked notify() suspend(); //blocked resume();

stop(); //dead new: When a thread is created, it is in the new state. New implies that the thread object has been created but it has not started running. It requires the start() method to start it. Runnable A thread is said to be in runnable state, when it is executing a set of instructions. The run() method contains the set of instructions. This method is called automatically after the start() method. Dead: The normal way for a thread to die is by returning from its run() method. We can also call stop(), but this throws an exception that's a subclass of Error(which means we normally do not catch it). Blocked: The thread could be run but there is something that prevents it. While a thread is in the blocked state the sheduler will simply skip over it and not give it any CPU time. Until a thread re-enters the runnable state it will not perform any operations. wait() - notify() suspend() - resume() sleep(milliseconds) Common Methods of thread start() - The start() starts execution of the invoking object . It can throw an IllegalThreadStateException if the thread was already started. stop() - This method terminates the invoking object. suspend() - This method suspends the invoking object. The thread will become runnable again if it gets the resume() method. sleep() - This method suspends execution of the executing thread for the specified number of milliseconds. It can throw an InterruptedException. The Syntax is : public void sleep(long ms) resume() - the resume() method restarts the suspended method at the point at which it was halted. Using runnable interface

The Runnable interface contains only run(), which should be included in a classes implementing them. Methods of thread class activeCount() returns the current number of active Threads in this thread group. currentThread() Returns a reference to the currently executing thread object & is a static method. isAlive() To check whether given thread is alive getName() Gets and return this Thread's name getPriority() Gets and returns the Thread's priority setName(String) Sets the Thread's Name setPriority(int) sets the Thread's priority toString() Returns a string representation of the Thread, including the threads name,priority and thread group Runnable interface void run() Thread(Runnable threadob, String ThreadName) Methods in Thread isAlive() - This method is used to check about a thread whether the thread is dead or alive. If the thread is in run state, it will return true, otherwise it will return false (ie., after the lifetime) join() - This method is used to keep a particular thread in wait state until the mentioned thread finished its work. join() method is closely related to wait() and sleep() method. wait() - it will be in wait state for a long time. sleep() - it will be in wait state for a specified time. join() - it will be in wait state until the other thread finishes their processes. Eg: class ThreadDemo implements Runnable { Thread t; ThreadDemo(String name) { t = new Thread(this,name); //new born state t.start(); } public void run() { try

{ for(int i=1;i<=5;i++) { System.out.println(t.getName() + " : " + i); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("Exception : " + e); } } public static void main(String args[]) { System.out.println("Main Thread"); ThreadDemo d1 = new ThreadDemo("Child"); try { for(int j=1;j<=5;j++) { System.out.println("Main : " + j); Thread.sleep(1000); } }catch(InterruptedException e) { System.out.println("Exception : " + e); } } } Eg: class NewT extends Thread { Thread t; NewT(String msg) { t = new Thread(this,msg); t.start(); } public void run() { try { for(int i=1;i<=5;i++) { System.out.println(t.getName() + " : " + i);

} t.sleep(1000); }catch(InterruptedException e) {} System.out.println(t.isAlive()); } } class Joindemo { public static void main(String args[]) { NewT t1 = new NewT("One"); NewT t2 = new NewT("Two"); NewT t3 = new NewT("Three"); try { t1.t.join(); t2.t.join(); t3.t.join(); }catch(InterruptedException e){} System.out.println("Main Thread Exiting \n"); } } Thread Priority MAX_PRIORITY - 10 MIN_PRIORITY - 1 NORM_PRIORITY - 5 Eg: class NT extends Thread { Thread t; NT(String m) { t = new Thread(this,m); System.out.println("\n Thread : "+t.getName()); System.out.println("Priority : "+t.getPriority()); t.start(); } public void run() { System.out.println("New Priority : "+t.getPriority()); try { System.out.println("\n"+t.getName()+" is in wait stage"); t.sleep(1000); } catch(Exception e) { } System.out.println(t.getName()+" completed the Process"); }

} class Priority { public static void main(String sp[]) { System.out.println("\n Main Starts the Process"); NT x = new NT("One"); NT y = new NT("Two"); x.t.setPriority(3); y.t.setPriority(8); System.out.println("\n Main Conpleted the Process"); } } Synchronization When the first thread completes its execution then the second thread is called. Eg: // This program is not synchronized class Callme { void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); }catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ,String s) { target=targ; msg=s; t=new Thread(this); t.start(); } public void run() { target.call(msg); }

} class Synch { public static void main(String args[]) { Callme target = new Callme(); Caller ob1=new Caller(target,"Hello"); Caller ob2=new Caller(target,"synchronized"); Caller ob3=new Caller(target,"World"); try { ob1.t.join(); ob2.t.join(); ob3.t.join(); }catch(InterruptedException e) { System.out.println("Interrupted"); } } } Eg: // This program is synchronized class Callme { synchronized void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); }catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ,String s) { target=targ; msg=s; t=new Thread(this); t.start(); } public void run() {

target.call(msg); } } class Synch1 { public static void main(String args[]) { Callme target = new Callme(); Caller ob1=new Caller(target,"Hello"); Caller ob2=new Caller(target,"Synchronized"); Caller ob3=new Caller(target,"World"); try { ob1.t.join(); ob2.t.join(); ob3.t.join(); }catch(InterruptedException e) { System.out.println("Interrupted"); } } } DeadLock Thread X Synchronized Thread Y - Synchronized Eg: class First { synchronized void show(Second s) { System.out.println("\n Now Thread is in First"); try { Thread.sleep(1000); } catch(Exception e) { } s.disp(); } synchronized void disp() { System.out.println("\n Inside First Class Disp Method"); } } class Second { synchronized void show(First f) { System.out.println("\n Now Thread is in Second"); try { Thread.sleep(1000);

} catch(Exception e) { } f.disp(); } synchronized void disp() { System.out.println("\n Inside Second Class Disp Method"); } } class DeadLock implements Runnable { First f = new First(); Second s = new Second(); DeadLock() { System.out.println("\n Current Thread : "+Thread.currentThread().getName()); Thread t = new Thread(this,"Demo"); System.out.println("\n Created Thread : "+t.getName()); t.start(); f.show(s); System.out.println("\n After Executing f.show()"); } public void run() { s.show(f); System.out.println("\n Again Executing s.show()"); } public static void main(String sp[]) { new DeadLock(); } } File Handling The data is stored in floppy disk or hard disk using the concept of file. It is collection of related records placed in a particular area on the disk. A record is composed of several fields in a group of characters. Characters in java are Unicode Characters composed of two bytes, each byte containing eight binary digits. In java file input get from 1. keyboard 2. mouse 3. disk 4. network 5. memory

output goto 1. screen 2. printer 3. disk 4. memory 5. network Streams we can get input from file and stored in a destination file. In between getting and storing the streams can be worked as a connector. Two types of streams input stream output stream Stream classes two types of stream classes 1. byte stream classes 2. character stream classes Types of byte stream classes 1. InputStream classes 2. OutputStream classes Input stream classes 1. FileInputStream 2. SequenceInputStream 3. PipeInputStream 4. ByteArrayInputStream 5. ObjectInputStream 6. StringBufferInputStream 7. FilterInputStream 1. BufferedInputStream 2. PushbackInputStream 3. DataInputStream Class 4. DataInput Interface InputStream functions * Reading bytes * Closing Streams * Marking position in streams * Skipping ahead in a stream * Finding the number of bytes in a stream InputStream Methods read() Reads a byte from the input stream read(byte b[]) read an array of bytes into b

read(byte b[],int n,int m) reads m bytes into b starting from the nth byte available() give no.of bytes available in the input skip(n) skips over n bytes from the input stream reset() goes back to the beginning of the stream close() close the input stream DataInput Interface methods readShort() readInt() readLong() readFloat() readDouble() readLine() readChar() readBoolean() OutputStream Classes 1. FileOutputStream 2. ObjectOutputStream 3. PipedOutputStream 4. ByteArrayOutputStream 5. FilterOutputStream 1. BufferedOutputStream 2. PushbackOutputStream 3. DataOutputStream Class 4. DataOutput Interface OutputStream functions * Writing bytes * Closing streams * Flushing Streams OutputStream Methods write() - Writes a byte to the output stream write(byte[] b) - Writes all bytes in the array b to the output stream write(byte b[],int n,int m) - Write m bytes from array b starting from the nth byte close() - Close the outputstream flush() - Flushed the outputstream DataOutput Interface Methods writeShort() writeInt()

writeLong() writeFloat() writeDouble() writeBytes() writeChar() writeBoolean() Eg: import java.io.*; class FileDemo { static void p(String s) { System.out.println(s); } public static void main(String args[]) { File f1=new File("d:\\demo\\demojava\\sample.txt"); p("File name : " + f1.getName()); p("Path : " + f1.getPath()); p("Abs Path : " + f1.getAbsolutePath()); p("Parent : " + f1.getParent()); p(f1.exists() ? "exists" : "Does not exists"); p(f1.canWrite() ? "is writeable" : "is not writeable"); p(f1.canRead() ? "is readable" : "is not readable"); p("is " + (f1.isDirectory() ? " " : "not " + " a Directory")); p(f1.isFile() ? "is normal file" : " might be a named pipe"); p(f1.isAbsolute() ? " is absolute" : "is not absolute"); p("File last modified : " + f1.lastModified()); p("File Size : " + f1.length() + " Bytes"); } } Eg: //FileInputStreamDemo import java.io.*; class FileInputStreamDemo { public static void main(String args[]) throws IOException { FileInputStream f = new FileInputStream("sample.txt"); int size = f.available();

System.out.println("Available Bytes : " + size); int n = size / 4; System.out.println("Reading First " + n + " bytes using readmethod"); for(int i=0;i<n;i++) System.out.print((char)f.read() + " "); System.out.println(); System.out.println("Still Available : " +f.available()); byte b[] = new byte[n]; System.out.println("Reading next " + n + " bytes using read byte array"); f.read(b); System.out.println(new String(b,0,b.length)); System.out.println("Still Available : " + f.available()); n = f.available() / 2; System.out.println("Skipping Half of the Bytes"); f.skip(n); System.out.println("Still Available : " + f.available()); System.out.println("Reading Last " + n + " bytes"); f.read(b,0,10); System.out.println(new String(b,0,10)); System.out.println("Still Available : " + f.available()); } } Eg: //Demonstrate Fileoutputstream import java.io.*; class FileOutputStreamDemo { public static void main(String args[]) throws IOException { String source = "Sample String to write data into a file"; byte buf[] = source.getBytes(); FileOutputStream f1 = new FileOutputStream("file1.txt"); for(int i=0;i<buf.length;i+=2) f1.write(buf[i]); System.out.println("File1 Written"); FileOutputStream f2 = new FileOutputStream("file2.txt"); f2.write(buf);

System.out.println("File2 Written"); FileOutputStream f3 = new FileOutputStream("file3.txt"); f3.write(buf,0,10); System.out.println("File3 Written"); } } Eg: //Demonstrate ByteArrayOutputStream import java.io.*; class ByteArrayOutputStreamDemo { public static void main(String args[]) throws IOException { ByteArrayOutputStream f = new ByteArrayOutputStream(); String source = "Sample string for byte array"; byte buf[] = source.getBytes(); f.write(buf); System.out.println("Convert to string"); System.out.println(f.toString()); System.out.println("To an Byte array"); byte b[] = f.toByteArray(); for(int i=0;i<b.length;i++) System.out.print((char)b[i] + " "); System.out.println(); System.out.println("To an Outputstream"); FileOutputStream f1 = new FileOutputStream("test.txt"); f.writeTo(f1); System.out.println("Doing Reset"); f.reset(); for(int j=0;j<3;j++) f.write('X'); System.out.println(f.toString()); } } Eg: // Demonstrate ByteArrayInputStream import java.io.*; class ByteArrayInputStreamDemo { public static void main(String args[]) throws IOException { String tmp="abcdefghijklmnopqrstuvwxyz";

byte b[]=tmp.getBytes(); ByteArrayInputStream input1=new ByteArrayInputStream(b); ByteArrayInputStream input2=new ByteArrayInputStream(b,0,3); int c; while((c=input2.read()) != -1) { System.out.println((char)c); } System.out.println(new String(b,0,input1.available())); } } Eg: //use buffered Input import java.io.*; class BufferedInputStreamDemo { public static void main(String args[]) throws IOException { String s="This is a &copy; copyright symbol "+ "but this is &copy not.\n";` byte buf[]=s.getBytes(); ByteArrayInputStream in=new ByteArrayInputStream(buf); BufferedInputStream f=new BufferedInputStream(in); int c; boolean marked=false; while((c=f.read()) != -1) { switch(c) { case '&': if(!marked) { f.mark(32); marked=true; }else { marked=false; } break; case ';': if(marked) { marked=false; System.out.print("(c)"); } else System.out.print((char)c); break;

case ' ': if(marked) { marked=false; f.reset(); System.out.print('&'); }else System.out.print((char)c); break; default: if(!marked) System.out.print((char)c); break; } } } } Eg: //Demonstrate unread(). import java.io.*; class PushbackInputStreamDemo { public static void main(String args[]) throws IOException { String s="if (a == 4) a = 0;\n"; byte buf[]=s.getBytes(); ByteArrayInputStream in=new ByteArrayInputStream(buf); PushbackInputStream f=new PushbackInputStream(in); int c; while((c=f.read()) != -1) { switch(c) { case '=': if((c=f.read()) == '=') System.out.print(".eq."); else { System.out.print("<-"); f.unread(c); } break; default: System.out.print((char)c); break; }

} } } Character Stream classes Two types reader stream classes writer stream classes ReaderStream Classes 1. BufferedReader 2. StringReader 3. CharArrayReader 4. PipeReader 5. InputStreamReader 1. FileReader 6. FilterReader 1. PushbackReader WriterStream classes BufferedWriter PrintWriter CharArrayWriter StringWriter FilterWriter PipeWriter OutputStreamWriter 1. FileWriter Input / Output Exceptions EOFException - Signals that an end of file or end of stream has been reached unexpectedly during the input FileNotFoundException - informs that a file could not be found InterruptedIOException - Warns an I/O Operations has been interrupted IOException - Signals that an I/O Exception of some sort has occured Eg: //Demonstrate FileReader import java.io.*; class FileReaderDemo { public static void main(String args[]) throws Exception { FileReader fr=new FileReader("file2.txt"); BufferedReader br=new BufferedReader(fr);

String s; while((s=br.readLine()) != null) { System.out.println(s); } fr.close(); } } Eg: //Demonstrate FileWriter import java.io. class FileWriterDemo { public static void main(String args[]) throws Exception { String source="Now is the time for all good men\n" +" to come to the aid of their country\n" +" and pay their due taxes."; char buffer[]=new char[source.length()]; source.getChars(0,source.length(),buffer,0); FileWriter f0=new FileWriter("file1.txt"); for (int i=0;i<buffer.length;i+=2) { f0.write(buffer[i]); } f0.close(); FileWriter f1=new FileWriter("file2.txt"); f1.write(buffer); f1.close(); FileWriter f2=new FileWriter("file3.txt"); f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4); f2.close(); } } Eg: //Demonstrate CharArrayReader import java.io.*; public class CharArrayReaderDemo { public static void main(String args[]) throws IOException { String tmp="abcdefghijklmnopqrstuvwxyz"; int length=tmp.length(); char c[]=new char[length]; tmp.getChars(0,length,c,0); CharArrayReader input1=new CharArrayReader(c);

CharArrayReader input2=new CharArrayReader(c,0,5); int i; System.out.println("Input1 is:"); while((i=input1.read()) != -1) { System.out.print((char)i); } System.out.println(); System.out.println("Input2 is:"); while((i=input2.read()) != -1) { System.out.print((char)i); } System.out.println(); } } Eg: //Demonstrate CharArrayWriter import java.io.*; class CharArrayWriterDemo { public static void main(String args[]) throws IOException { CharArrayWriter f=new CharArrayWriter(); String s="This should end up in the array"; char buf[]=new char[s.length()]; s.getChars(0,s.length(),buf,0); f.write(buf); System.out.println("Buffer as a string"); System.out.println(f.toString()); System.out.println("Into array"); char c[]=f.toCharArray(); for(int i=0;i<c.length;i++) { System.out.print(c[i]); } System.out.println("\n To a FileWriter()"); FileWriter f2=new FileWriter("test.txt"); f.writeTo(f2); f2.close(); System.out.println("doing a reset"); f.reset(); for(int i=0;i<3;i++) f.write('X'); System.out.println(f.toString());

} } Eg: //use buffered input import java.io.*; class BufferedReaderDemo { public static void main(String args[]) throws IOException { String s = "This is a &copy; copyright symbol "+ "but this is &copy not.\n"; char buf[]=new char[s.length()]; s.getChars(0,s.length(),buf,0); CharArrayReader in=new CharArrayReader(buf); BufferedReader f=new BufferedReader(in); int c; boolean marked=false; while((c=in.read()) != -1) { switch(c) { case '&': if(!marked) { f.mark(32); marked=true; } else { marked=false; } break; case ';': if(marked) { marked=false; System.out.print("(c)"); } else System.out.print((char)c); break; case ' ': if(marked) { marked=false; f.reset(); System.out.print('&'); } else System.out.print((char)c); break;

default: if(!marked) System.out.print((char)c); break; } } } } Eg: //Demonstrate unread() import java.io.*; class PushbackReaderDemo { public static void main(String args[]) throws IOException { String s="if (a == 4) a = 0 \n"; char buf[]=new char[s.length()]; s.getChars(0,s.length(),buf,0); CharArrayReader in=new CharArrayReader(buf); PushbackReader f=new PushbackReader(in); int c; while((c=f.read()) != -1) { switch(c) { case '=': if((c=f.read()) == '=') System.out.print(".eq."); else { System.out.print("<-"); f.unread(c); } break; default: System.out.print((char)c); break; } } } } Networks Connection between Different peripherals Networks enables sharing of resources and communications. Internet is a network of networks. Networking in java is possible through the use of

java.net.package. The classes within this package encapsulate the socket model developed by Berkely Software Division. (BSD) Protocols Communication between computers in network requires certain set of rules called protocols.Java networking is done using TCP/IP (Transmission control protocol/Internet protocol) Protocol and UDP (User Datagram Protocol). Some of the different protocols are HTTP - HyperText transfer Protocol (enables interaction with internet) FTP - File Transfer Protocol (Enables transfer of files between computers) SMTP - Simple Mail transfer protocol (Provides email facility) POP3-Post Office Protocol NNTP - Network news transfer protocol (acts as a bulletin board for sharing news) WAP - Wireless application protocol. SOAP - Simple Object Access Protocol.(.NET) For Transferring data over internet in the format of XML Sockets Sockets can be understood as a place used to plug in just like electric sockets. Here TCP/IP as a protocol for communication and IPaddress area addresses of the sockets. IPAddress: 132.147.168.2 255.255.0.0 Subnet mask Specific ports are assigned to some protocols by TCP/IP. Client or HTTP : 8080 Server : 9090 FTP :21 Telnet : 25 Client/Server A Computer which request for some service from another computer,is called a client. The one that processes the request and give response is called server. Internet Address Every Computer connected to a network has a unique IP address.An IP address is a 32bit number which has four numbers seperated by periods. IP Address : 132.147.168.5 Subnet Mask: 255.255.0.0 InetAddress Class

InetAddress is a class which is used to encapsulate the IP address and the DNS(Domain Naming System).To Create an instance in InetAddress class,factory methods are used as there are no visible constructors available for this class. Factory methods are convensions where static method returns an instance of this class. Methods static InetAddress getLocalHost() - Returns InetAddress object representing local host static InetAddress getByName(String hostname) Returns InetAddress for the host passed to it. Eg: import java.net.*; class IPDemo { public static void main(String args[]) throws UnknownHostException { InetAddress ia = InetAddress.getLocalHost(); System.out.println("IP Address : " + ia); } } Eg: import java.net.*; class IPDemo1 { public static void main(String args[]) { try { InetAddress ia = InetAddress.getByName("system1"); System.out.println("IP of System1 : " + ia); }catch(UnknownHostException e) { System.out.println(e); } } } UDP (One way communication) Datagram

Datagram is a type of socket that represents an entire communication. There are two classes in java which enables communication with datagrams 1. DatagramPacket - acts as a data container. contains data,sizeof data, destination ip address 2. DatagramSocket - is a mechanism used to receive and send DatagramPackets DatagramPacket Constructors DatagramPacket(byte data[],int size) DatagramPacket(byte data[],int size,InetAddress I,int Port) DatagramSocket The creation of DatagramSocket throws a SocketException,which must be handled. Constructors DatagramSocket s=new DatagramSocket(); DatagramSocket s=new DatagramSocket(int port) Methods send(DatagramPacket d) - Dispatches the given DatagramPacket object receive(DatagramPacket p) - Receives the DatagramPacket object close() - closes the socket connection The send and receive methods of the DatagramSocket class throws an IOException. Drawback 1. There is no acknowledgement Eg: import java.net.*; import java.io.*; class DatagramServer { public static DatagramSocket ds; public static int clientport=789,serverport=790; public static void main(String args[]) throws Exception { byte buffer[]=new byte[1024]; ds=new DatagramSocket(serverport); BufferedReader dis=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Server waiting for input"); InetAddress ia=InetAddress.getByName("system2");

while(true) { String str=dis.readLine(); if((str==null || str.equals("end"))) break; buffer=str.getBytes(); ds.send(new DatagramPacket(buffer,str.length(),ia,clientport)); } } } Eg: import java.net.*; import java.io.*; class DatagramClient { public static DatagramSocket ds; public static byte buffer[]=new byte[1024]; public static int clientport=789; public static void main(String args[]) throws Exception { ds=new DatagramSocket(clientport); System.out.println("Client is waiting for server send data"); System.out.println("press ctrl+c to come to dos prompt"); while(true) { DatagramPacket p=new DatagramPacket(buffer,buffer.length); ds.receive(p); String psx=new String(p.getData(),0,p.getLength()); System.out.println(psx); } } }

TCP/IP This Protocol is used to send an arbitary amount of data The ServerSocket class is used by the server to wait for the client and the client connects to the server using the Socket class
Server / Socket Client /Socket

Listen

Connect

Accept

Socket class Send Data Receive Data (Client) Constructor Receive Data Send Data Socket s=new Socket(String hostname,int port) Socket s=new socket(InetAddress a,int port) Methods InetAddress getInetAddress() Returns InetAddress associated with the socket object. int getPort() - Returns remote port to which this socket object is connected int getLocalPort() - Returns the local port to which the Socket object is connected InputStream getInputStream() - Returns the InputStream associated with this socket OutputStream getOutputStream() - Returns the OutputStream associated with this socket. void close() - Close both InputStream and OutputStream. ServerSocket class (Server) ServerSocket object waits for the client to make a connection. Socket accept() - used to wait for a client to initiate communications. Constructors ServerSocket ss=new ServerSocket(int port); ServerSocket ss= new ServerSocket(int port[],int maxqueue); Eg: import java.io.*;

import java.net.*; class server { public static void main(String args[]) throws Exception{ try { Socket soc=null; ServerSocket ss; int cli_port = 100; ss = new ServerSocket(cli_port); System.out.println("Server Waiting for client"); soc=ss.accept(); System.out.println("Connected"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintStream ps = new PrintStream(soc.getOutputStream()); ps.println("U R Connected Enter messages"); BufferedReader br1 = new BufferedReader(new InputStreamReader(soc.getInputStream())); while(true) { String re = br1.readLine(); System.out.println(re); String se = br.readLine(); ps.println(se); } }catch(Exception e) {} } } Eg: import java.io.*; import java.net.*; class client { public static void main(String args[]) { try { Socket soc; int cli_port = 100; soc = new Socket(InetAddress.getByName(args[0]),cli_port); BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); BufferedReader br1 = new BufferedReader(new InputStreamReader(soc.getInputStream())); PrintStream ps = new PrintStream(soc.getOutputStream());

while(true) { String re = br1.readLine(); System.out.println(re); String se = br.readLine(); ps.println(se); } }catch(Exception e) {} } } Abstract Windowing Toolkit (AWT) Applets An applet is a dynamic and interactive program that run inside a Web page displayed by a java-capable browser such as HotJava or Netscape Navigator or Appletviewer or Internet Explorer. Differences between Applet and Application Appln Applet 1. Java appln are simple stand Java applets are run inside alone programs that can run using a world wide web browser the java interpreter from the that supports Java applets. command line A reference to an applet is embedded in a web page using a special HTML tag. An applet is also executed using the appletviewer appln, which is part of JDK. Advantages They are run inside java browser that provides frame, event handling facility, graphics context and surrounding user interface. Restrictions Java applets have restrictions to ensure security and to prevent them from being affected by viruses. Some of the restrictions are listed below. * Applets cannot read or write to the file system. Applet tag Syntax: <applet code="class file" codebase="path of the class file" width=100 height=300> </applet> eg: MyFirstApplet.java

import java.awt.*; import java.applet.*; public class MyFirstApplet extends Applet { public void paint(Graphics g) { g.drawString("My First Applet Program",70,30); } } //<applet code="MyFirstApplet.class" width=300 height=400></applet> MyFirstApplet.html <applet code="MyFirstApplet.class" width=300 height=400> </applet> Applet Class Methods init() start() paint(Graphics g) repaint() -> update() -> paint() stop() destroy() Passing Parameter to Applet Tag - <PARAM> Two Attributes NAME - Name of the parameter VALUE - Value of the parameter public void init() - graphics method getParameter(NAME) - This method takes one argument the string representing the value of the parameter Eg: ParamtestApplet.java import java.awt.*; import java.applet.*; public class ParamtestApplet extends Applet { Font f=new Font("TimesRoman",Font.BOLD,40); String name; public void init() { name=getParameter("fname"); if(name==null) name="friend";

name="Have a nice day " + name; } public void paint(Graphics g) { g.setFont(f); g.setColor(Color.blue); g.drawString(name,50,50); } } ParamtestApplet.html <applet code="ParamtestApplet.class" width=400 height=400> <param NAME=fname value="Abi"> </applet> Major Applet activities init () - gets called as soon as the applet started start() - This method is executed after the init() paint() - draws the object in the applet stop() - is used to halt the running of an applet. destroy() - is used to free the memory occupied by the variables and objects initialized in the applet repaint() - is used in case an applet is to be repainted. The repaint() calls the update() method, to clear the screen of any existing context. The update() method in turn calls the paint() method that then redraws the context of the current frame. Eg: import java.awt.*; import java.applet.*; public class lifeCycle extends Applet { public void init() { System.out.println("Init Method"); } public void start() { System.out.println("Start Method"); } public void stop() { System.out.println("Stop Method"); }

public void paint() { System.out.println("Paint Method"); } public void destroy() { System.out.println("Destroy Method"); } } //<applet code=lifeCycle width=400 height=300></applet> The Graphics class This class contains methods for drawing strings , lines,rectangles,and other shapes defined in the graphics class. Drawing characters,bytes and strings 'g','r','a','p','h','i','c','s' - Characters 100,101,103,124,97,87 - Bytes "graphics" - Strings void drawBytes(byte[] data,int offset, int length,int x,int y) data -> the data to be drawn offset-> the start offset in the data length-> the no.of bytes that are drawn x-> x co-ordinate y-> y co-ordinate void drawChars(char[] data,int offset,int length,int x,int y) abstract void drawString(String str,int x,int y) eg: drawCBS.java import java.applet.*; import java.awt.*; public class drawCBS extends Applet { byte b[]={100,114,97,119,66,121,116,101,115}; char c[]={'d','r','a','w','c','h','a','r','s'}; String s="drawString example"; Font f; public void init() { f = new Font("TimesRoman",Font.BOLD,30); } public void paint(Graphics g) { g.setFont(f);

g.setColor(Color.red); g.drawBytes(b,0,9,100,30); g.drawChars(c,2,3,100,60); g.drawString(s,100,90); } } //<applet code="drawCBS.class" width=500 height=500></applet> Draw Lines,Rectangles and Ovals drawLine(int x1,int y1,int x2,int y2) - x1,y1 starting point x2,y2 ending point drawRect(int x1,int y1,int width,int height) fillRect(int x1,int y1,int width,int height) x1,y1 starting point width - width of the rectangle height - height of the rectangle drawRoundRect(int x1,int y1,int width,int height,int angle1,int angle2) fillRoundRect(int x1,int y1,int width,int height,int angle1,int angle2) x1,y1 - starting point width - width of the rectangle height - height of the rectangle width1 - width1 of the angle corners height1 - height1 of the angle corners drawPolygon(int xs[],int ys[],int pts) fillPolygon(int xs[],int ys[],int pts) xs - an array of integers representing x co_ordinates ys - an array of integers representing y co_ordinates pts- an integer representing the total no of points drawOval(int x1,int y1,int widht,int height) fillOval(int x1,int y1,int width,int height) x1,y1 - starting point of the oval width,height - width and height of the oval drawArc(int x1,int y1,int width,int height,angle1,angle2) fillArc(int x1,int y1,int width,int height,angle1,angle2) angle1 - degree value at which the arc starts angle2 - degree value at which the arc ends Eg: drawShapes.java import java.awt.*; import java.applet.*;

public class drawShapes extends Applet { int xs[]={40,49,60,70,57,40}; int ys[]={260,310,315,280,260,270}; //this is for fillpolygon int xss[]={140,150,180,200,170,150,140}; int yss[]={260,310,315,280,260,270,265}; public void paint(Graphics g) { g.drawString("Some of the drawing objects",40,20); g.drawLine(40,30,200,30); g.drawRect(40,60,70,40); g.fillRect(140,60,70,40); g.drawRoundRect(240,60,70,40,10,20); g.fillRoundRect(40,120,70,40,10,20); g.drawOval(240,120,70,40); g.fillOval(40,180,70,40); g.drawArc(140,180,70,40,0,180); g.fillArc(240,180,70,40,0,-180); g.drawPolygon(xs,ys,6); g.fillPolygon(xss,yss,6); } } //<applet code="drawShapes.class" width=500 height=500></applet> Fonts Class Text can be written inside an applet using different fonts. The font class of Java offers a wide variety of fonts like TimesRoman,Courier,Helvetica, Futura,Platino etc., Font Styles :- BOLD,PLAIN,ITALIC Constants Description static int BOLD Font.BOLD static int PLAIN Font.PLAIN static int ITALIC Font.ITALIC Constructor Description Font(String name,int style,int size) Creates a new font from the specified name,style and size Methods Description

abstract void setFont(f) String getStyle() int getSize() String getFamily()

boolean isPlain() boolean isBold() boolean isItalic() Eg: import java.applet.*; import java.awt.*; public class fonts extends Applet { Font f,f1,f2; int style,size; String s,s1; public void init() { f=new Font("Helvetica",Font.BOLD,20); f1=new Font("TimesRoman",Font.BOLD,10); f2=new Font("Courier",Font.ITALIC,20); } public void paint(Graphics g) { g.setFont(f); g.drawString("Font name is : Helvetica",30,30); g.setFont(f1); g.drawString("Font name is : TimesRoman",30,80); g.setFont(f2); g.drawString("Font name is : Courier",30,130); style=f.getStyle(); if(style==Font.PLAIN) s="PLAIN"; else if(style==Font.BOLD) s="BOLD"; else if(style==Font.ITALIC) s="ITALIC"; else s="BOLD AND ITALIC"; size=f2.getSize();

set this graphics contexts font to the specified font returns a string value that indicating the current font style returns an integer value that indicating the current font size Returns the font family name as a string Returns true if the font is plain Returns true if the font is bold Returns true if the font is italic

s1=f2.getName(); s1+= " size is " + size + " style is " + s; g.drawString(s1,30,180); g.drawString("Font family is : " +f2.getFamily(),30,250); } } //<applet code="fonts" width=500 height=500></applet> FontMetrics class The fontmetrics class is used to obtain precise information on a specific font such as height,descent (ie) the amount of characters dips below the baseline,ascent(the amount of character raises above the baseline),leading between lines(the difference between the height and the descent). Methods Description abstract font getFont() This will return a Font object representing the current font public int getAscent() returns a value representing the ascent of a font in points public int getDescent() returns a value representing the descent of a font in points public int getLeading() returns a value representing the leading of a font in points public int getHeight() returns a value representing the height of a font in points public fontMetrics getFontMetrics() returns current font metrics Eg: import java.applet.*; import java.awt.*; public class fontMetrics extends Applet { Font f1; int ascent,descent,leading,height; String one,two,three,four; public void init() { f1=new Font("Helvetica",Font.BOLD,14); } public void paint(Graphics g) { g.setFont(f1);

ascent=g.getFontMetrics().getAscent(); descent=g.getFontMetrics().getDescent(); height=g.getFontMetrics().getHeight(); leading=g.getFontMetrics().getLeading(); one="Ascent of font f1 is " + ascent; two="Descent of font f1 is " + descent; three="Height of font f1 is " + height; four="Leading of font f1 is " + leading; g.drawString(one,20,20); g.drawString(two,20,50); g.drawString(three,20,80); g.drawString(four,20,110); } } //<applet code="fontMetrics" width=500 height=500></applet> Color Class Colors are represented as combination of red,blue and green. Each component can have a no between 0 to 255, 0,0,0 is black and 255,255,255 white Color c1 = new Color(100,150,250); Color Name RGB value Color.gray 128,128,128 Color.green 0,255,0 Color.yellow 255,255,0 Color.pink 255,175,175 Color.red 255,0,0 Color.blue 0,0,255 Color.magenta 255,0,255 Color.cyan 0,255,255 setColor() - set color to an object setBackground() - sets background color of an applet setForeground() - used to change the color of the whole applet after it has been drawn. Color getBackground() Color getForeground() eg: import java.awt.*; import java.applet.*; public class ColorApplet extends Applet { Font f,f1,f2;

public void init() { f=new Font("TimesRoman",Font.BOLD,20); f1=new Font("Courier",Font.ITALIC,20); f2=new Font("Helvetica",Font.PLAIN,20); } public void paint(Graphics g) { setBackground(Color.cyan); g.setColor(Color.green); g.setFont(f); g.drawString("Be Happy. Be Hopeful",30,30); g.setColor(Color.blue); g.setFont(f1); g.drawString("Be Happy.Be Hopeful",30,70); g.setColor(Color.pink); g.setFont(f2); g.drawString("Be Happy.Be Hopeful",30,110); } } //<applet code="ColorApplet" width=500 height=500></applet> Images Image img; .Methods used to load and display an image img = getImage(URL,String) - Loads an image from an URL. URL specifies the loacation from which the image is to be loaded. String is usually the name of the image file. drawImage(Image,x,y,imageObserver) Draws an Image at the given co-ordinates. Image Object refers to the picture to be drawn.x,y are the co-ordinates where the image is to be drawn.ImageObserver is usually the applet itself. drawImage(image,x,y,width,height,ImageObserver) getCodeBase() - Which returns the path of the file getDocumentBase() - Which returns the URL of the .HTML file. http://www.rediff.com file://c:/mydocument/ getWidth() - return the width of the applet browser getHeight() - return the height of the applet browser Eg: import java.awt.*; import java.applet.*;

public class ImageDemo extends Applet { Image img; public void init() { img=getImage(getCodeBase(),"rabbit.gif"); } public void paint(Graphics g) { //showStatus("URL = " + getCodeBase()); //showStatus("Width = " + img.getWidth(this)); showStatus("Height = " + img.getHeight(this)); g.drawImage(img,10,10,this); g.drawImage(img,130,100,200,150,this); } } //<applet code="ImageDemo" width=500 height=500></applet> Clipping Clipping is the technique by which the drawing area can be restricted to a small portion of the screen. A clipping is an area where drawing is allowed . Any drawing outside clipping region is clipped off and not displayed. clipRect(x,y,width,height) eg: import java.awt.*; import java.applet.Applet; public class Clipper extends Applet { public void paint(Graphics g) { g.clipRect(10,10,150,150); g.setFont(new Font("TimesRoman",Font.ITALIC,28)); g.fillOval(100,60,80,80); g.drawString("Happy New Year",50,30); } } //<applet code="Clipper" width=500 height=500></applet> Event Handling Mouse move Mouse Click Mouse Drag key type key presses key released

Event An event is an object that describes a state change in a source Event Sources A source is an object that generates an event(textbox,list,choice,button) For event Handling 1. Register the source with some event class or event listeners syntax: public void addTypeListener(TypeEvent el) (interface) Type - Name of the event el - reference to the event listener For Eg: Button b; b.addActionListener(this); void actionPerformed(ActionEvent e) { statements; } java.awt.event package Event Class Description ActionEvent Generated when a button is pressed, a list item is double clicked, or a menu item is selected AdjustmentEvent Generated when a scroll bar is manipulated. Component Event Generated when a component is hidden, moved,resized or becomes visible Container Event Generated when a component is added or removed from a container focus Event Generated when a component gains or loses keyboard focus ItemEvent Generated when a check box or list item is clicked; also occurs when a choice selection is made or a checkable menu item is selected or deselected KeyEvent Generated when input is received from keyboard MouseEvent Generated when the mouse is dragged, clicked,pressed or released. also generated when the mouse enters or exits a component TextEvent Generated when the value of the textarea or textfield is changed WindowEvent Generated when a window is activated, closed, deactivated, deiconified,iconified,opened or quit Listener Interfaces and a brief description of the methods

The ActionListener Interface This interface defines the actionPerformed() method that is invoked when an action event occurs. void actionPerformed(ActionEvent ae) The AdjustmentListener interface This interface defines the adjustmentValueChanged() method that is invoked when an adjustment event occurs. void adjustmentValueChanged(AdjustmentEvent ae) The ComponentListener Interface This interface defines four methods that are invoked when a component is moved,shown,resized or hidded. void componentResized(ComponentEvent e) void componentMoved(ComponentEvent e) void componentShown(ComponentEvent e) void componentHidden(ComponentEvent e) The ContainerListener Interface This interface contains two methods. When a component is added to a container, componentAdded() is invoked. When a component is removed from a container, componentRemoved() is invoked. void componentAdded(ContainerEvent ce) void componentRemoved(ContainerEvent ce) The FocusListener Interface Components got or lost focus. void focusGained(FocusEvent fe) void focusLost(focusEvent fe) The ItemListener Interface This invoked when a state of the item is changed void itemStateChanged(ItemEvent ie) The KeyListener Interface key pressed,released,typed. void keyPressed(KeyEvent ke) void keyReleased(KeyEvent ke) void keyTyped(KeyEvent ke) The MouseListener Interface mouse click,press,release,enter,exit void mouseClicked(MouseEvent me) void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePressed(MouseEvent me) void mouseReleased(MouseEvent me)

The MouseMotionListener Interface mouse drag,move void mouseDragged(MouseEvent me) void mouseMoved(MouseEvent me) The TextListener interface Text field,TextArea void textChanged(TextEvent te) The WindowListener Interface open,close,activate,deactivate,iconified,deiconified void windowActivated(WindowEvent we) void windowClosed(WindowEvent we) void windowClosing(WindowEvent we) void windowDeactivated(WindowEvent we) void windowDeiconified(WindowEvent we) void windowIconified(WindowEvent we) void windowOpened(WindowEvent we) Eg: import java.awt.*; import java.applet.*; import java.awt.event.*; public class MouseEvents extends Applet implements MouseListener,MouseMotionListener { String msg = " "; int mouseX=0,mouseY=0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { mouseX = 0; mouseY = 10; msg = "Mouse Clicked"; repaint(); } public void mouseEntered(MouseEvent me) { mouseX = 0; mouseY = 10; msg = "Mouse Entered"; repaint();

} public void mouseExited(MouseEvent me) { mouseX = 0; mouseY = 10; msg = "Mouse Exited"; repaint(); } public void mousePressed(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); msg = "Down"; repaint(); } public void mouseReleased(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); msg = "Up"; repaint(); } public void mouseDragged(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); msg = "*"; showStatus("Mouse Dragged at " + mouseX + ", " + mouseY); repaint(); } public void mouseMoved(MouseEvent me) { showStatus("Mouse Moved at " + me.getX() + ", "+ me.getY()); } public void paint(Graphics g) { g.drawString(msg,mouseX,mouseY); } } //<applet code="MouseEvents" width=500 height=500></applet> Keyboard Events Key pressed, key released, key typed. we can use the KeyListener Eg: import java.awt.*; import java.awt.event.*;

import java.applet.*; public class SimpleKey extends Applet implements KeyListener{ String msg=" "; int X = 10,Y = 20; public void init() { addKeyListener(this); requestFocus(); //set the input focus } public void keyPressed(KeyEvent ke) { showStatus("Key Down"); } public void keyReleased(KeyEvent ke) { showStatus("Key Up"); } public void keyTyped(KeyEvent ke) { msg += ke.getKeyChar(); repaint(); } public void paint(Graphics g) { g.drawString(msg,X,Y); } } //<applet code="SimpleKey.class" width=300 height=100></applet> Virtual Keys VK_F1 - VK_F12 VK_A - VK_Z VK_0 - VK_9 VK_ENTER VK_ESCAPE VK_DOWN VK_PAGE_UP VK_LEFT VK_SHIFT VK_CANCEL VK_RIGHT VK_UP VK_PAGE_DOWN VK_CONTROL VK_ALT

VK_BACK Demonstration of Virtual keycodes import java.awt.*; import java.applet.*; import java.awt.event.*; public class KeyEvents extends Applet implements KeyListener { String msg = ""; int X = 10,Y = 20; public void init() { addKeyListener(this); requestFocus(); } public void keyPressed(KeyEvent ke) { showStatus("Key Down"); int key = ke.getKeyCode(); switch(key) { case KeyEvent.VK_F1: msg += "<F1>"; break; case KeyEvent.VK_F2: msg += "<F2>"; break; case KeyEvent.VK_F3: msg += "<F3>"; break; case KeyEvent.VK_PAGE_DOWN: msg += "<PgDn>"; break; case KeyEvent.VK_PAGE_UP: msg += "<PgUp>"; break; case KeyEvent.VK_LEFT: msg += "<Left Arrow>"; break; case KeyEvent.VK_RIGHT: msg += "<Right Arrow>"; break; } repaint(); }

public void keyReleased(KeyEvent ke) { showStatus("Key Up"); } public void keyTyped(KeyEvent ke) { msg += ke.getKeyChar(); repaint(); } public void paint(Graphics g) { g.drawString(msg,X,Y); } } //<applet code="KeyEvents.class" width=300 height=100></applet> Adapter Classes ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener Eg: AdapterDemo1.java import java.awt.*; import java.awt.event.*; import java.applet.*; public class AdapterDemo1 extends Applet { int x,y; String msg = new String(); public void init() {

addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { x = me.getX(); y = me.getY(); msg = "Clicked"; repaint(); } }); } public void paint(Graphics g) { g.drawString(msg,x,y); } } //<applet code=AdapterDemo1 width=400 height=400></applet> AdapterDemo2.java import java.applet.*; import java.awt.*; import java.awt.event.*; public class AdapterDemo2 extends Applet { String msg = new String(); public void init() { addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent ke) { msg += ke.getKeyChar(); repaint(); } }); requestFocus(); } public void paint(Graphics g) { g.drawString(msg,50,50); } //<applet code=AdapterDemo2 width=400 height=400></applet>

User Interface Components Object Component Label Button CheckBox TextComponent TextArea TextField Choice List ScrollBar Common Methods setSize(int width,int height) - Resizes the correxponding component so that it has width and height setFont(font f) - Sets the font of the corresponding component setEnabled(boolean b)- Enables or Disables the corresponding component, depending on the value of the parameter b. setVisible(boolean b) - shows or hides the corresponding component depending on the value of the parameter b setForeground(Color c) - sets the foreground color of the corresponding component. setBounds(int x,int y,int width,int height) -Moves and resizes the corresponding component. setBackground(Color c) - sets the background color of the component Color getBackground() gets the background color of the corresponding component Bounds getBounds() gets the bounds of the corresponding component in the form of a rectangle object Font getFont() - gets the font of the corresponding component Color getForeground() - gets the foreground color of the corresponding component Size getSize() - Returns the size of the corresponding component in the form of a Dimension object.

Button Constructor Description Button() Constructs a button with no label Button(String label) Constructs a button with label specified. Methods Method Description addActionListener(ActionListener l) Adds the specified actionlistener to receive the action events from the corresponding button getActionCommand() Returns the command name of the action fired by the corresponding button getLabel() Returns the label of the corresponding button setLabel(String label) sets the label of the button to the value specified getSource() Returns the object name of the command button eg: import java.awt.*; import java.awt.event.*; import java.applet.*; public class ButtonDemo extends Applet implements ActionListener { String msg = " "; Button yes,no,maybe; public void init() { yes = new Button("Yes"); no = new Button("No"); maybe = new Button("Undecided"); add(yes); add(no); add(maybe); yes.addActionListener(this); no.addActionListener(this); maybe.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); if(str.equals("Yes")) { msg = "You pressed Yes."; }

else if(str.equals("No")) { msg = "You pressed No."; }else { msg = "You pressed undecided."; } repaint(); } public void paint(Graphics g) { g.drawString(msg,6,100); } } //<applet code="ButtonDemo.class" width = 300 height = 100></applet> CheckBox Constructor Description Checkbox() creates a checkbox with no label. Checkbox(String label) Creates a checkbox with specified label Checkbox(String label,boolean state) Creates a checbox with the specified label and sets the state Checkbox(String label,CheckboxGroup group,boolean state) Creates a checkbox with the specified label and sets the specified state and places it in the specified group. The position of the checkbox group and state can be interchanged Method Description CheckboxGroup getCheckboxGroup() Determines the group of the corresponding Checkbox getLabel() Gets the name of the corresponding checkbox getSelectedObjects() Returns an array(length l) containing the checkbox label or null if the checkbox is not selected. getState() Detrmines if the checkbox is 'true' or 'false' state getItem() returns the item object setCheckboxGroup(CheckboxGroup g) sets the corresponding checkbox group to the specified one setLabel(String label) Set the label of the corresponding checkbox to the value specified setState(boolean state) sets the state of the corresponding checkbox to the value specified CheckboxDemo.java

import java.awt.*; import java.awt.event.*; import java.applet.*; public class CheckboxDemo extends Applet implements ItemListener { String msg = new String(); Checkbox Win98,winNT,solaris,mac; public void init() { Win98 = new Checkbox("Windows98",null,true); winNT = new Checkbox("WindowsNT/2000"); solaris = new Checkbox("Solaris"); mac = new Checkbox("MacOS"); add(Win98); add(winNT); add(solaris); add(mac); Win98.addItemListener(this); winNT.addItemListener(this); solaris.addItemListener(this); mac.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } public void paint(Graphics g) { msg = "Current state : "; g.drawString(msg,6,80); msg = " Windows 98: " + Win98.getState(); g.drawString(msg,6,100); msg = " Windows NT/2000: " + winNT.getState(); g.drawString(msg,6,120); msg = " Solaris: " + solaris.getState(); g.drawString(msg,6,140); msg = " MacOS: " +mac.getState(); g.drawString(msg,6,160); } } //<applet code="CheckboxDemo.class" width=300 height=200></applet> CBGroup.java import java.awt.*;

import java.awt.event.*; import java.applet.*; public class CBGroup extends Applet implements ItemListener { String msg = new String(); Checkbox Win98,winNT,solaris,mac; CheckboxGroup cbg; public void init() { cbg = new CheckboxGroup(); Win98 = new Checkbox("Windows 98",cbg,true); winNT = new Checkbox("Windows NT/2000",cbg,false); solaris = new Checkbox("Solaris",cbg,false); mac = new Checkbox("MacOS",cbg,false); add(Win98); add(winNT); add(solaris); add(mac); Win98.addItemListener(this); winNT.addItemListener(this); solaris.addItemListener(this); mac.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } public void paint(Graphics g) { msg = "Current Selection: "; msg +=cbg.getSelectedCheckbox().getLabel(); g.drawString(msg,6,100); } } //<applet code="CBGroup.class" width=500 height=500></applet> Choice Constructor Description Choice() Creates a new Choice item Choice c = new Choice(); Method Description add(String item) Adds an item to the corresponding choice menu

addItem(String item) Adds an item to the corresponding choice getItem(int index) Gets the string at the specified index of the corresponding choice menu getItemCount() Returns the number of items in the corresponding choice menu getSelectedIndex() Returns the index of the currently selected item getSelectedItem() Gets a representation of the current choice as a string insert(String item, int index) Inserts the item into the corresponding choice at the specified position remove(int position) Removes an item into the corresponding choice menu at the specified position remove(String item) Removes the first occurence of item from the corresponding choice menu removeAll() Removes all item from the corresponding choice menu select(int pos) Sets the selected item in the corresponding choice menu to be the item at the specified position select(String str) Sets the selected item in the coresponding Choice menu to be the item whose name is equal to the specified string eg: import java.awt.*; import java.awt.event.*; import java.applet.*; public class ChoiceDemo extends Applet implements ItemListener { Choice os,browser; String msg = new String(); public void init() { os = new Choice(); browser = new Choice(); os.add("Windows 98"); os.add("Windows NT/2000"); os.add("Solaris"); os.add("MacOS");

browser.add("Netscape 1.1"); browser.add("Netscape 2.x"); browser.add("Netscape 3.x"); browser.add("Netscape 4.x"); browser.add("Internet Explorer 3.0"); browser.add("Internet Explorer 4.0"); browser.add("Internet Explorer 5.0"); browser.add("Lynx 3.4"); browser.select("Netscape 4.x"); add(os); add(browser); os.addItemListener(this); browser.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } public void paint(Graphics g) { msg = "Current OS : "; msg += os.getSelectedItem(); g.drawString(msg,6,120); msg = "Current Browser : "; msg += browser.getSelectedItem(); g.drawString(msg,6,140); } } //<applet code="ChoiceDemo.class" width=500 height=500></applet> ChoiceDemo1.java import java.applet.*; import java.awt.*; import java.awt.event.*; public class ChoiceDemo1 extends Applet implements ActionListener { Choice names; TextField tf; Button ad,rm,ra; Label na,cnt; public void init() { setLayout(null);

na = new Label("Enter Name : "); tf = new TextField(20); names = new Choice(); ad = new Button("Add"); rm = new Button("Remove"); ra = new Button("RemoveAll"); cnt = new Label("Count : "); na.setBounds(100,100,130,30); tf.setBounds(240,100,100,30); names.setBounds(100,150,100,30); ad.setBounds(240,150,100,30); rm.setBounds(240,190,100,30); ra.setBounds(240,230,100,30); cnt.setBounds(240,270,100,30); add(na); add(tf); add(names); add(ad); add(rm); add(ra); add(cnt); ad.addActionListener(this); rm.addActionListener(this); ra.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String na; if(ae.getSource() == ad) { na = tf.getText(); names.add(na); tf.setText(""); cnt.setText("Count : " +names.getItemCount()); } else if(ae.getSource() == rm) { int index =names.getSelectedIndex(); names.remove(index); cnt.setText("Count : " + names.getItemCount());

} else if(ae.getSource() == ra) { names.removeAll(); cnt.setText("Count : " +names.getItemCount()); } } } //<applet code="ChoiceDemo1" width=400 height=400></applet> Label For displaying text Constructor Description Label() Constructs an empty label. Label(String text) Constructs a string with the corresponding text Label(String text,int alignment)Constructs a string with the text, with the specified alignment. the alignment could be CENTER,LEFT,RIGHT Method Description getText() Gets the text of the coresponding label. setText(String text) set the text for the corresponding label to the specified text Eg: import java.awt.*; import java.applet.*; public class LabelDemo extends Applet { public void init() { Label one = new Label("One"); Label two = new Label("Two"); Label three = new Label("Three"); add(one); add(two); add(three); } } /*<applet code = "LabelDemo.class" width = 300 height = 100></applet>*/ List List the items, the user can select a single or multiple items.

Constructors List() List(int rows)

Description Creates a new scrolling list of items Creates a new scrolling list of items with the specified number of visible lines List(int rows,Boolean mutilplemode) Creates a new scrolling list of items to display the specified number of rows Method Description add(String item) Adds the specified item at the end of the scrolling list add(String item,int index) Adds the specified item at the position specified deselect(int index) deselects the item at the specified index getItem(int index) Gets the item at the specified index getItemCount() gets the number of items in the list getItems() gets the items in the list getRows() Gets the number of visible lines in the corresponding list int[] getSelectedIndexes() Gets the index of the selected item in the list getSelectedItem() Gets the selected item in the corresponding list select(int index) Selects the item at the specfied index in the corresponding list setMultipleMode(boolean b) Sets the flag that allows multiple selection in the corresponding list Eg: import java.awt.*; import java.awt.event.*; import java.applet.*; public class ListDemo extends Applet implements ItemListener { List os,browser; String msg=new String(); public void init() { os = new List(4,true); browser = new List(4,false); os.add("Windows 98"); os.add("Windows NT/2000"); os.add("Solaris"); os.add("MacOS");

browser.add("Netscape 1.1"); browser.add("Netscape 2.x"); browser.add("Netscape 3.x"); browser.add("Netscape 4.x"); browser.add("Internet Explorer 3.0"); browser.add("Internet Explorer 4.0"); browser.add("Internet Explorer 5.0"); browser.add("Lynx 2.4"); browser.select(1); add(os); add(browser); os.addItemListener(this); browser.addItemListener(this); } public void itemStateChanged(ItemEvent ae) { repaint(); } public void paint(Graphics g) { int idx[]; msg = "Current OS: "; idx= os.getSelectedIndexes(); for(int i=0;i<idx.length;i++) msg += os.getItem(idx[i]) + " " ; g.drawString(msg,6,120); msg = "Current browser:"; msg += browser.getSelectedItem(); g.drawString(msg,6,140); } } /*<applet code="ListDemo.class" width=500 height=500></applet>*/ ScrollBars Vertical Horizontal ScrollBar Contructors Scrollbar() Scrollbar(int style) Scrollbar(int style,int initial value,int thumbsize,int min, int max) style Scrollbar.VERTICAL Scrollbar.HORIZONTAL

initial value - Starting value of the scrollbar thumbsize - Defint the thumbsize min - Minimum value max - Maximum value Methods setValues(int initialvalue,int thumbsize,int min,int max) - Set the values int getMinimum() - Get minimum value int getMaximum() - Get Maximum value int getValue() - Get the current value void setUnitIncrement(int newincr) - Defualt 1, void setBlockIncrement(int newIncr) - Set the block increment (ie) click at the centre space of the scrollbar -> default 10 To process ScrollBar events, the AdjustmentListener is used. Each time a user nteracts with a scroll bar, an AdjustmentEvent object is generated. getAdjustmentType () - Used to determine the type of the adjustment. LOCK_DECREMENT A Page Down event has been generated BLOCK_INCREMENT A Page Up event is generated TRACK An absoulte tracking event is generated UNIT_DECREMENT The line down button in a scrollbar is pressed UNIT_INCREMENT The line up button in a scrollbar is pressed Eg: import java.awt.*; import java.awt.event.*; import java.applet.*; public class SBDemo extends Applet implements AdjustmentListener,MouseMotionListener { String msg = new String(); Scrollbar vertSB,horzSB; public void init() { int width =Integer.parseInt(getParameter("width")); int height=Integer.parseInt(getParameter("height")); vertSB = new Scrollbar(Scrollbar.VERTICAL,0,1,0,height); horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,width); add(vertSB); add(horzSB); vertSB.addAdjustmentListener(this);

horzSB.addAdjustmentListener(this); addMouseMotionListener(this); } public void adjustmentValueChanged(AdjustmentEvent ae) { repaint(); } public void mouseDragged(MouseEvent me) { int x = me.getX(); int y = me.getY(); vertSB.setValue(x); horzSB.setValue(y); repaint(); } public void mouseMoved(MouseEvent me){} public void paint(Graphics g) { msg = "Vertical: "+ vertSB.getValue(); msg += ", Horizontal: " + horzSB.getValue(); g.drawString(msg,6,160); g.drawString("*",horzSB.getValue(),vertSB.getValue()); } } /*<applet code="SBDemo.class" width=500 height=500> <param name="width" value="255"> <param name="height value="255"> </applet> */ TextField For Single-line data Entry. Constructors TextField() TextField(int length) TextField(String str) TextField(String str,int length) Methods String getText() Used to get the text from TextField void setText(String str) Used to set the text String getSelectedText() returns the selected text void select(int startindex,int endindex) Used to select the text void setEditable(boolean canEdit) If it is false, the text cannot be altered

boolean isEditable() Used to check if the text is editable or not void setEchoChar(char ch) Set the printed character in text (password field) boolean echoCharIsSet() check if the echo char is set or not char getEchoChar() get the echoed character Eg: import java.awt.*; import java.applet.*; import java.awt.event.*; public class TextFieldDemo extends Applet implements TextListener,ActionListener { TextField name,pass; public void init() { Label namep = new Label("Name : ",Label.RIGHT); Label passp = new Label("Password : ",Label.RIGHT); name = new TextField(12); pass = new TextField(8); pass.setEchoChar('*'); add(namep); add(name); add(passp); add(pass); name.addTextListener(this); pass.addTextListener(this); name.addActionListener(this); pass.addActionListener(this); } public void textValueChanged(TextEvent te) { repaint(); } public void actionPerformed(ActionEvent ae) { repaint(); } public void paint(Graphics g) { g.drawString("Name : "+ name.getText(),6,60); g.drawString("Selected Text in name :" + name.getSelectedText(),6,80); g.drawString("Password : " + pass.getText(),6,100); }

} //<applet code="TextFieldDemo" width=500 height=500></applet> TextArea Multiline Data Entry Constructors TextArea() TextArea(int numLines,int numChars) TextArea(String str) TextArea(String str,int numLines,int numChars) TextArea(String str,int numLines,int numChars,int sBars) sBars SCROLLBARS_BOTH -0 SCROLLBARS_HORIZONTAL_ONLY -2 SCROLLBARS_NONE - 3 SCROLLBARS_VERTICAL_ONLY -1 Methods String getText() void setText(String str) void select(int startIndex,int endIndex) String getSelectedText() boolean isEditable() void setEditable(boolean canEdit) void append(String str) - Appends the text at end of the line void insert(String str,int index) - Insert the string in the correspoding index position void repalceRange(String str,int startIndex,int ndIndex) - Replace the string with the corresponding start and end index Eg: import java.awt.*; import java.applet.*; public class TextAreaDemo extends Applet { TextArea ta; String str="This is a sample string for adding text in text area"; public void init() { ta = new TextArea(str,10,25,3); add(ta); } } //<applet code="TextAreaDemo" width=500 height=500></applet> Frame

To Create dynamic window Act as a container Constructors Frame(String title) Methods setVisible(boolean) setSize(int width,int height) setLocation(int x,int y) Eg: import java.awt.*; import java.awt.event.*; public class FrameDemo extends Frame { public FrameDemo(String title) { super(title); setVisible(true); setSize(400,400); setLocation(100,100); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose(); System.exit(0); } }); } public static void main(String args[]) { FrameDemo fm = new FrameDemo("Sample"); } } Eg: import java.awt.*; import java.awt.event.*; public class FrameDemo extends Frame implements ActionListener { Button b1,b2,b3; public FrameDemo(String title) {

super(title); setLayout(new FlowLayout()); b1 = new Button("Yes"); b2 = new Button("No"); b3 = new Button("May be"); add(b1); add(b2); add(b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); setSize(400,400); setLocation(100,100); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose(); System.exit(0); } }); } public void actionPerformed(ActionEvent ae) { if(ae.getSource() == b1) System.out.println("Yes Clicked"); else if(ae.getSource() == b2) System.out.println("No Clicked"); else System.out.println("Maybe clicked"); } public static void main(String args[]) { FrameDemo fm = new FrameDemo("Sample"); } } Menus Create a Menu bar Create Menu Inside menu create menu item

Frame f = new Frame("Sample"); MenuBar mb = new MenuBar(); Menu mFile = new Menu("File"); MenuItem mNew = new MenuItem("New"); mFile.add(mNew); mb.add(mFile) f.setMenuBar(mb); Menu class Methods Methods Description add(Menu) Adds the specified menuitem to the menu add(String) Adds the specified string to the menu. A new Menu item with the specified string as the label is created and it is added to the menu. addSeparator()Adds a separator to the menu getItem(int index) Returns the item at the specified index as a string remove(int index) Deletes the item at the specified index from the menu MenuItem class Methods Methods Description getLabel() Returns the label of the menu item as a string setLabel(String) Changes the label of the menuitem to the specified string setEnabled(boolean) Makes the menu item selectable/deselectable depending on whether the parameter is true or false CheckboxMenuItem Creates a dual state menu item Methods Description getState() Returns the state of the menu item as boolean value. A value of true implies that the checkbox menu item is selected. setState(boolean) Sets the state of the menu item. If the value passed is true the menu item is set to selected state. Eg: import java.awt.*; import java.awt.event.*; public class SampleFrame extends Frame implements ActionListener { MenuBar mb;

Menu mFile,mEdit; MenuItem mNew,mOpen,mSave,mExit; MenuItem mCut,mCopy,mPaste; public SampleFrame(String title) { super(title); mb = new MenuBar(); mFile = new Menu("File"); mEdit = new Menu("Edit"); mNew = new MenuItem("New"); mOpen = new MenuItem("Open"); mSave = new MenuItem("Save"); mExit = new MenuItem("Exit"); mCut = new MenuItem("Cut"); mCopy = new MenuItem("Copy"); mPaste = new MenuItem("Paste"); mEdit.add(mCut); mEdit.add(mCopy); mEdit.add(mPaste); mFile.add(mNew); mFile.add(mOpen); mFile.add(mSave); mFile.addSeparator(); mFile.add(mExit); mb.add(mFile); mb.add(mEdit); setMenuBar(mb); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose(); System.exit(0); } }); mExit.addActionListener(this); mNew.addActionListener(this); setSize(400,400); setVisible(true); } public void actionPerformed(ActionEvent ae)

{ if(ae.getSource() == mExit) { dispose(); System.exit(0); } else if(ae.getSource() == mNew) { FrameDemo fm = new FrameDemo("Menu Frame"); } } public static void main(String args[]) { SampleFrame1 sf = new SampleFrame1("Menu Creation"); } } Dialog Class For Dialog box first create a frame Then create two panels one for giving message and the another one for creating the Ok and Cancel Buttons. Then add the ActionListener to the Buttons to perform some operations. Constructors Description Dialog(Frame,boolean) Creates a new dialog, which is initially invisible. The frame acts as a parent of the dialog. The dialog is closed when its parent is closed. The boolean value specifies whether the dialog is modal or not. Dialog(Frame,String,boolean) Creates a new dialog with the specified string as the title. The other two parameter are the same as in the previous constructor Methods Description setResizable(boolean) Sets the resizable flag of the dialog.if the boolean value is true, the dialog is made resizable boolean isModal() Returns true if the dialog is modal. A modal dialog prevents the user input to other windows in the application until the dialog is closed boolean isResizable() Returns true is the dialog is resizable

Eg: import java.awt.*; import java.awt.event.*; public class MessageBox extends Dialog implements ActionListener { public MessageBox(Frame fm,String msg) { super(fm,"Message",false); setLayout(new GridLayout(2,1,0,0)); Panel p1 = new Panel(); Panel p2 = new Panel(); p1.setLayout(new FlowLayout()); p1.setFont(new Font("Times Roman",Font.BOLD,20)); p2.setLayout(new FlowLayout()); p1.add(new Label(msg)); Button b1,b2; b1 = new Button("Ok"); b2 = new Button("Cancel"); p2.add(b1); p2.add(b2); b1.addActionListener(this); add(p1); add(p2); setSize(250,150); setResizable(false); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose(); } }); } public void actionPerformed(ActionEvent ae) { dispose(); } } MessageBoxAppln.java import java.awt.*;

import java.awt.event.*; public class MessageBoxAppln extends Frame implements ActionListener { MenuBar mb; Menu mFile; MenuItem mDialog,mExit; public MessageBoxAppln(String title) { super(title); mb = new MenuBar(); mFile = new Menu("File"); mDialog = new MenuItem("Dialog"); mExit = new MenuItem("Exit"); mFile.add(mDialog); mFile.add(mExit); mb.add(mFile); setMenuBar(mb); setSize(400,400); setVisible(true); mDialog.addActionListener(this); mExit.addActionListener(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose(); System.exit(0); } }); } public void actionPerformed(ActionEvent ae) { if(ae.getSource() == mDialog) { MessageBox mb = new MessageBox(this,"Java Alert: Sample Message"); mb.setVisible(true); } else if(ae.getSource() == mExit) {

dispose(); System.exit(0); } } public static void main(String args[]) { MessageBoxAppln mba = new MessageBoxAppln("MessageBox Demo"); } } FileDialog Used to display the modal dialog windows like open and save Constructor Description FileDialog(Frame parent) Creates a filedialog for loading a file FileDialog(Frame parent, String title) Creates a Filedialog window with the specified title for loading a file. FileDialog(Frame parent, String title,int mode) Creates a file dialog window with the specified title for loading or saving a file Method Description getDirectory() Gets the directory of the corresponding file dialog getFile() Gets the file of the corresponding file dialog getFilenameFilter() Determines the file dialog's filename filter getMode() Indicates whether the file dialog is in the save mode or open mode setDirectory(String) Sets the directory of the file dialog window to the one specified setFile(String file) Sets the selected file for the corresponding file dialog window to the one specified setFilenameFilter( sets the filename filter for the filenamefilter filter) specified dialog window to the specified value setMode(int mode) Sets the mode of the file dialog Eg: import java.awt.*;

import java.awt.event.*; import java.io.*; public class MyApp extends Frame implements ActionListener { MenuBar mb; Menu mFile; MenuItem mNew,mOpen,mSave,mExit; TextArea ta; public MyApp(String title) { super(title); setLayout(new FlowLayout()); mb = new MenuBar(); mFile = new Menu("File"); mNew = new MenuItem("New"); mOpen = new MenuItem("Open"); mSave = new MenuItem("Save"); mExit = new MenuItem("Exit"); mFile.add(mNew); mFile.add(mOpen); mFile.add(mSave); mFile.addSeparator(); mFile.add(mExit); mb.add(mFile); setMenuBar(mb); setSize(400,400); setVisible(true); ta = new TextArea(); add(ta); mNew.addActionListener(this); mOpen.addActionListener(this); mSave.addActionListener(this); mExit.addActionListener(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose(); System.exit(0); } }); }

public void actionPerformed(ActionEvent ae) { if(ae.getSource() == mNew) { ta.setText(""); } else if(ae.getSource() == mOpen) { FileDialog fd =new FileDialog(this,"Open Dialog",FileDialog.LOAD); fd.show(); String fname = fd.getDirectory() + "/" + fd.getFile(); try { FileInputStream fin = new FileInputStream(fname); byte b[] = new byte[fin.available()]; fin.read(b); String data = new String(b,0,b.length); ta.setText(data); fin.close(); }catch(Exception e) {} } else if(ae.getSource() == mSave) { FileDialog fd = new FileDialog(this,"Save Dialog",FileDialog.SAVE); fd.show(); String fname = fd.getDirectory() + "/" + fd.getFile(); String data = ta.getText(); byte b[] = new byte[data.length()]; data.getBytes(0,data.length(),b,0); try { FileOutputStream fo = new FileOutputStream(fname); fo.write(b); fo.close(); }catch(Exception e) {} } else if(ae.getSource() == mExit) {

dispose(); System.exit(0); } } public static void main(String args[]) { MyApp m1 =new MyApp("NotepadAppln"); } } Layouts - To set the applet orientation Four Layouts FlowLayout-default (word processor) left,right,center GridLayout - set as rows and columns BorderLayout - Set as borders CardLayout - Used for Slide preparation FlowLayout Constructor Description FlowLayout() Constructs a new flow layout with centered alignment leaving a vertical and horizontal gap of 5 pixels FlowLayout(int align) Constructs a new FlowLayout with the alignment specified leaving a vertical and horizontal gap of 5 pixels. FlowLayout(int align,int vgap,int hgap) Constructs a new flow layout with the alignment specified, leaving a vertical and horizontal gap as specified Method getAlignment() getHgap() getVgap() setAlignment(int align) setHgap(int n) setVgap(int n) Eg: import java.awt.*; import java.applet.*; public class FLDemo extends Applet { Button b1,b2,b3;

public void init() { setLayout(new FlowLayout(FlowLayout.LEFT,50,30)); b1 = new Button("Yes"); b2 = new Button("No"); b3 = new Button("May be"); add(b1); add(b2); add(b3); } } //<applet code=FLDemo width=400 height=400> </applet> GridLayout constructor Description GridLayout() Constructs a grid layout with a default one column per component in a single row GridLayout(int rows,int cols) Constructs a grid layout with the specified rows and cols GridLayout(int rows,int cols,int hgap, int vgap) Creates a grid layout with the specified rows and cols and specified horizontal and vertical gaps Method getColumns() getRows() getHgap() getVgap() setColumns(int cols) setRows(int rows) setHgap(int hgap) setVgap(int vgap) Eg: import java.applet.*; import java.awt.*; public class GLDemo extends Applet { public void init() { setLayout(new GridLayout(5,5,10,10)); for(int i=1;i<=5;i++)

{ for(int j=1;j<=5;j++) { add(new Button("j = " + j)); } } } } //<applet code=GLDemo width=400 height=400></applet> BorderLayout Constructor Description BorderLayout() Creates a new BorderLayout with no gap between the components BorderLayout(int hgap,int vgap) Creates a new BorderLayout with thespecified hgap and vgap between components Methods getHgap() getVgap() setHgap(int hgap) setVgap(int vgap) Insets method around the control sets the gap in top,bottom,left and right Insets(top,bottom,left,right) Eg: import java.awt.*; import java.applet.*; public class BLDemo extends Applet { Button north,south,east,west; TextArea ta; public void init() { setLayout(new BorderLayout(10,20)); north = new Button("North"); south = new Button("South"); east = new Button("East"); west = new Button("West"); ta = new TextArea();

add(BorderLayout.SOUTH,south); add(BorderLayout.NORTH,north); add(BorderLayout.EAST,east); add(BorderLayout.WEST,west); add(BorderLayout.CENTER,ta); } public Insets getInsets() { return new Insets(10,10,10,10); } } //<applet code=BLDemo width=400 height=400></applet> CardLayout CardLayout() Creates a new CardLayout CardLayout(int hgap,int vgap) Create a new CardLayout with hgap and vgap value Methods setHgap(int gap) setVgap(int gap) getHgap() getVgap() Eg: import java.awt.*; import java.applet.*; import java.awt.event.*; class windowsPanel extends Panel { Checkbox win98,winnt,solaris,mac; public windowsPanel() { setLayout(new FlowLayout()); win98 = new Checkbox("Windows 98"); winnt = new Checkbox("Windows NT"); solaris = new Checkbox("Solaris"); mac = new Checkbox("Mac OS"); add(win98); add(winnt); add(solaris); add(mac); }

} class browserPanel extends Panel { Choice browser; public browserPanel() { setLayout(new FlowLayout()); browser = new Choice(); browser.add("Internet Explorer"); browser.add("Netscape Navigator"); browser.add("Appletviewer"); browser.add("Hotjava"); add(browser); } } public class CLDemo extends Applet implements ActionListener { Button b1,b2; windowsPanel w1 = new windowsPanel(); browserPanel p1 = new browserPanel(); public void init() { setLayout(new FlowLayout()); b1 = new Button("Windows"); b2 = new Button("Browser"); Panel s1 = new Panel(); s1.setLayout(new CardLayout()); s1.add("Windows",w1); s1.add("Browser",p1); add(b1); add(b2); add(s1); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { if(ae.getSource() == b1) { w1.setSize(400,400);

w1.setVisible(true); p1.setVisible(false); } else { w1.setVisible(false); p1.setSize(200,200); p1.setVisible(true); } } } //<applet code=CLDemo width=400 height=400></applet> JFC/Swing (Java Foundation Class) Swing is a set of classes that provides more powerful and flexible components than are possible with AWT. In addition to the familiar components, such as button,check boxes and labels, Swing supplies several exciting additions, including tabbedpanes, scrollpanes,trees and tables. Unlike AWT components, Swing components are not implemented by platform-specific code. Instead, they are written in Java and, therefore, are platform-independent. The term lightweight is used to describe such elements. AWT - Heavy Weight Components javax.swing.*; Class Description AbstractButton Abstract superclass for swing buttons ButtonGroup Encapsulates a mutually exclusives set of buttons ImageIcon Encapsulates an icon JApplet The swing version of Applet JButton The swing push button class JCheckBox The swing checkbox class JComboBox Encapsulates a combo box (an combination of drop-down list and text field) JLabel The swing version of a label. JRadioButton The swing version of a radio button JScrollPane Encapsulates a scrollable window JTabbedPane Encapsulates a tabbed window

JTable Encapsulates a table based control JTextField The swing version of text field JTree Encapsulates a tree based control swing related classes are contained in javax.swing.* package JApplet same as applet class in awt. Container c=getContentPane(); //Retrieves the browser settings. c.add(components); Icons and Labels Icons are encapsulated by the ImageIcon class. ImageIcon(String filename); ImageIcon i1 = new ImageIcon("new.gif"); ImageIcon(URL url); ImageIcon i2 = new ImageIcon("d:\demo\new.gif"); Method Description int getIconHeight() Returns the height of the icon in pixels. int getIconWidth() Returns the width of the icon in pixels void paintIcon(Component comp, Graphics g,int x,int y) Paints the icon at position x,y on the graphics context g. JLabel JLabel(icon i) JLabel(String s) JLabel(String s,icon i,int align) align = LEFT,RIGHT,CENTER,LEADING,TRAILING Methods Icon getIcon() String getText() void setIcon(ImageIcon) void setText(String s) Eg: import javax.swing.*; import java.awt.*; public class JLabelDemo extends JApplet { public void init() { Container c = getContentPane(); ImageIcon ii = new ImageIcon("fish.gif"); JLabel jl = new JLabel("Fish",ii,JLabel.CENTER); c.add(jl);

} } //<applet code="JLabelDemo.class" width=500 height=500></applet> JTextFields JTextField() JTextField(int cols) JTextField(String s,int cols) JTextField(String s) Eg: import javax.swing.*; import java.awt.*; public class JTextFieldDemo extends JApplet { public void init() { Container c = getContentPane(); c.setLayout(new FlowLayout()); JLabel jl= new JLabel("Enter Name : "); JTextField jtf = new JTextField(15); c.add(jl); c.add(jtf); } } //<applet code="JTextFieldDemo.class" width=500 height=500></applet> JButton String getText() void setText(String s) void addActionListener(ActionListener al) void removeActionListener(ActionListener al) JButton(Icon i) JButton(String s) JButton(String s,Icon i) Eg: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JButtonDemo extends JApplet implements ActionListener{ JTextField jtf; public void init() { Container c = getContentPane(); c.setLayout(new FlowLayout());

ImageIcon i1 = new ImageIcon("Juggler1.gif"); JButton jb = new JButton(i1); jb.setActionCommand("Juggler1"); jb.addActionListener(this); c.add(jb); ImageIcon i2 = new ImageIcon("Juggler2.gif"); jb = new JButton(i2); jb.setActionCommand("Juggler2"); jb.addActionListener(this); c.add(jb); ImageIcon i3 = new ImageIcon("Juggler3.gif"); jb = new JButton(i3); jb.setActionCommand("Juggler3"); jb.addActionListener(this); c.add(jb); ImageIcon i4 = new ImageIcon("Juggler4.gif"); jb = new JButton(i4); jb.setActionCommand("Juggler4"); jb.addActionListener(this); c.add(jb); jtf = new JTextField(15); c.add(jtf); } public void actionPerformed(ActionEvent ae) { jtf.setText(ae.getActionCommand()); } } //<applet code="JButtonDemo.class" width=500 height=500></applet> JCheckBox void setDisabledIcon(icon di) void setPressedIcon(Icon pi) void setSelectedIcon(Icon si) void setRollOverIcon(Icon ri) JCheckBox(Icon i) JChecjBox(Icon i, boolean state) JCheckBox(String s) JCheckBox(String s,boolean state) JCheckBox(String s,Icon i) JCheckBox(String s,Icon i,boolean state) void setSelected(boolean state)

ItemStateChanged() - event getText() method getItem() method Eg: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JCheckBoxDemo extends JApplet implements ItemListener { JTextField jtf; public void init() { Container c = getContentPane(); c.setLayout(new FlowLayout()); ImageIcon normal = new ImageIcon("new.gif"); ImageIcon rollover =new ImageIcon("open.gif"); ImageIcon selected = new ImageIcon("save.gif"); JCheckBox cb = new JCheckBox("C",normal); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this); c.add(cb); cb = new JCheckBox("C++",rollover); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this); c.add(cb); cb = new JCheckBox("Java",selected); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this); c.add(cb); cb = new JCheckBox("Perl",normal); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this); c.add(cb); jtf = new JTextField(15); c.add(jtf); }

public void itemStateChanged(ItemEvent ie) { JCheckBox cb = (JCheckBox)ie.getItem(); jtf.setText(cb.getText()); } } //<applet code="JCheckBoxDemo.class" width=400 height=400></applet> JRadioButton JRadioButton(Icon i) JRadioButton(Icon i,boolean state) JRadioButton(String s) JRadioButton(String s,boolean state) JRadioButton(String s,icon i) JRadioButton(String s,Icon i,boolean state) Eg: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JRadioButtonDemo extends JApplet implements ActionListener { JTextField tf; public void init() { Container c = getContentPane(); c.setLayout(new FlowLayout()); JRadioButton b1= new JRadioButton("A"); b1.addActionListener(this); c.add(b1); JRadioButton b2 = new JRadioButton("B"); b2.addActionListener(this); c.add(b2); JRadioButton b3 = new JRadioButton("C"); b3.addActionListener(this); c.add(b3); ButtonGroup bg = new ButtonGroup(); bg.add(b1); bg.add(b2); bg.add(b3); tf = new JTextField(5); c.add(tf); }

public void actionPerformed(ActionEvent ae) { tf.setText(ae.getActionCommand()); } } //<applet code="JRadioButtonDemo.class" width=400 height=400></applet> JComboBox JComboBox() JComboBox(Vector v) Vector -> Dynamic arrays which contains unlike datatypes void addItem(Object obj) Eg: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JComboBoxDemo extends JApplet implements ItemListener { JLabel jl; ImageIcon ju1,ju2,ju3,ju4; public void init() { Container c = getContentPane(); c.setLayout(new FlowLayout()); JComboBox jc = new JComboBox(); jc.addItem("Juggler1"); jc.addItem("Juggler2"); jc.addItem("Juggler3"); jc.addItem("Juggler4"); jc.addItemListener(this); c.add(jc); jl = new JLabel(new ImageIcon("Juggler1.gif")); c.add(jl); } public void itemStateChanged(ItemEvent ie) { String s = (String)ie.getItem(); jl.setIcon(new ImageIcon(s + ".gif")); } } //<applet code="JComboBoxDemo.class" width=400 height=400></applet> JTabbed Panes

A Tabbed pane is a component that appears as a group of folders in a file cabinet. JTabbedPane() void addTab(String str,Component comp) Eg: import javax.swing.*; import java.awt.event.*; import java.awt.*; public class JTabbedPaneDemo extends JApplet { public void init() { Container c = getContentPane(); JTabbedPane jtp = new JTabbedPane(); jtp.addTab("Cities",new CitiesPanel()); jtp.addTab("Colors",new ColorsPanel()); jtp.addTab("Flavours",new FlavoursPanel()); c.add(jtp); } } class CitiesPanel extends JPanel { public CitiesPanel() { JButton b1 = new JButton("New York"); add(b1); JButton b2 = new JButton("London"); add(b2); JButton b3 = new JButton("Hong Kong"); add(b3); JButton b4 = new JButton("Tokyo"); add(b4); } } class ColorsPanel extends JPanel { public ColorsPanel() { JCheckBox cb = new JCheckBox("Red"); add(cb); JCheckBox cb1 = new JCheckBox("Green"); add(cb1); JCheckBox cb2 = new JCheckBox("Blue"); add(cb2); } }

class FlavoursPanel extends JPanel { public FlavoursPanel() { JComboBox jcb = new JComboBox(); jcb.addItem("Vanilla"); jcb.addItem("Chocolate"); jcb.addItem("Strawberry"); add(jcb); } } //<applet code="JTabbedPaneDemo.class" width=400 height=400></applet> JScrollPanes JScrollPane(Component comp) JScrollPane(int vsb,int hsb) JScrollPane(Component comp,int vsb,int hsb) Constant HORIZONTAL_SCROLLBAR_AS_NEEDED HORIZONTAL_SCROLLBAR_ALWAYS VERTICAL_SCROLLBAR_AS_NEEDED VERTICAL_SCROLLBAR_ALWAYS Eg: import java.awt.*; import javax.swing.*; public class JScrollPaneDemo extends JApplet { public void init () { Container c=getContentPane(); c.setLayout(new BorderLayout()); JPanel jp=new JPanel(); jp.setLayout(new GridLayout(20,20)); int b=0; for(int i=0;i<10;i++) { for(int j=0;j<10;j++) { jp.add(new JButton("Button " + b)); ++b; } } int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

JScrollPane jsp=new JScrollPane(jp,v,h); c.add(jsp); } } //<applet code="JScrollPaneDemo.class" width=400 height=380></applet> JTree JTree(HashTable ht) child node in first form JTree(Object obj[]) obj is a child node in second form JTree(TreeNode tn) tree in the third form JTree(Vector v) child nodes Events addTreeExpansionListener(TreeExpansionListener tel) removeTreeExpansionListener(TreeExpansionListener tel) TreePath getPathForLocation(int x,int y) - method toString() - used to return the treepath DefaultMutableTreeNode(Object obj) void add(MutableTreeNode child) TreeExpansionListener interface provides two methods void treeCollapsed(TreeExpansionEvent tee) void treeExpanded(TreeExpansionEvent tee) Eg: import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.tree.*; public class JTreeEvents extends JApplet { JTree tree; JTextField jtf; public void init() { Container c = getContentPane(); c.setLayout(new FlowLayout()); DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options"); DefaultMutableTreeNode a = new DefaultMutableTreeNode("A"); top.add(a); DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1"); a.add(a1);

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2"); a.add(a2); DefaultMutableTreeNode b = new DefaultMutableTreeNode("B"); top.add(b); DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1"); b.add(b1); DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2"); b.add(b2); DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3"); b.add(b3); tree = new JTree(top); int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(tree,v,h); c.add(jsp,BorderLayout.CENTER); jtf = new JTextField(20); c.add(jtf,BorderLayout.SOUTH); tree.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { doMouseClicked(me); } }); } void doMouseClicked(MouseEvent me) { TreePath tp = tree.getPathForLocation(me.getX(),me.getY()); if (tp != null) jtf.setText(tp.toString()); else jtf.setText(""); } } //<applet code="JTreeEvents.class" width=400 height=400></applet> JTable

JTable(Object data[][],Object colHeads[]) Eg: import java.awt.*; import javax.swing.*; public class JTableDemo extends JApplet { public void init() { Container c=getContentPane(); c.setLayout(new BorderLayout()); final String[] colHeads={"Name","Phone","Fax"}; final Object[][] data = { {"Gail","4567","8675"}, {"subha","5757","7575"}, {"akila","4747","6822"}, {"nikila","4848","4382"}, {"sabari","4756","3284"}, {"vino","9743","3975"}, {"sowmi","5856","8356"}, {"leela","2348","2453"}, {"padma","4535","1435"}, {"urmila","3457","3457"}, {"uma","4774","2345"}, {"chitra","4742","3245"}, {"vidhya","3456","2134"}, {"nithya","3453","2492"} }; JTable table=new JTable(data,colHeads); int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp=new JScrollPane(table,v,h); c.add(jsp,BorderLayout.CENTER); } } //<applet code="JTableDemo.class" width=300 height=300></applet> JDBC -> Java Database Connectivity Used to connect with database.. ODBC - Open Database Connectivity

SQL - Server username:sa password: Create table stud(sno int,sname varchar(20),course varchar(10),fees int) sp_help stud Select * from stud Insert into stud values(100,'aaaa','dast',4500); Creating DSN (Data source Name) Start -> settings -> Control Panel -> Administrative Tools -> ODBC Data Sources * Click the Add Button * Select the Driver Name "SQL -Server" Steps to Connect with Backend 1. Initialize the Driver File Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 2. Establish the connection with database. 3. Query the Database. java.sql.*; Connection -> Establish Connection ResultSet -> Query the Database (Select) Statement -> Execute the commands (DDL(Data Definition Language) - Create, Alter, Drop DML(Data Manipulation Language)- Insert, Update, Delete TCL(Transaction and control Language) - commit, Rollback) PreparedStatement -> Execute the commands. try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:mysql","sa","killer"); } Connection Class Methods createStatement() -> Initialize the Statement object Statement Class Methods executeUpdate(String qry) -> Execute Create, Alter, Drop, Insert,Update, Delete Command executeQuery(String qry) -> Execute Select command. TableCreationDemo.java import java.sql.*;

class TableCreationDemo { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","sa",""); String qry = "Create Table Stud1(sno int,sname varchar(20))"; Statement st = con.createStatement(); st.executeUpdate(qry); System.out.println("Table Created"); } catch(Exception e) { System.out.println("Exception : " + e); } } } InsertionDemo.java import java.sql.*; import java.io.*; class InsertionDemo { public static void main(String args[]) { int sno; String sname; String wish="y"; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","sa",""); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); do{ System.out.print("Enter sno and sname : "); sno = Integer.parseInt(br.readLine());

sname = br.readLine(); String qry = "Insert into Stud1 values(" + sno + ",' " + sname + " ')"; Statement st = con.createStatement(); int r = st.executeUpdate(qry); System.out.println(r + " row(s) Inserted"); System.out.print("Add Another Record (y/n)?"); wish = br.readLine(); }while(wish.equals("y")); }catch(Exception e) { System.out.println("Exception : " + e); } } } SELECTIONDEMO.java import java.sql.*; class SelectionDemo { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:mydsn","sa",""); Statement st = con.createStatement(); String qry = "Select * from stud1"; ResultSet rs = st.executeQuery(qry); while(rs.next()) { System.out.println(rs.getInt(1) + " " + rs.getString(2)); } }catch(Exception e) { System.out.println("Exception : " + e); } } } Student.java import java.sql.*;

import java.awt.*; import java.awt.event.*; public class Student extends Frame implements ActionListener { Label sno,sname; TextField sn,sna; Button ins,can; Connection con; String msg = new String(); public Student(String title) { super(title); setLayout(new FlowLayout()); sno = new Label("Sno"); sname = new Label("Sname"); sn = new TextField(5); sna = new TextField(20); ins = new Button("Insert"); can = new Button("Cancel"); add(sno); add(sn); add(sname); add(sna); add(ins); add(can); ins.addActionListener(this); can.addActionListener(this); addWindowListener(new MWA(this)); } public void actionPerformed(ActionEvent ae) { int no; String nam; if(ae.getSource() == ins) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:mydsn","sa","");

no = Integer.parseInt(sn.getText()); nam = sna.getText(); String qry = "Insert into Stud1 Values(" + no + ",'" + nam + "')"; Statement st = con.createStatement(); int r = st.executeUpdate(qry); msg = r + " row(s) Inserted"; MessageBox mb = new MessageBox(msg); mb.setVisible(true); } catch(Exception e) { System.out.println("Exception : " + e); } } else if(ae.getSource() == can) { sn.setText(""); sna.setText(""); } } public static void main(String args[]) { Student s = new Student("Student Data"); s.setVisible(true); s.setSize(400,400); } } class MWA extends WindowAdapter { Student s; public MWA(Student s) { this.s = s; } public void windowClosing(WindowEvent we) { try { s.dispose(); System.exit(0);

}catch(Exception e){} } } class MessageBox extends Frame implements ActionListener { Label ms; Button b1; public MessageBox(String lab) { setLayout(new FlowLayout()); ms = new Label(lab); b1 = new Button("ok"); add(ms); add(b1); setSize(200,200); setLocation(100,100); b1.addActionListener(this); } public void actionPerformed(ActionEvent ae) { try{ dispose(); }catch(Exception e){} } } Exercise: Update sname from stud1 where sno=101; Delete from stud1 where sname=" "; Update set sname=Brindha where sname=Akila

Remote Method Invocation


Which allows a Java object that executes on one machine to invoke a method of a Java object that executes on another Machine. In this way RMI supports Distributed applications. DCOM -> Distributed component Object model CORBA -> Common Object Request Broker Architecture. Java C++ Working of an RMI Application

* Server side * Client Side. Server side Method definitions. Three files are created for server (ie) 1. Interface file which contains the declaration of the method. That interface can be extend with the class of Remote (ie) the methods are accessed using remote object. The methods also declared with the exception of RemoteException 2. A Class file that implements the interface. This class extends the UnicastRemoteObject class. 3. The third file creates the object of the class and binds the object in RMI Registry. Client Accessing the method that is defined in the server.A file that creates a class that access the remote object through rmi registry. Starting RMI Registry jdk\bin> rmiregistry Understanding RMI Architecture Application Layer -> Responsible for actual representation of the client and server implementation. Stub/Skeleton Layer -> The stub acts as a representative of a server on the client side and skeleton acts as a representative of a client on the server side. Stub Class It is responsible for initiating a call to the remote object that it represents by way of the remote reference layer. The stub is responsible for passing the method details such as its name, parameters and the return type ofthe remote reference layer through a marshall stream. A marshal stream is simply a stream object that is used to transport parameters, exceptions and errors needed for method dispatch and returning the results. Skeleton Class The skeleton is responsible for sending parameter to the method implementation and for sending return values and exception back to the client that made the call. Remote Reference layer

The remote reference layer acts as a layer of abstraction between the stub and skeleton classes and the communication protocols that are handled by the transport layer. Transport layer This layer is responsible for setting up connection and handling the transport of data from one machine to another.
Client / Java Server / Java

Stub

Skeleton

RMI Registry

Network Layer

Programs SimpleIntf.java import java.rmi.*; public interface SimpleIntf extends Remote { public int add(int a,int b) throws RemoteException; public int sub(int a1,int b1) throws RemoteException; } SimpleImpl.java import java.rmi.*; import java.rmi.server.*; public class SimpleImpl extends UnicastRemoteObject implements SimpleIntf { public SimpleImpl() throws RemoteException {} public int add(int a,int b) throws RemoteException { return a+b; } public int sub(int a1,int b1) throws RemoteException

{ return a1-b1; } } Server.java import java.rmi.*; class Server { public static void main(String args[]) throws Exception { SimpleImpl s1 = new SimpleImpl(); System.out.println("Server Initializing...."); Naming.rebind("sys1",s1); System.out.println("Server Registered..."); } } Client.java import java.rmi.*; import java.rmi.server.*; class Client { public static void main(String args[]) throws Exception { String url = "rmi://system6/sys1"; SimpleIntf intf1 = (SimpleIntf) Naming.lookup(url); int c = intf1.add(10,20); int d = intf1.sub(40,30); System.out.println("c = " + c); System.out.println("d = " + d); } } javac SimpleIntf.java javac SimpleImpl.java rmic SimpleImpl javac Server.java javac Client.java First Command Prompt >rmiregistry

Second Command Prompt >java Server Third Command Prompt >java Client ChatIntf.java import java.rmi.*; public interface ChatIntf extends Remote { public String get() throws RemoteException; public void set(String str) throws RemoteException; } ChatImpl.java import java.rmi.*; import java.rmi.server.*; public class ChatImpl extends UnicastRemoteObject implements ChatIntf { String s = ""; public ChatImpl() throws RemoteException {} public String get() throws RemoteException { return s; } public void set(String str) throws RemoteException { s = s + str + "\n"; } } ChatServer.java import java.rmi.*; import java.rmi.server.*; public class ChatServer { public static void main(String args[]) throws Exception { ChatImpl impl = new ChatImpl(); System.out.println("Initializing server...."); Naming.rebind("chat",impl);

System.out.println("Registered...."); } } ChatClient.java import java.rmi.*; import java.rmi.server.*; import java.applet.*; import java.awt.event.*; import java.awt.*; public class ChatClient extends Applet implements ActionListener { Label l1,l2; TextField tf,tf1; TextArea ta; ChatIntf ci; String Name=""; public void init() { try { ci = (ChatIntf)Naming.lookup("rmi://system16/chat"); } catch(Exception e) { System.out.println("Lookup Error"); } l1 = new Label("Username : "); l2 = new Label("Message : "); tf = new TextField(20); tf1 = new TextField(30); ta = new TextArea(); add(l1); add(tf); add(l2); add(tf1); add(ta); tf.addActionListener(this); tf1.addActionListener(this);

receiveClient r1 = new receiveClient(this,ci); r1.start(); } public void actionPerformed(ActionEvent ae) { if(ae.getSource() == tf) { String x = tf.getText(); try { Name = Name + x + " : "; ci.set(Name); }catch(Exception e) {} tf.setText(""); } else if(ae.getSource() == tf1) { Name += tf1.getText(); try { ci.set(Name); }catch(Exception e) {} tf1.setText(""); } } } class receiveClient extends Thread { ChatIntf ci; ChatClient cl; public receiveClient(ChatClient cl,ChatIntf ci) { this.cl = cl; this.ci = ci; } public void run() { String s = null;

while(true) { try { s = ci.get(); cl.ta.setText(s); Thread.sleep(2000); }catch(Exception e) {} } } } //<applet code=ChatClient width=400 height=400></applet> DBIntf.java import java.rmi.*; import java.io.*; import java.sql.*; public interface DBIntf extends Remote { public void adding(String query) throws RemoteException,SQLException,ClassNotFoundException; public void update(String query) throws RemoteException,SQLException,ClassNotFoundException; public void delete(String query) throws RemoteException,SQLException,ClassNotFoundException; public String retrieve(String query) throws RemoteException,SQLException,ClassNotFoundException; } DBImpl.java import java.rmi.*; import java.rmi.server.*; import java.sql.*; public class DBImpl extends UnicastRemoteObject implements DBIntf { Connection connection; Statement statement; PreparedStatement ps; public DBImpl() throws RemoteException {

try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection("jdbc:odbc:mysql","sa","killer"); statement = connection.createStatement(); }catch(ClassNotFoundException e) {} catch(SQLException ex){} } public void adding(String query) throws RemoteException,SQLException,ClassNotFoundException { ps = connection.prepareStatement(query); ps.execute(); } public void update(String query) throws RemoteException, SQLException, ClassNotFoundException { ps = connection.prepareStatement(query); ps.execute(); } public void delete(String query) throws RemoteException,SQLException, ClassNotFoundException { ps = connection.prepareStatement(query); ps.execute(); } public String retrieve(String query) throws RemoteException, SQLException, ClassNotFoundException { String res = new String(); ResultSet rs = statement.executeQuery(query); ResultSetMetaData metadata = rs.getMetaData(); int columns = metadata.getColumnCount(); while(rs.next()) { for(int i=1;i<=columns;i++) {

res += rs.getString(i); } } return res; } public static void main(String args[]) throws Exception { DBImpl impl = new DBImpl(); Naming.rebind("DBase",impl); System.out.println("Service bound"); } } DBClient.java import java.rmi.*; import java.rmi.server.*; import java.sql.*; public class DBClient { DBIntf intf; public DBClient() throws RemoteException { try{ intf = (DBIntf) Naming.lookup("rmi://system6/DBase"); System.out.println("DBase Found"); }catch(Exception e) { System.out.println("Exception : " + e); } } public void add1() throws RemoteException,SQLException,ClassNotFoundException { intf.adding("Insert into students values(\'ABI\',\'B.Com\')"); System.out.println("Record Added"); } public void edit() throws RemoteException, SQLException, ClassNotFoundException {

intf.update("Update students set course=\'M.Com\' where sname=\'ABI\'"); System.out.println("Record Updated"); } public void retr() throws RemoteException, SQLException, ClassNotFoundException { String str = "Select * from students where sname=\'ABI\'"; System.out.println("The Result is : " + intf.retrieve(str)); } public void del() throws RemoteException, SQLException, ClassNotFoundException { String str = "Delete from students where sname=\'aaaa\'"; intf.delete(str); System.out.println("Record Deleted"); } public static void main(String args[]) { try { DBClient dbc = new DBClient(); dbc.add1(); dbc.edit(); dbc.retr(); // dbc.del(); }catch(Exception e) { System.out.println("Exception : " + e); } } }

Servlets
Servlets are program that run on a Web Server and build Web pages dynamically. A Servlet can be though of as a server side applet. Servlets are loaded and executed by a Web Server in the same manner as the

applets are loaded and executed by a Web browser. A servlet accesses requests from the client, performs some task, and returns results. The following are the basic steps of using servlets * The client makes a request * The web server forwards the request to the servlet after receiving it from the client * Some kind of process is done by the servlet after receiving the request. * A response is returned back to the web server from the servlet. * The web server will forwards the response to the client. The security issues, as associated with applets, are not applied with servlets because servlets are executed on the server and if your Web server is secure behind a firewall, then your servlet is secure as well. Why use Servlets? Servlets have various benefits over other technologies that are used for writing server side programs. One such technology is CGI (Common Gateway Interface) scripts. Servlets have less startup cost, they run continously, and they are Platform - Independent. The CGI program that handles the request for the server is terminated as soon as the request is processed whereas the Servlets continue to run even after the request is processed. This eliminates the heavy startup overhead. The CGI program must store the information in a database or a file and read it again the next time it starts up when it needs to maintain information across the network. There is heavy startup overhead for this reason. You have to create different versions of plug ins for running the same CGI program on a different hardware platform or a different operating system. Servlets can run on any platform that supports Java. Requirements for writing servlets We have to install JavaSoft's Java Servlet Development Kit (JSDK) before creating any servlet. This kit includes the Java.servlet and Sun.servlet pacakges, sample servlets for Windows 95 and NT, and ServletRunner to test servlets. We have to set the environment variable CLASSPATH, to the required location so that your servlets can find the servlet packages. The following environment variable need to be set for Windows systems, with the JSDK installed in the C:\jsdk; d:\demo\servlet>set Classpath=%path%;d:\jsdk2.0\src; d:\demo\servlet>set path=%path%;d:\jdk1.3\bin;

Steps required to run any Servlet * If your web server is not running, start it. * Configure the Web Server to install the servlet. * Run your Web browser. * Direct the browser to the particular URL that refers to the new servlet. Another thing to remember while creating servlets is that you need to create some kind of client application that invokes the servlet. This client application can be provided in the form of HTML or applets. We will be developing our application using HTML. While HTML is lightweight and is supported by Java enabled web browsers, applets are beneficial as they solve the portability and distribution problems. We will be using both HTML and applets to communicate with servlets. The Servlet Architecture There are various interfaces and classes that are used to implement a simple servlet. Let us discuss some of them that are essential for working of a servlet. The Servlet Interface All servlets are implemented the Servlet Interface, either directly or by extending a class that implements it such as GenericServlet. The Servlet interface provides methods that manage the servlet and its comunications with clients. While developing a servlet, we need to provide implementations for all or some of these methods. For example, the init() and destroy() methods are used to start and stop a servlet. The service() method is invoked by the server so that the servlet can perform its services. It takes two parameters one of the ServletRequest interface and the other of the ServletResponse interface. ServletResponse and ServletRequest Interface When a servlet accepts a call from a client, it receives object from the ServletRequest and ServletResponse interfaces. The ServletRequest interface encapsulates the communication from the client to the server, while the ServletResponse interface encapsulates the communication from the servlet back to the client. The ServletRequest interface allows the servlet access to information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host (getRemoteHost() method) that made the request and the server that received it. It also provides the servlet with access to the input stream, ServletInputStream, through which the servlet gets data from clients that

are using application protocols such as the HTTP POST and PUT methods. Subclasses of ServletRequest allow the servlet to retrieve more protocol specific data. For example, HttpServletRequest contains methods for accessing HTTP specific header information The ServletResponse interface gives the servlet methods for replying to the client. It allows the servlet to set the content length and mime type of the reply, and provides an output stream, ServletOutputStream, and a Writer through which the servlet can send the reply data. Subclasses of ServletResponse give the servlet more protocol-specific capabilities. For example, HttpServletResponse contains methods that allow the servlet to manipulate HTTP - specific headed information. Servlet Life cycle 1. When a server loads a servlet, it runs the servlet's init method. The servlet calls the init methods once, when it loads the servlet, and will not call it again unless it is reloading the servlet. The server cannot reload a servlet until after it has removed the servlet by calling the destroy method. 2. After the server loads and initializes the servlet, the servlet is able to handle client requests. It processes them in its service method. Each client's request has its call to the service method run in its own servlet thread: the method receives the client request, and sends the client its response. Servlets can run multiple service methods at a time. Eg: HelloServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloServlet extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { PrintWriter ps = res.getWriter(); res.setContentType("text/html"); ps.println("<h1 align=center> Hello Servlet </h1>"); } } FirstServlet.html

<html> <head> <title> My First Servlet Program </title> </head> <body bgcolor=#ffcc99> <center> <form method=post action="http://localhost:8080/servlet/HelloServlet"> <input type=submit> </form> </center> </body> </html> The Servlet API The Servlet API was defined by Sun Microsystems for writing servlets. The package javax.servlet defines all the classes and interfaces associated with the Servlet API. Some of the interfaces defined inside the Servlet API are: Servlet ServletContext ServletRequest ServletResponse And the classes are: ServletInputStream ServletOutputStream To Write servlets, the developer has to use the four interfaces to make the server comply with the servlet API and then use the server's implementations of these interfaces along with the ServletInputStream, and ServletOutputStream classes. The following section describes the Servlet API classes and interfaces in detail. Servlet Life Cycle init() service() destroy() Like Applet, Servlets also have Life Cycle to perform the clients request in a proper manner. There are three important methods available in Servlet Life Cycle.

init() method is loaded only once when the servlet begins the execution. This is the first loaded method in Servlet execution. service() method is the full responsible for the entire execution. This is executed each and every time whenever the user sends a request to the Server. This is the method to override the statements which are nessessary to execute at the time of request sending. destroy() method is executed at last when the servlet goes to the termination stage. Like init() method, destroy() method also executed only once at the time of termination of a process. GenericServlet GenericServlet is a class contains some methods which are helpful to perform the servlet operation by overriding the available methods in this class This class implements two interfaces named Servlet, ServletConfig. Servlet interface contains the methods getServletConfig() getServletInfo() init() service() destroy() ServletConfig interface contains the methods getInitParameters() getInitParameterNames() getServletContext() GenericServlet contains all the methods available in the Servlet and ServletConfig interfaces. HttpServlet HttpServlet is a class extended by GenericServlet class that contains some methods doGet() - when the data got from the Server. (visible to end user) doPost() - when the data posted to the server. (invisible to the end user) doPut() - when the data put on the server directly doDelete() - when the data deleted on the server doTrace() - when the data traced on the server MVC - Model View Controller Architecture Design -> Applet or HTML

Controller -> Servlet Business Logic -> EJB init() public void init(ServletConfig ob) throws ServletException { statements; } service() public void service(ServletRequest req, ServletResponse res) throws ServletException,IOException { statements; } doGet() public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { statements; } doPost() public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { statements; } Implementation * Create a Servlet Program * Compile the Program and copy the .class file into d:\jsdk2.0\examples * Start the Server servletrunner (which is the .exe file to start the WebServer, commonly located in the place d:\jsdk2.0\bin) * Open the Browser and type the following in the Address Bar http://localhost:8080/servlet/classfilename - if U run in the local system. http://remotehost:8080/servlet/classfilename - if U run in the remote system. Cookies Maintaining Variable Values between the pages. Cookie c1 = new Cookie("cookiename","cookievalue"); res.addCookie(c1); First Page

username password Second Page req.getParameter(username) req.getParameter(password) Cookie c1 = new Cookie("uname","aaaa"); Cookie c2 = new Cookie("pword","aaa"); res.addCookie(c1); res.addCookie(c2); -> Write only third page Cookie c[] = req.getCookies() -> read only for(int i=0;i<c.length;i++) if(c[i].getName().equals("uname")) Servlet Interface and its methods 1. public void service(ServletRequest req,ServletResponse res) 2. public void init() 3. ServletContext getServletContext() 4. void log(String mesg) 5. String getServletInfo() 6. public void destroy() ServletRequest interface 1. int getContentLength() 2. String getProtocol() 3. String getParameter(String ParameterName) 4. Enumeration getParameterNames() 5. InetAddress getRemoteAddr() 6. String getRemoteHost() 7. String getQueryString() 8. String getServerName() 9. int getServerPort() 10. String getPathTranslated() 11. String getHeader(String header_field) 12. ServletInputStream getInputStream() ServletResponse Interface 1. ServletOutputStream getOutputStream() 2. void setContentLength() 3. void setContentType(String type) 4. void writeHeaders()

5. void setStatus(int status) 6. void setHeader(String header_field,String header_value) status constants SC_OK SC_CREATED SC_NO_CONTENT SC_MOVED_PERMANENTLY SC_MOVED_TEMPORARILY SC_BAD_REQUEST SC_UNAUTHORIZED SC_FORBIDDEN SC_NOT_FOUND ServletContext Interface 1. String getServletInfo() 2. String getServlet() 3. Enumeration getServlets() Applet to Servlet Communication Session Tracking Session ID -> When the user pass the first request, the Session ID is created automatically and stored in System Cookie. The Session ID is used for the subsequent request. If the session is destroyed, the session ID cookie is destroyed automatically. HttpSession.putValue("SessionName","Value"); HttpSession.getValue("Sessionname"); Eg: First.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class First extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println("<h1> My First Servlet Program </h1>"); }

} First.html <html> <head> <title> First Servlet Program </title> </head> <body> <center> <form method=get action="http://localhost:8080/servlet/First"> <input type=submit> </form> </center> </body> </html> Running Program First Command Prompt > Set classpath=%path%;d:\jsdk2.0\src; >javac First.java >copy First.java d:\jsdk2.0\examples Second Command prompt d:\jsdk2.0\bin>servletrunner Internet Explorer First.html Login.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Login extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { pageHeader(res); dispDetail(res); pageFooter(res); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException

{ pageHeader(res); processDetail(req,res); pageFooter(res); } private void pageHeader(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<h1 align=center> Login Form </h1>"); } private void dispDetail(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<table align=center>"); out.println("<form method=post>"); out.println("<tr>"); out.println("<td> Username <td> <input type=text name=uname>"); out.println("<tr>"); out.println("<td> Password <td> <input type=password name=pword>"); out.println("<tr>"); out.println("<td><td> <input type=submit>"); out.println("</form>"); out.println("</table>"); } private void pageFooter(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<h2 align=center> Enter the Login Details </h2>"); }

private void processDetail(HttpServletRequest req,HttpServletResponse res) throws IOException { String uname,pword; uname = req.getParameter("uname"); pword = req.getParameter("pword"); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<table align=center border=1>"); out.println("<tr>"); out.println("<td> Username <td>" + uname); out.println("<tr>"); out.println("<td> Password <td>" + pword); out.println("</table>"); } } Regis.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.sql.*; import java.util.Date; public class Regis extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { pageHeader(res); dispDetail(res); pageFooter(res); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { pageHeader(res); storeDetail(req,res); pageFooter(res); }

private void pageHeader(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head><title>Registration Form</title></head>"); out.println("<body bgcolor=lightyellow>"); out.println("<h1 align=center> Registration Form </h1>"); } private void pageFooter(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("</body>"); out.println("</html>"); } private void dispDetail(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<table align=center>"); out.println("<form method=post>"); out.println("<tr>"); out.println("<td> Username <td> <input type=text name=uname>"); out.println("<tr>"); out.println("<td> Passsword <td> <input type=password name=pword>"); out.println("<tr> <td> Retype Password <td> <input type=password name=rpword>"); out.println("<tr> <td> Date of Birth <td> <input type=text name=dob>"); out.println("<tr> <td> Age <td> <input type=text name=age>"); out.println("<tr> <td> Address <td> <textarea rows=5 cols=25 name=addr></textarea>");

out.println("<tr> <td> Phone No <td> <input type=text name=phno>"); out.println("<tr> <td> Email ID <td> <input type=text name=emailid>"); out.println("<tr> <td> <td> <input type=submit> <input type=reset>"); out.println("</form>"); out.println("</table>"); } private void storeDetail(HttpServletRequest req,HttpServletResponse res) throws IOException { String uname,pword,rpword,db,addr,email; int phno,age; uname = req.getParameter("uname"); pword = req.getParameter("pword"); rpword = req.getParameter("rpword"); db = req.getParameter("dob"); age = Integer.parseInt(req.getParameter("age")); addr = req.getParameter("addr"); phno = Integer.parseInt(req.getParameter("phno")); email = req.getParameter("emailid"); res.setContentType("text/html"); PrintWriter out = res.getWriter(); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","sa","killer"); String qry = "Insert into Regis values('" + uname + "','" + pword + "','" + rpword + "','" + db + "'," + age + ",'" + addr + "'," + phno + ",'" + email + "')"; Statement st = con.createStatement(); int r = st.executeUpdate(qry); out.println("<h2 align=center> Record Inserted Sucessfully </h2>"); } catch(Exception e)

{ out.println("Exception : " + e); } } } DateField.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.sql.*; public class DateField extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { pageHeader(res); dispDetail(res); pageFooter(res); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { pageHeader(res); storeDetail(req,res); pageFooter(res); } private void pageHeader(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title> Date Validation </title></head>"); out.println("<body bgcolor=cyan>"); } private void dispDetail(HttpServletResponse res) throws IOException

{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<table align=center>"); out.println("<form method=post>"); out.println("<tr> <td> Date of Birth <td> <input type=text name=dob>"); out.println("<tr> <td> Age <td> <input type=text name=age>"); out.println("<tr> <td> <td> <input type=submit> <input type=reset>"); out.println("</form>"); out.println("</table>"); } private void storeDetail(HttpServletRequest req,HttpServletResponse res) throws IOException { String db; int age; res.setContentType("text/html"); PrintWriter out = res.getWriter(); db = req.getParameter("dob"); age = Integer.parseInt(req.getParameter("age")); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","sa","killer"); Statement st = con.createStatement(); String qry = "Insert into temp1 values('" + db + "'," + age + ")"; int r = st.executeUpdate(qry); if(r == 1) out.println("<h2 align=center> Record Inserted </h2>"); else out.println("<h2 align=center> Insertion Error </h2>"); }

catch(Exception e) { out.println("Exception : " + e); } } private void pageFooter(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("</body>"); out.println("</html>"); } } SearchDetail.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.sql.*; public class SearchDetail extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { pageHeader(res); dispDetail(res); pageFooter(res); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { pageHeader(res); viewDetail(req,res); pageFooter(res); } private void pageHeader(HttpServletResponse res) throws IOException {

PrintWriter out =res.getWriter(); res.setContentType("text/html"); out.println("<html><body bgcolor=#ffcc99>"); out.println("<form method=post>"); out.println("<table align=center border=1>"); } private void pageFooter(HttpServletResponse res)throws IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println("</table></form></body></html>"); } private void dispDetail(HttpServletResponse res)throws IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println("<tr> <td> Username <td> <select name=uname>"); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","sa","sa"); String qry = "Select username from Regis"; Statement st = con.createStatement(); ResultSet rs = st.executeQuery(qry); while(rs.next()) { String uname = rs.getString(1); out.println("<option value='" + uname + "'>" + uname); } con.close(); } catch(Exception e){} out.println("</select>"); out.println("<tr> <td> <input type=submit value=Submit>");

} private void viewDetail(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); String uname = req.getParameter("uname"); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","sa","sa"); String qry = "Select * from Regis where username='" + uname + "'"; Statement st = con.createStatement(); ResultSet rs = st.executeQuery(qry); if(rs.next()) { out.println("<tr> <td> " + rs.getString(1) + "<td>" + rs.getString(2) + "<td>" + rs.getString(3) + "<td>" + rs.getString(4) + "<td>" + rs.getInt(5) + "<td>" + rs.getString(6) + "<td>" + rs.getInt(7) + "<td>" + rs.getString(8)); } con.close(); } catch(Exception e) {} } } Cookie1.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Cookie1 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException

{ pageHeader(res); dispDetail(res); pageFooter(res); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { pageHeader(res); getDetail(req,res); pageFooter(res); } private void pageHeader(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head> <title> Cookies </title> </head>"); out.println("<body bgcolor=lightyellow>"); out.println("<h2 align=center> Adding Cookie </h2>"); } private void dispDetail(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<table align=center>"); out.println("<form method=post>"); out.println("<tr><td> Username <td> <input type=text name=uname>"); out.println("<tr><td> Password <td> <input type=password name=pword>"); out.println("<tr> <td> <td> <input type=submit> <input type=reset>"); out.println("</form>"); out.println("</table>"); }

private void getDetail(HttpServletRequest req,HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String una,pwd; una = req.getParameter("uname"); pwd = req.getParameter("pword"); out.println("Username : " + una + "<br>"); out.println("Password : " + pwd + "<br>"); out.println("<h3> Adding username and password to Cookies </h3>"); out.println("<h3> Click the <a href=http://localhost:8080/servlet/next> Next </a> Link to view the Cookies </h3>"); Cookie c1 = new Cookie("username",una); Cookie c2 = new Cookie("password",pwd); res.addCookie(c1); res.addCookie(c2); } private void pageFooter(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("</body>"); out.println("</html>"); } } next.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class next extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {

pageHeader(res); dispDetail(req,res); pageFooter(res); } private void pageHeader(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head><title> Retrieving Cookie </title> </head>"); out.println("<body bgcolor=lightyellow>"); out.println("<h2 align=center> Cookie Values are </h2>"); } private void dispDetail(HttpServletRequest req,HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); Cookie c[] = req.getCookies(); out.println("<table align=center border=1>"); for(int i=0;i<c.length;i++) { if(c[i].getName().equals("username")) { out.println("<td> Username : " + "<td>" + c[i].getValue()); } else if(c[i].getName().equals("password")) { out.println("<td> Password : " + "<td>" + c[i].getValue()); } } out.println("</table>"); }

private void pageFooter(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("</body>"); out.println("</html>"); } } Session1.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.Date; public class Session1 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("Text/html"); PrintWriter out = res.getWriter(); HttpSession session = req.getSession(true); out.println("<h2>"); out.println("<pre>"); out.println("Session ID : " + session.getId()); Date d = new Date(session.getCreationTime()); out.println("Creation Time : " + d); Date d1 = new Date(session.getLastAccessedTime()); out.println("Last Accessed Time : " + d1); out.println("New : " + session.isNew()); out.println("</pre>"); out.println("</h2>"); } } SessionCounter.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

public class SessionCounter extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); HttpSession hs = req.getSession(true); //session enabled if(hs.getValue("counter") == null) { hs.putValue("counter",new Integer(1)); } else { int count = ((Integer)hs.getValue("counter")).intValue() + 1; hs.putValue("counter",new Integer(count)); } out.println("<h1> You have visisted the page " + hs.getValue("counter") + " no of times</h1>"); } } Eg: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.sql.*; public class SessionCounter extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); HttpSession session = req.getSession(true); int count=0; try

{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:sdsn1","",""); String qry = "Select max(visitcount) from SessionCounter"; Statement st = con.createStatement(); ResultSet rs = st.executeQuery(qry); if(session.isNew()) { if(rs.next()) { count = rs.getInt(1); count++; qry = "Insert into SessionCounter values(" + count + ")"; int r = st.executeUpdate(qry); } else { count = 1; qry = "Insert into SessionCounter values(" + count + ")"; int r = st.executeUpdate(qry); } } else { if(rs.next()) { count = rs.getInt(1); } else { count = 1; } } } catch(Exception e)

{ out.println(e); } out.println("<h1 align=center>This Site has been visited " + count + " no of times</h1>"); } } myapplet.java import java.awt.*; import java.applet.*; import java.awt.event.*; import java.net.*; import java.io.*; public class myapplet extends Applet implements ActionListener { TextField tf,tf1; Button b; URL url; URLConnection uc; public void init() { tf= new TextField(20); b = new Button("Send"); tf1 = new TextField(20); add(tf); add(b); add(tf1); b.addActionListener(this); } public void actionPerformed(ActionEvent ae) { try { url = new URL("http://localhost:8080/servlet/myservlet1"); uc = url.openConnection(); uc.setDoOutput(true); uc.setDoInput(true);

DataOutputStream dout = new DataOutputStream(uc.getOutputStream()); dout.writeUTF(tf.getText()); dout.flush(); DataInputStream din = new DataInputStream(uc.getInputStream()); String data = din.readUTF(); tf1.setText(data); } catch(Exception e) { System.out.println("Exception : " + e); } } } //<applet code="myapplet.class" width=400 height=400></applet> myservlet1.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class myservlet1 extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { try { ServletInputStream sin = req.getInputStream(); DataInputStream din = new DataInputStream(sin); String data = din.readUTF(); ServletOutputStream sout = res.getOutputStream(); DataOutputStream dout = new DataOutputStream(sout); dout.writeUTF("Message From Servlet:- " + data); dout.flush(); }catch(Exception e) { System.out.println(e);

} } } Marquee.java import java.awt.*; import java.awt.event.*; import java.applet.*; import java.net.*; public class Marquee extends Applet implements ActionListener { TextField tf1,tf2; Label l1,l2; Button b1; URL url; public void init() { l1 = new Label("Enter a Text :"); l2 = new Label("Enter no of times : "); tf1 = new TextField(50); tf2 = new TextField(10); b1 = new Button("Click"); add(l1); add(tf1); add(l2); add(tf2); add(b1); b1.addActionListener(this); } public void actionPerformed(ActionEvent ae) { try { String txt = tf1.getText(); int no = Integer.parseInt(tf2.getText()); AppletContext con = getAppletContext(); url = new URL("http://localhost:8080/servlet/MarqueeServlet? text=" + txt + "&no=" + no); con.showDocument(url);

}catch(Exception ex){} } } MarqueeServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class MarqueeServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String txt = req.getParameter("text"); int no = Integer.parseInt(req.getParameter("no")); out.println("<body bgcolor=lightyellow>"); out.println("<marquee loop=" + no + ">" + txt + "</marquee>"); out.println("</body>"); } } SReq.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.Enumeration; public class SReq extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { pageHeader(res); dispDetail(res); pageFooter(res); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

{ pageHeader(res); viewDetail(req,res); pageFooter(res); } private void pageHeader(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head> <title> Servlet info </head> </title>"); out.println("<body bgcolor=lightyellow>"); } private void pageFooter(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("</body>"); out.println("</html>"); } private void dispDetail(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<form method=post>"); out.println("<table align=center>"); out.println("<tr><td> Username <td> <input type=text name=uname>"); out.println("<tr> <td> Password <td> <input type=password name=pword>"); out.println("<tr> <td> <td> <input type=submit> <input type=reset>"); out.println("</table>"); out.println("</form>"); }

private void viewDetail(HttpServletRequest req,HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String Name,Value; Enumeration enum; enum = req.getParameterNames(); while(enum.hasMoreElements()) { Name = (String)enum.nextElement(); Value = req.getParameter(Name); out.println(Name + " : " + Value + "<br>"); } } } SReqMeth.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SReqMeth extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { pageHeader(res); viewDetail(req,res); pageFooter(res); } private void pageHeader(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<body bgcolor=lightyellow>"); out.println("<h1 align=center> Request Methods </h1>"); }

private void viewDetail(HttpServletRequest req,HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("Protocol : " + req.getProtocol() + "<br>"); out.println("Content Length : " + req.getContentLength() + "<br>"); out.println("Remote Addr : " + req.getRemoteAddr() + "<br>"); out.println("Remote Host : " + req.getRemoteHost() + "<br>"); out.println("Query String : " + req.getQueryString() + "<br>"); out.println("Server Name : " + req.getServerName() + "<br>"); out.println("Path Translated : " + req.getPathTranslated() + "<br>"); } private void pageFooter(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("</body>"); out.println("</html>"); } }
Java Bean like ActiveX in VB - User Defined Control reusable components. We can Create the user control and set the properties, methods and event for that control Here All the components are treated as object. Software Component Basics 1. Software component is a software isolated into a discrete, reusable structure 2. Component is a reusable piece of software to create applications. 3. JavaBean technology is a component technology.

4. Implemented as an architecture - independent and Platform Independent Architecture Single Tier Architecture Two Tier Architecture (Client / Server Technology) Client -> Java Frame which contains controls. (Predefined , Userdefined) Server -> Storing and Distributing Data (Oracle, SQL - Server) Multi Tier Architecture Client -> Java Frames, HTML Controlling -> business logic (Database Connectivity and Functions - Java, Servlets, JSP, EJB) Server -> Storing and Retrieving Data (Oracle, SQL Server Two Types of Components 1. Visual Component - CheckBox, ListBox 2. Non Visual Component. - Timer Control, Spell Checker. Visual Software Components 1. Visual Software Components are software components with visual representation. 2. Button is an example for Visual software Component 3. Visual component propogates the user - input events. 4. Visual design tools/application builder tools provide support to graphically manipulate the buttons. Non Visual Software Components 1. Non visual component sounds an ideal use at programming level. 2. Timer control is an example for non-visual component. 3. Spell check is a self contained component and can be integrated into any application. Component Model 1. Defines the architecture of components 2. Software component model defines two fundamental elements namely components and containers 3. Containers are also referred to as forms, pages,frames (or) shells 4. Containers are also be component. A Component model is responsible for providing the following services. 1. Introspection -> This process exposes the properties, methods and events that a Java Bean component supports. It is used at runtime while the Bean is being created with the visual development tool.

2. Event Handling 3. Persistance - Permanent. 4. layout 5. Application Builder Support. (BDK) 6. Distributed Computing Support. (RMI, Servlets) Advantages of Java Beans 1. A Bean obtains all the benefits of Java's "Write Once, run AnyWhere" paradigm. 2. The properties, events and methods of a bean that are exposed to an application builder tool can be controlled. 3. A bean may be designed to operate correctly in different locales, which makes it useful in global markets. 4. Auxiliary software can be provided to help a person configure a Bean. This software is only needed when the design time parameters for that component are being set. It dos not need to be included in the run-time environment. 5. The Configration settings of a Bean can be saved in persistent storage and restored at later time. 6. A Bean my register to receive events from other objects and can generate events that are sent to other objects. Basic Structure of a Bean 1. Components of Data and Methods 2. Capable of accessing private,public and protected methods 3. Functionality of similar groups of methods and interfaces. 4. Interfaces provides support to facilitates such as persistance and application builder tool integration. Usage Scenarios - where it is used Two primary developement use scenarios for beans are; 1. Using an application builder tool to build an applet. 2. Handcoding an applet Using an Application builder tool to build an applet Steps required in building up an application are given below: 1. visually layout the application appropriately using beans. 2. Customize the beans using visual property editors. 3. Connect beans with builder tool facilities and write event handler code. 4. Package the application with the beans and share it. Bean Development Kit. c:\bdk\beanbox>run Using beans in handwritten code

Steps required in building up an application are given below: 1. Layout the applications and appropriately position the bean 2. Customize the beans 3. Connect the bean that register event listeners and handlers the event 4. Package the application with the beans and distribute them. Eg: Step1: Create a Java file and compile it. Step2: Create a Manifest file which contains the name of the classes and images. Step3: Create JAR (Java Archieve used to compress the classes,manifest and the images) File. Step4: Copy the jar file into bdk\jars. c -> A new archieve is to be created f-> The first element in the file list is the name of the archieve that is to be created or accessed. m -> The second element in the file list is the name of the external manifest file. jar cfm Circle.jar Circle.mft Circle.class Simple Property Boolean Property Indexed Property Simple Property A simple property contains one value that may be either a simple type or an object. Eg: int getSize(); void setSize(int a); void setColor(Color c); Color getColor(); Boolean Property A Boolean property has a value of true or false. It can be identified by the following pattern a specified in the example. boolean isVis() void setVis(boolean x); Indexed Property An indexed property is a property that can take an array of values. Eg: Circle.java import java.awt.*; import java.applet.*;

public class Circle extends Applet { public void paint(Graphics g) { g.drawOval(10,10,80,80); } } javac Circle.java Circle.mft Name: Circle.class Java-Bean: true d:\demo\beans>jar cfm Circle.jar Circle.mft Circle.class cd.. d:\demo\beans>copy Circle.jar c:\bdk\jars c:\bdk\beanbox>run myBean1.java import java.awt.*; public class myBean1 extends Canvas { private Color c = Color.red; public void setCol(Color a) { c = a; setBackground(c); } public Color getCol() { return c; } public myBean1() { setSize(100,100); setBackground(c); setVisible(true); } } myBean1.mft Name: myBean1.class Java-Bean: true

MyBean.java // Implementing Simple and Boolean Property import java.awt.*; import java.awt.event.*; public class MyBean extends Canvas implements MouseListener { private Color color; private boolean rectAngular; private int iWidth = 200; private int iHeight = 100; public MyBean() { addMouseListener(this); rectAngular = false; setSize(iWidth,iHeight); change(); } public void setHeight(int h) { iHeight = h; setSize(iWidth,iHeight); repaint(); } public int getHeight() { return iHeight; } public void setWidth(int w) { iWidth = w; setSize(iWidth,iHeight); repaint(); } public int getWidth() { return iWidth; } public void setRectangular(boolean flag) { this.rectAngular = flag;

repaint(); } public boolean getRectangular() { return rectAngular; } public void change() { color = randomColor(); repaint(); } private Color randomColor() { int r = (int) (255 * Math.random()); int g = (int) (255 * Math.random()); int b = (int) (255 * Math.random()); return new Color(r,g,b); } public void paint(Graphics g) { int h = iHeight; int w = iWidth; setSize(iWidth,iHeight); g.setColor(color); if(rectAngular) { g.drawRect(0,0,w-1,h-1); g.fillRect(0,0,w-1,h-1); } else { g.fillOval(0,0,w-1,h-1); } } public void mousePressed(MouseEvent me) { change(); } public void mouseReleased(MouseEvent me) {

change(); } public void mouseEntered(MouseEvent me) { change(); } public void mouseExited(MouseEvent me) { change(); } public void mouseClicked(MouseEvent me) { change(); } } MyBean.mft Name: MyBean.class Java-Bean: true myBean2.java // Implementing Simple, Indexed and Boolean Property import java.awt.*; public class myBean2 extends Canvas { private Color c = Color.cyan; private boolean v = true; private int[] b = {50,100,350}; private int sz = 0; public myBean2() { setSize(b[sz],b[sz]); setBackground(c); setVisible(v); } public void setCanvassize(int a) { sz = a; setSize(b[sz],b[sz]); } public int getCanvassize() {

return sz; } public boolean isVis() { return v; } public void setVis(boolean a) { v = a; setVisible(v); } public void setCol(Color a) { this.c = a; setBackground(c); } public Color getCol() { return c; } } myBean2.mft Name: myBean2.class Java-Bean: true

Java Server Pages Server Side Scripting Language. The Java Server Pages technology is platform independent. You can author JSP pages on any platform, run them on any web server and access them from any web browser. Webserver's running JSP Internet Information Server 5.0 (WindowsNT) JavaWebserver 2.0 Apache Server - This Server provide full support for JSP(WindowsNT) J2EE server Weblogic Websphere Life cycle of JSP 1. Browser Request HTML or JSP 2. The Request are received by the server. 3. Server sends request to Java Engine 3. If needed, the Java engine reads the .jsp file 4. The JSP is turned into a Servlet, compiled and loaded 5. The servlet runs and generates HTML 6. Java engine sends HTML to server 7. Server sends HTML back to browser Advantages 1. Flexible Environment 2. It supports direct beans information 3. It is an Interpreter Language(Automatically compiled) 4. It supports XML(Extensible Markup Language) tags 5. Reuse of components and tag libraries. Structural syntax of JSP Constructor jspInit() - Initialization jspService() - Processing request jspDestroy() - Destroyed Comments <%-- ...text... --%> JSP comments are stripped out by the JSP Engine at Translation time. Declarations <%! type varname; %>

<%! returntype methodname(argument1,argument2...){} %> eg: <%! String s=null; %> <%! void disp() {} %> Declarations may be used to add variables or methods to a JSP. <% (Scriptlet) Statements %> Expression <%= Expression %> <%= a+b %> The expression tag places the printable form of a Java expression into the output of a page. Scriptlets <% ...java code ...%> Scriptlets allow arbitary Java code, and eventually other languages, to be placed in a JSP. For the most part such code should reside in beans and other classes, but there are times when placing it in a page is unavoidable. Complex logic can be added to pages by surrounding regions of text with scriptlets, when one scriptlets ends with an opening brace and a second one provides a matching close. Eg: HTML file <html> <body> <h1> JSP </h1> <form method=get action="first.jsp"> <br> <input type=submit> </form> </body> </html> JSP file <%@ page language="java" %> <%! String s=null; %> <%s="csc" %> <B>s= <%= s %> </B> Include Directive

<%@ include file=" " %> The include directive adds the text of one JSP or Other file to another file at translation time. Page Directive <%@ page options ... %> The page directive specifies a large number of options that affect the entire page. Each of these options may be used independently language="java" This code will specifies what language will be used in scriplets. Currently only java is supported extends = "base class" This code can force the generated servlet to extend a specific class. This should be used very rarely import="package.class" import="java.sql.*" import="package.*" import="java.util.Date" Import parameters within a page directive turn into import statements in the generated java file. Multiple import statements can be used. session=true|false By default, the first time a user access any JSP on a site, a session is started for that user and the user will be issued a cookie. This behaviour can be disabled by setting the session flag to false. buffer="none|sizekb" This flag sets the amount of data that will be buffered before being sent to the user. The default is 1024Kb. None indicates that all output should be sent directly. autoflush="true|false" if buffering is turned on and this value is set to true, data will automatically be sent to the user when the buffer is full. if buffering is on and this value is set to false, an exception will occur when the buffer is full. is buffering is not on, this value has no effect. The default is true isThreadSafe="true|false" This value indicates whether it is safe for the JSP engine to send multiple requests to a page simultaneously. The default is true. Setting it to false is equivalent to declaring the generated servlet will implement SingleThreadModel. info="text"

This value sets a description of the page's purpose, its author, or any other information. Anything placed here will be accessible through the resulting servlet's getServletInfo method. errorPage="pathToErrorPage" errorPage = "customerror.jsp" This value customizes the page sent to the user when an error occurs at run time. isErrorPage="true|false" This value indicates that a JSP will be used as an error page. When this is true, the JSP will have access to an additional implicit value called exception, which will be Exception or Throwable representing the error that occured. The default for this value is false. contentType="mime-type" (Multipurpose Internet Mail Extensions) This value changes the content type of the page. In current implementations, It is equivalent to request.set("mime-type"). The default is text/html.(Multipurpose Internet mail extension) Implicit Objects available in JSP Out - output stream for page content Config - Servlet configuration data Request - Request data, including parameters Response - Response data Session - User specific session data Application - Data shared by all application pages. PageContext - Context data for page execution Exception - Uncaught error or exception Page - Page's servlet instance (Same as Server Object) Request Object Used to get information from the client browser Methods Enumeration getParameterNames() Returns the names of all request parameters String getParameter(name) Returns the first (or primary) value of a single request parameter Enumeration getParameterValues() Retrieves all of the values for a single request parameter getHeaderNames() Retrieves the names of all headers associated with request

getHeader(name) header, as a string getHeaders(name) request header getIntHeader(name) header,as an integer getDateHeader(name) header, as a date getCookies() with the request getMethod() method for the request. getRequestURI() including any string getQueryString() request URL, if any getSession()

Retrieves the value of a single request Returns all of the values for a single Returns the value of a single request Returns the value of a single request Retrieves all of the cookies associated Returns the HTTP(eg.GET , POST) Returns the request URL, up to but not Returns the query string that follows the

Retrieves the Session data for the request(ie., the session implicit object), optionally creating it if it does not already exists getRequestDispatcher(path) Creates the request dispatcher for the indicated local URL getRemoteHost() Returns the fully qulified name of the host that sent the request. getRemoteAddr() Returns the network address of the host that sent the request getRemoteUser() Returns the name of the user that sent the request, if known. getProtocol() Http/1.1 Eg1: <html> <body> Hello user! You are using a computer called <%= request.getRemoteHost() %>! </body> </html> Eg2: <html> <body>

Hello user! I am on a computer called <%= request.getServerName() %>, and you are using a computer called <%= request.getRemoteHost() %>! </body> </html> Eg3: <html> <head> <title> Request fields </title> </head> <body bgcolor="#ffffff"> <table border="1"> <tr> <td> You are using this authorization type: </td> <td><%= request.getAuthType() %> </td> </tr> <tr> <td> You are using this request method: </td> <td><%= request.getMethod() %> </td> </tr> <tr> <td> Characters are encoded using this scheme: </td> <td><%= request.getCharacterEncoding() %> </td> </tr> <tr> <td> The protocol used for this request was: </td> <td><%= request.getProtocol() %> </td> </tr> <tr> <td> The scheme used for this request was: </td> <td><%= request.getScheme() %> </td> </tr> Eg4: <%@ page language="java" %> <h1> Request Info </h1> <% out.print("<table>"); out.print("<tr><td> Protocol = <td>" + request.getProtocol()); out.print("<tr><td> ServerName = <td>" + request.getServerName()); out.print("<tr><td> ServerPort = <td>"+request.getServerPort());

out.print("<tr><td> Remote Address = <td>"+request.getRemoteAddr()); out.print("<tr><td> Method = <td>"+request.getMethod()); out.print("<tr><td> RequestURI = <td>"+request.getRequestURI()); out.print("<tr><td> QueryString = <td>"+request.getQueryString()); out.print("<tr><td> Session = <td>" + request.getSession()); out.print("<tr><td> RemoteHost = <td>" + request.getRemoteHost()); out.print("<tr><td> RemoteUser = <td>" + request.getRemoteUser()); out.print("</table>"); %> Eg5: <body> <form method=get action="form.jsp"><br> Name <input type=text name=Name><br> Last Name <input type=text name=Last><br> Mail Id <input type=text name=Email><br> Send <input type=submit> </form> </body> <%@ page language="java" import="java.util.Enumeration" %> <%! Enumeration e=null; %> <%! String Name=null; %> <%! String value=null; %> <% e=request.getParameterNames(); out.print("<table border=2>"); while(e.hasMoreElements()) { Name=(String)e.nextElement(); value=request.getParameter(Name); out.print("<tr><td>" + Name + "<td>" + value); } out.print("</table>"); %> Eg6: <html> <title> checkBox </title> <body> <form method="post" action="http://localhost:8080/check.jsp"> <b> Click the CheckBox below </b>

<input type=checkbox value=red name="rcolor" checked> Red <input type=checkbox value=blue name="rcolor" > Blue <input type=checkbox value=green name="rcolor" > Green <input type=submit value=enter> </form> </body> </html> <html> <title> Check box </title> <body> <b> The color you selected is </b> <% String names[]= request.getParameterValues("rcolor") ; for(int i=0;i<names.length;++i) { out.println(names[i]); %> } %> </body> </html> Eg7: <%@ page import="java.util.Date" %> <%! Date now = new Date(); %> <html> <head><title> Current Time </title></head> <body> <% now = new Date(); %> Hello! At the tone, the time will be exactly and <%= now.getHours() %>:<%= now.getMinutes() %> and <%= now.getSeconds() %> seconds. <p> <b> Beeep! </b> </body> </html> Eg8: <%@ page language="java" import="java.io.*" %> <%! FileReader fi=null; %> <%! public void jspInit() { try {

fi=new FileReader("d:/demo/jsp/JSPText1.txt"); }catch(FileNotFoundException fx) {} } %> <% int r; try { while((r=fi.read()) != -1) out.print((char)r); }catch(Exception ex){} %> demofile This is a sample demofile Eg9: <%@ page isErrorPage="true" %> <body> <%=exception.getMessage() %> </body> <%@ page errorPage="errorpage.jsp"%> <% if(true) { throw new Exception("A pure JSP Exception"); } %> Eg10: forward.html <body> <form method=get action="http:\\localhost:8080\forward.jsp"> <h1> Forward jsp </h1> send <input type=submit> </form> </body> forward.jsp <%@ page language="java" %> <jsp:forward page="inbox.jsp"/> inbox.jsp <%@ page language="java" %> <h1> JSP forward tag </h1> Response Object

Response Object represents the response that will be sentback to a user as a result of processing the JSP page. This object implements the javax.servlet.ServletResponse interface. Methods setContentType(string) - Sets the Content type("text/html") and character encoding (ISO) getCharacterEncoding() - Default character Encoding setContentLength(int) OutputStream getOutputStream() Writer getWriter() addCookie(cookie) setStatus(int sc) sendError(int sc) sendError(int sc,String sm) sendRedirect(String URL) Sc_constants SC_CONTINUE = 100 SC_OK = 200 SC_CREATED = 201 SC_ACCEPTED = 202 SC_NOT_FOUND = 404 SC_NOT_ACCEPTABLE = 406 SC_BAD_GATEWAY = 502 response.sendRedirect Method sample.html <form method=get action="sample.jsp"> Enter login name : <input type=text name=login><br> <input type=submit> </form> sample.jsp <%@ page language="java" %> <%! String l=null; %> <% l = request.getParameter("login"); if(l.equals("scott")) response.sendRedirect("inbox.jsp"); else

response.sendError(404); %> inbox.jsp <h1> inbox file </h1> Session Used to cache information about a specific browser instance. The server gives the browser a unique token(SessionID) in response to its first request so the browser can identify itself to the server for subsequent request. Methods String getId() long getCreationTime() long getLastAccessedTime() boolean isNew() putValue(String key,Object value) Object getValue(String key) removeValue(String key) session.jsp <%@ page language="java" import="java.util.Date" %> <h1> Session Info </h1> <% out.print("<table>"); out.print("<tr><td> Creation time <td>" + new Date(session.getCreationTime())); out.print("<tr><td> Last Accessed Time <td>" + new Date(session.getLastAccessedTime())); out.print("<tr><td> New <td>" + session.isNew()); out.print("</table>"); %> session2.jsp <%@ page language="java" %> <% String name=(String)session.getValue("BookName"); if(name==null) { session.putValue("BookName","Professional JSP"); response.sendRedirect("session3.jsp"); } else { out.println(name);

} %> session3.jsp <%@ page language="java" %> <% String s=(String)session.getValue("BookName"); out.print(s); %> JDBC Connectivity <%@ page language="java" import="java.sql.*" %> <%! Connection con=null; %> <%! Statement st = null; %> <%! String qry; %> <%! String uname,pword,rpword,dob,addr,email; %> <%! int age,phno; %> <% try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:mysql","sa","killer"); }catch(Exception e) { out.println(e); } %> <% String label; try { label = request.getParameter("cmd"); if(label.equals("Add")) { uname = request.getParameter("uname"); pword = request.getParameter("pword"); rpword = request.getParameter("rpword"); dob = request.getParameter("dob"); age = Integer.parseInt(request.getParameter("age"));

addr = request.getParameter("addr"); phno = Integer.parseInt(request.getParameter("phno")); email = request.getParameter("email"); st = con.createStatement(); qry = "Insert into register values('" + uname + "','" + pword + "','" + rpword + "','" + dob + "'," + age + ",'" + addr + "'," + phno + ",'" + email + "')"; int r = st.executeUpdate(qry); System.out.println(r + " row(s) Inserted"); } else if(label == null) { System.out.println("No Values"); } }catch(Exception e) { System.out.println(e); } %> <html> <head> <title> Register Form </title> <script> function AddRec() { document.reg.cmd.value = "Add" } </script> </head> <body bgcolor="lightyellow"> <h2 align=center> Registration Form </h2> <table align=center> <form method=post action="DBRegister.jsp" name="reg"> <tr> <td> Username <td> <input type=text name=uname> <tr> <td> Password <td> <input type=password name=pword> <tr>

<td> Retype Password <td> <input type=password name=rpword> <tr> <td> Date of Birth <td> <input type=text name="dob"> <tr> <td> Age <td> <input type=text name="age"> <tr> <td> Address <td> <textarea rows=5 cols=25 name="addr"> </textarea> <tr> <td> Phone No <td> <input type=text name="phno"> <tr> <td> Email <td> <input type=text name="email"> <tr> <td> <td> <input type=submit onClick="AddRec()"> <input type=reset> <input type=hidden name="cmd"> </form> </table> </body> </html> Javabeans Vs JSP 1. Security 2. Reusability of Source code <jsp:useBean id="id_name" class="classname"/> <jsp:setProperty name="id_name" property="property_name" param="paramname" value="value"/> <jsp:getProperty name="id_name" property="property_name"/> getNextInt() setNextInt() Scope Session Application Request Response Steps to Create Bean file and extract in JSP 1. Create a java file and compile it. 2. Copy the class file to c:\javawebserver2.0\classes 3. Create JSP file in public_html and run it. Eg: paintbrush.java

public class paintbrush { private String color; public paintbrush() { color="red"; } public void setColor(String col) { color=col; } public String getColor() { return color; } } paint.jsp <%@ page import="paintbrush" %> <pre> <h1> <jsp:useBean id="p1" class="paintbrush" scope="session"/> <form method=post action="paint.jsp"> Current color value : <jsp:getProperty name="p1" property="color" /></h1> <jsp:setProperty name="p1" property="color" value="blue"/> <input type=submit value=Repeat> </pre> </form> Cookies For Creating Cookie Cookie c = new Cookie("Cookie_name","Value") request String getName() - Get the name of the Cookie String getValue() - Get the value of the Cookie response response.addCookie(c); Cookie[] request.getCookies() - get the Cookies values. Eg: Login.html <html> <body> <h2 align=center> Login Form </h2> <table align=center>

<form method=post action="Cookie1.jsp"> <tr> <td> Username <td> <input type=text name="uname"> <tr> <td> Password <td> <input type=password name="pword"> <tr> <td> <td> <input type=submit> <input type=reset> </form> </table> </body> </html> Cookie1.jsp <%@ page language="java" %> <%! String uname,pword; %> <% uname = request.getParameter("uname"); pword = request.getParameter("pword"); out.println("<h2 align=center> Adding Cookies </h2>"); Cookie c1 = new Cookie("username",uname); Cookie c2 = new Cookie("password",pword); response.addCookie(c1); response.addCookie(c2); out.println("<a href=http://localhost:8080/Cookie2.jsp> Next </a>"); %> Cookie2.jsp <%@ page language="java" %> <%! String un,pw; %> <% Cookie c1[] = request.getCookies(); for(int i=0;i<c1.length;i++) { if(c1[i].getName().equals("username")) { un = c1[i].getValue(); } else if(c1[i].getName().equals("password")) { pw = c1[i].getValue();

} } out.println("<font face=Arial size=4 color=blue>"); out.println("Username : " + un + "<br>"); out.println("Password : " + pw + "<br>"); out.println("<a href=http://localhost:8080/Cookie3.jsp> Next </a>"); %> Cookie3.jsp <%@ page language="java" %> <%! String un,pw; %> <% Cookie c1[] = request.getCookies(); for(int i=0;i<c1.length;i++) { if(c1[i].getName().equals("username")) { un = c1[i].getValue(); } else if(c1[i].getName().equals("password")) { pw = c1[i].getValue(); } } out.println("<font face=Arial size=4 color=red>"); out.println("Username : " + un + "<br>"); out.println("Password : " + pw + "<br>"); %>

Enterprise Java Beans Sun Microsystems introduced the J2EE application server and the Enterprise JavaBean (EJB) specifications as a venture into the multitier server side component architecture market. It is important to note that though EJB and JavaBeans are both component models, they are not same. EJBs are interprocess components and JavaBeans are intraprocess components. EJB is a specification for creating server side components that enables and simplifies the task of creating distributed objects. The Key features of EJB are as follows EJB components are server side components written using Java EJB components implement the business logic only. We need not write code for system level services, such as managing transactions and security. EJB components provides services, such as transaction and security management and can be customized during deployment. EJB can maintain state information across various method calls. Enterprise JavaBeans Component Architecture
Client Home Interface EJB Home Stub Remote Interface EJB Object Stub EJB Server EJB Home

EJB Container

Home Interface EJB Object Remote Intf Bean Class

EJB Server which contains the EJB container. EJB container, which contains enterprise beans Enterprise bean, which contains methods that implement the business logic. EJB Server EJB Server provides some low level services, such as network connectivity to the container. It also provides the following services:

1. Instance Passivation If a container needs resource, it can decide to temporarily swap out a bean from the memory storage. 2. Instance Pooling If an instance of the requested bean exists in the memory, the bean is reassigned to another client. 3. Database Connection Pooling When an Enterprise bean wants the access a database, it does not create a new database connection of the database connection already exists in the pool. 4. Precached Instances The EJB server maintains a cache. This cache information about the state of the enterpirse bean. EJB Container The EJB container acts as an interface between and Enterprise bean and the clients. Clients communicate with the enterprise bean through the Remote and Home Interfaces provide by the container. The client communicating to the enterprise bean through the container enables the container to service the clients request with great flexibility. For Instance, the container manages a pool of enterprise beans and uses them as the need arises, instead of creating a new instance of the bean for each client request. The container also provides the following services: 1. Security 2. Transaction Management 3. Persistance -> Permanent Storage 4. Life Cycle Management Enterprise Bean Enterprise JavaBeans are write once, run anywhere, middle tier components that consists of methods that implements the business rule. The enterprise bean encapsulates the business logic. There are two types of enterprise bean. 1. Entity Bean 2. Session Bean Entity Bean Entity Beans are enterprise beans that persist across multiple sessions and multiple clients. There are two types of Entity bean: 1. Bean Managed Persistance 2. Container Managed Persistance

In a Bean managed persistance, the programmer has to write the code for database calls. On the other hand, in container managed persistance, the container takes care of database calls. Session Bean Session bean perform business tasks without having a persistent storage mechanism, such as a database and can use the shared data. There are two types of session beans: 1. Stateful Session Bean 2. Stateless Session Bean A Stateful session bean can store information in an instance variable to be used across various method calls. Some of the application require information to be stored across various method calls. A Stateless session bean do not have instance variables to store information. Hence, stateless session beans can be used in situations where information need not to be used across method calls. J2EE application Components Enterprise Bean (.jar files) Web Component (.war files) | | ------------------------------------------------------| J2EE Application(.ear Files) | Deployed J2EE Server Jar -> Java Archive War -> Web Archieve Ear -> Enterprise Archieve Session Bean Stateless Bean Home Interface Remote Interface Bean Class Server Class Client Application s.bat path=%path%;d:\jdk1.2\bin;d:\j2sdkee1.2\bin set classpath=d:\j2sdkee1.2\lib\j2ee.jar;d:\demo\ejb; set java_home=d:\jdk1.2 set j2ee_home=d:\j2sdkee1.2

Eg: Calculator.java //Remote Interface import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Calculator extends EJBObject { public double dollarToRs(double dollars) throws RemoteException; } CalculatorHome.java // Home Interface import java.io.Serializable; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome; public interface CalculatorHome extends EJBHome { Calculator create() throws RemoteException, CreateException; } CalculatorEJB.java //Enterprise Bean class import java.rmi.RemoteException; import javax.ejb.SessionBean; import javax.ejb.SessionContext; public class CalculatorEJB implements SessionBean { public double dollarToRs(double dollars) { return dollars * 47.20; } public CalculatorEJB() {} public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {}

} Deploying an Enterprise JavaBean CalculatorClient.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; public class CalculatorClient extends JFrame { public static int w = 500; public static int h = 95; public static String str = "Earnest Bank Welcomes You"; Container c; JLabel l,result; JTextField t; JButton b; public static String value; public static double dbl; public static double amt; public CalculatorClient() { super(str); c = getContentPane(); c.setLayout(new GridLayout(2,2,2,2)); l = new JLabel("Enter the amount in Dollars($)"); c.add(l); t = new JTextField(10); c.add(t); b = new JButton("Calculator"); c.add(b); result = new JLabel(); c.add(result); value = t.getText(); b.addActionListener(new addEvent()); setSize(w,h);

show(); } public class addEvent implements ActionListener { public void actionPerformed(ActionEvent e) { value = t.getText(); dbl = Double.parseDouble(value); try { Context ic = new InitialContext(); Object obj = ic.lookup("CalculatorJNDI"); CalculatorHome home = (CalculatorHome) PortableRemoteObject.narrow(obj,CalculatorHome.class); Calculator calc = home.create(); amt = calc.dollarToRs(dbl); result.setText("Result(Rs.): " + String.valueOf(amt)); }catch(Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); } } } public static void main(String args[]) { CalculatorClient m = new CalculatorClient(); } } Stateful Session Bean The bean instance needs to be initialized when it is needed The client application is an interactive one The client is likely to invoke Does not multiple method calls existsclient specific information across method The bean needs to store remove() Create() calls. ejbRemove() newInstance() Life Cycle of a Stateful session bean ejbPassivate()
setSessionContext() ejbCreate() Ready ejbActivate() Passive

Eg: Problem Statement Earnest Banks Chief Technology Officer (CTO) has entrusted the development team with the task of creating an application to validate the credit card information entered by the user. The team is responsible for justifying the choice of stateful session bean as the bean type and writing code for the required application Eg: Card.java import java.util.*; import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Card extends EJBObject { public int validate(String CardNo) throws RemoteException; } CardHome.java import java.io.Serializable; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome; public interface CardHome extends EJBHome { Card create(String person,String CardNo) throws RemoteException,CreateException; } CardEJB.java import javax.ejb.*; import java.rmi.RemoteException; public class CardEJB implements SessionBean

{ String CustomerName; String CardNo; public void ejbCreate(String person,String cardNo) throws CreateException { if(person.equals("") || cardNo.equals("")) { throw new CreateException("Null person or card Number not allowed"); } CustomerName = person; CardNo = cardNo; } public int validate(String cardNo) throws RemoteException { int len = CalcLen(cardNo); if (len > 16) return 0; else return 1; } public int CalcLen(String cardNo) throws RemoteException { return cardNo.length(); } public CardEJB() {} public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void setSessionContext(SessionContext ctx) {} } CardClient.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.naming.Context;

import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; public class CardClient extends JFrame { public static int w = 690; public static int h =95; public static String str = "Earnest Shopping Center Welcomes You"; Container c; JLabel lname,lcard,result; JTextField tname,tcard; JButton b; public int res; public static String uname; public static String ccno; public CardClient() { super(str); c = getContentPane(); c.setLayout(new GridLayout(3,2,2,2)); lname = new JLabel("Name:"); c.add(lname); tname = new JTextField(20); c.add(tname); lcard = new JLabel("Card Number"); c.add(lcard); tcard = new JTextField(16); c.add(tcard); b = new JButton("Submit"); c.add(b); result = new JLabel(); c.add(result); b.addActionListener(new addEvent()); setSize(w,h); show(); } public class addEvent implements ActionListener { public void actionPerformed(ActionEvent avt)

{ uname = tname.getText(); ccno = tcard.getText(); System.out.println(uname); System.out.println(ccno); try { Context initial = new InitialContext(); Object objref = initial.lookup("Cardjndi"); CardHome home = (CardHome)PortableRemoteObject.narrow(objref,CardHome.class); Card Creditcard = home.create(uname,ccno); res = Creditcard.validate(ccno); System.out.println(res); if(res == 0) { result.setText("The Card Number " + ccno + " is valid"); } else { result.setText("Sorry! The card Number " + ccno + " is invalid"); } }catch(Exception ex) { System.out.println("Exception Raised : " + ex); result.setText("Check if you have entered your name and also card number!"); } } } public static void main(String args[]) { CardClient c; c = new CardClient(); } }

Entity Bean Session Bean It is used to carry out tasks based on request from clients Entity Bean It is used to represent a business entity object in a data store It can be accessed by multiple clients It can model persistent data

It can be accessed by just a single client It cannot model persistent Data Problem Statement Earnest Banks Chief Technology Officer (CTO) has entrusted the development team with the task of creating an application that will enable the bank staff store the details of ATM transactions carried out by an account holder, in the central SQL Server 2000 database. The staff should be able to store transaction details such as account id, transaction date, transaction particulars, check number and amount withdrawn or deposited. Database Registration cRegistrationID int cFirst_Name char(50) cLast_Name char(50) cAddress char(50) cAccount_tyoe char(30) mAnnual_Income money(8) cPhone_No char(10) Account_Holder cAccount_id char(10) cRegistrationID int mBalance money(8) Account_Holder_Transaction cAccount_id char(10) dDate_of_Trans datetime vcParticulars varchar(50) cCheck_No char(10) mAmount money

Potrebbero piacerti anche