Programming on Java - Notes

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

description

- Programs - Core java- Programs - Advanced JavaFor Beginners - this will be helpful to improve your programming skills

Transcript of Programming on Java - Notes

Page 1: Programming on Java -  Notes

. E-CommerceElectronic Commerce -> Business thru Internet

Three Types1. Business to Business (B2B) (Intel Corporation - HCL)2. Business to Customer (B2C) (Chennaisilks.com)3. Customer to Customer. (C2C) (Bazee.com)

Web TechnologyDesigning-> SGML, HTML, DHTML, Frontpage, Dreamweaver,

Photoshop (Static Pages)Client side scripting -> Javascript, VBScript, JScript Server Side scripting -> Servlets, ASP, JSPStorage -> Oracle, SQL - Server, AccessCommunication -> RMI,CORBA,DCOM, XML (Distributed

Applications - Banking, Financial, Telecom)

Java Components and Related SoftwaresJava & RMI(Remote Method Invocation) -> jdk1.2 (Java

Development Kit)CORBA - Common Object Request Broker Architecture - jdk1.3Java Servlets -> JSDK2.0 (Java Servlet Development Kit)JSP(Java Server Pages) - Java Web Server 2.0, Tomcat, Apache

ServerJava Bean - bdk2.0 (Bean Development Kit)EJB (Enterprise Java Beans)- Weblogic or Websphere or J2EE

ServerJ2EE Server -> All the above components are integrated.

ArchitecturePresentation layer -> Input and Output formsBusiness logic -> ValidationsData layer -> Storing Data

Four types of Architecture1. Single Tier -> Foxpro, Clipper

Single User application2. Two Tier (or) Client/Server Technology-> VB and Oracle

VB and SQL - ServerPower Builder - SQLServer

VB -> Presentation and Business Logic (Client)Oracle -> Data layer (Server)Multi User application

Page 2: Programming on Java -  Notes

3. Three Tier -> HTML, ASP, Oracle (B2C, C2C)B2B Communication is not possible

Intel Corporation HCLJava XML VB4. Multi Tier (or) MVC Architecture (Model View Controller)

HTMLJavascript

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)

OracleXML -> CommunicationJSP Servlets EJB

MVC - Model View Controller Architecture (JSP, Servlets, EJB)

Java ProgrammingJava 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 JVMDisadvantage

Execution speed is slow because of using bytecode and JVMJava Programming TypesApplication -> Console Based application (Worked in Command

Page 3: Programming on Java -  Notes

Prompt)Datatypes, Operators, Identifiers, Character setControl StatementsArrays and StringsClass ConceptsInheritanceInterface and packageException HandlingStreams

ThreadNetworking

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

MenuFrame PanelLayoutsDialogs

JFC/Swing --> Java Foundation Class (Light Weight Components -> ie, the components are developed by using JavaJava Program DevelopmentJava development kit - jdkd:\>set path=%path%;d:\jdk1.3\bin;+d:\>pathd:\>notepad first.javasample programclass first {

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

}}d:\demo\DemoJava> javac first.javad:\demo\DemoJava> java firstNote:Java program must be within a class java class name and the filename may be same

Page 4: Programming on Java -  Notes

Description of Java programpublic - access specifier of the method mainstatic - without creating object for class we can access the main method defined in the class using class namevoid - return type of main methodmain - method nameString args[] - for passing arguments to main method. The argument type is String class.System - Package (Set of Predefined Classes)out - Class of Systemstatic method - println - Method of out

System.out.println("Welcome to Java Programming");System.out.print("Hello World");

Datatypesprimitive datatypescharfloat longdoubleintbooleanIntegerType Size Rangebyte 1 byte -128 to +127short2 bytes -32,768 to +32,767int 4 bytes -2,147,483,648 to +2,147,483,647long 8 bytes -9223372036854775808 to +9223372036854775807characterchar 2 bytes unicode characters.booleanboolean 1 byte true or falsefloatfloat 4 bytes - 3.4e38 to + 3.4e38double 8 bytes -1.7e308 to +1.7e308variableswhich holds some valuesThree kinds of variables1. Instance variable

Page 5: Programming on Java -  Notes

2. Local variable3. 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 classDeclaring variablesdatatype var_name;Naming Conventionsvar_name must be starting with characterspecial symbols are not allowedwhite spaces are not allowedonly underscore allowed.

int a;int emp_no;int emp no; //errorint e1;int 1e; //errorchar s$; //error

eg:int a;short b;float f;char c; (Variables)String str; (Instance (or) Object)

Eg://Non-static methodclass VarDecl{ void pr(String s) { System.out.println(s); } public static void main(String args[]) { short a = 10;

Page 6: Programming on Java -  Notes

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

OperatorsArithmetic + - * / %Relational >, <, >=, <=, ==, !=

Page 7: Programming on Java -  Notes

Logical &&, ||, !Increment and ++Decrement --Conditional ?:Assignment =Bitwise &, |, ^, <<, >>Arithmetic Assignment +=, -=, *=, /=, %=Programming Constructs

types1. Conditional Conditionalif statementsswitch casewhile loopdo whilefor

breakcontinueif statementif (condition){ statements; }if..elseif (condition){ true statements; }else { false statements }

if..else ifif (condition){

true statements} else if(condition){

true statements}else{

false statements;}nested if

Page 8: Programming on Java -  Notes

if (condition) {if (condition) {

true statements} else{

false statements}

}else{

false statements}Loopingwhile loopwhile (condition){

statements}do whiledo{

statements}while(condition);for loopfor(initialization;condition; inc or dec){

statements}switch caseswitch(expression){

case 1:statements;break;

case n:statements;break;

default:statements;

}

Page 9: Programming on Java -  Notes

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

Object Oriented Programming System Five Characteristics1. Classes and Objects2. Overloading3. Inheritance4. Polymorphism5. Data Abstraction and Data Encapsulation.Classes and ObjectsClass -> Collection of member variables and member functions.

Page 10: Programming on Java -  Notes

Object (or) Instance -> To access the class member variable and functions.

Syntax:class class_name{

access_specifier datatype var_nameaccess_specifier return_type function_name(arguments);

}classname ins_name = new class_name;new -> Memory allocation for instance.ins.memberfunction();Access Specifierprivate -> With in a classpublic -> Class, Subclass and main function(thru object)protected -> Class and Subclassno modifier -> similar to public ( Differed in package concept).Note: By default, the variables and functions are no modifier.

1. Defining class and objectclass 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();

Page 11: Programming on Java -  Notes

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

Page 12: Programming on Java -  Notes

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

Page 13: Programming on Java -  Notes

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

Page 14: Programming on Java -  Notes

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;

Page 15: Programming on Java -  Notes

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:

Page 16: Programming on Java -  Notes

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 keywordrefers current object.

Page 17: Programming on Java -  Notes

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

Page 18: Programming on Java -  Notes

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

Page 19: Programming on Java -  Notes

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

Page 20: Programming on Java -  Notes

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

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

Page 21: Programming on Java -  Notes

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

Page 22: Programming on Java -  Notes

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 Typestwo types1. single dimension2. multi dimensionsingle dimensionSyntax:

datatype var[] = new datatype[size];Eg:int a[] = new int[10];Initializationint a[5] = {1,2,3,4,5};a[0] = 1a[1] = 2a[2] = 3a[3] = 4a[4] = 5char c[] = new char[10]; //character Array

Page 23: Programming on Java -  Notes

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

Page 24: Programming on Java -  Notes

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

Page 25: Programming on Java -  Notes

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 inheritance1. Single2. Multiple -> Java Does'nt support 3. Multilevel 4. Heirarchical5. Hybrid -> Doesn't SupportSingle

Base |Derived

MultipleBase1 Base2 | | ---------------------------

|

Page 26: Programming on Java -  Notes

Derived1Multilevel

Base1 |Derived1

|Derived2

Base1 -> Base classDerived1 -> Base1 -> BaseClassDerived2 -> Derived1 -> Immediate ClassDerived2 -> Base1 -> Indirect Base ClassHeirarchical

Base |

----------------------------------------- | |Derived1 Derived2 | |

-------------------------------- -------------------------------------| | | |Derived11 Derived12 Derived21Derived22Hybrid

Combination of Multiple and MultilevelBase |Derived1 Base2

| | | | ---------------------------

|Derived2

Single InheritanceBase |Derived

Syntax:class base{

statements;

Page 27: Programming on Java -  Notes

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

Page 28: Programming on Java -  Notes

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

Page 29: Programming on Java -  Notes

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 classDerived2 -> Derived1 -> Direct Base classDerived2 -> 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;

Page 30: Programming on Java -  Notes

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

Page 31: Programming on Java -  Notes

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)

Page 32: Programming on Java -  Notes

{ 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.Syntaxaccess 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 interfaceaccess class class_name[extends superclass]

[implements interface[interface...]] {//class body

}Eg:Callback.javainterface Callback{

Page 33: Programming on Java -  Notes

public void call(int param);

}Client.javaclass 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.javaclass 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:

Page 34: Programming on Java -  Notes

IntStack.javainterface IntStack { void push(int item); int pop();}FixedStack.javaclass 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");

Page 35: Programming on Java -  Notes

for(int i=0;i<9;i++) System.out.println(mystack2.pop()); }}

PackagesCollection of Classes placed in a folder.Predefined Packagesimport java.io.*import java.util.Dateimport java.util.Vectorimport 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 ModiferSame packageSame Class Yes Yes Yes Yes

Same PackageSub Class No Yes Yes Yes

Same PackageNon Subclass No Yes No Yes

Different PackageSubclass No Yes Yes No

Different PackageNon Subclass No Yes No No

Protection.java

Page 36: Programming on Java -  Notes

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.javaDerived.javapackage 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.javaSamePackage.javapackage 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);

Page 37: Programming on Java -  Notes

}}javac -d . SamePackage.javaDemo.javaimport 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.javaProtection2.javapackage 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.javaOtherPackage.javapackage 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); }}

Page 38: Programming on Java -  Notes

javac -d . OtherPackage.javaDemo1.javaimport p2.Protection2;import p2.OtherPackage;class Demo1{ public static void main(String args[]) { Protection2 ob1 = new Protection2(); OtherPackage ob2 = new OtherPackage(); }}javac Demo1.javaAdvantages1. Class Files are placed in a single directory2. The packages are used in anywhere.

String ClassCollection of characters

String constructorsdefault constructor1. 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); cdeHash 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

'+' - ConcatenationtoString() - convert into String+= Operator will also work for strings.Str1+=Str2; (str1=str1+str2)

Page 39: Programming on Java -  Notes

String Class Methodslength() - number of characters in String.String s1="hello"int len=s1.length();len=5charAt(int) - The character at a location in the StringString s1="hello world"char a = s1.charAt(2)a=lgetChars() , 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 stringtoByteArray() - Produces a byte[] containing the characters in the string.equals() , equalsIgnoreCase() - An equality check on the contents of the two stringsstr1="hello"str2="Hello"str1.equals(str2) = falsestr1.equalsIgnoreCase(str2) = trueCompareTo() - 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 valuestr1 < str2 = -ve valuestr1 == str2 = 0startsWith() - Boolean result indicates if the string starts with the argumentString s1="hello"s1.startsWith("h");=trues1.startsWith("H"); = falseendsWith() - Boolean result indicates if the string ends with the argumentString s1="Hello";s1.endsWith("o"); - Trues1.endsWith("h");- false

Page 40: Programming on Java -  Notes

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') = 3s1.indexOf('s',5)=6s1.lastIndexOf('s') = 10s1.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 argumentString 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') = hewwotoLowerCase(),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 ") -> helloEg:class Arith { String fname="Aswath"; String lname="Narayanan";

Page 41: Programming on Java -  Notes

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

Page 42: Programming on Java -  Notes

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

Page 43: Programming on Java -  Notes

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 MethodstoString() - Creates a string from this stringbuffer or convert to

stringlength() - returns the number of character in the stringbuffercapacity() - 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 buffersetCharAt(int,char) - modifies the value of that location.StringBuffer sb = "Hello";sb.setCharAt(2,'w'); Hewlo;

Page 44: Programming on Java -  Notes

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 HandlingAn 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 ErrorsCompilation time errorsRuntime ErrorsCompile 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

Page 45: Programming on Java -  Notes

* Bad references to objects* and so onRuntime 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 stringException

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 ExceptionsArithmeticException - caused by math erros that is divide by zeroArrayIndexOutOfBoundsException - 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 objectNumberFormatException - Caused when a conversion between strings and number fails.OutOfMemoryException - caused when ther's not enough memory to allocate a new objectSecurityException - caused when an applet tries to perform an action not allowed by the browsers security settingStringIndexOutOfBoundsException - caused when a program attempts to access nonexistent character position in a stringNegativeArraySize Exception - declare the array size as negativeSyntax:try {

statement;//generates an exception

Page 46: Programming on Java -  Notes

} catch(Exception-type e){statement;

} finally{

statements;}Multiple Catch statementsSyntax: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 programthrow - throw a generated exception to anywhere of the program.Eg:class Exp1{ public static void main(String args[]) {

Page 47: Programming on Java -  Notes

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

Page 48: Programming on Java -  Notes

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

Page 49: Programming on Java -  Notes

} public static void main(String args[]) { UserDefException e = new UserDefException(); e.getInt(); }}Eg:cc

MultitaskingMultithreading - A single Program can perform multiple taskThread

A thread is a smallest unit of dispatchable code.Time slicing method

First Process - 5seconds Second process - 5 secondsThird Process - 5seconds

Queue - The Process are stored in a queue. (First in First Out)Thread Priorities

Min Priority - 1Norm Priority - 5Max Priority - 10

Creating a ThreadTwo ways1. Using Runnable Interface2. Extending Thread Class

States of ThreadFour states associated with a thread namelynewrunnabledeadblocked

Thread obj; //new born stateobj.start(); run(); //runnable statesleep(1000) //blockedwait(); //blockednotify()suspend(); //blockedresume();

Page 50: Programming on Java -  Notes

stop(); //deadnew:

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

Page 51: Programming on Java -  Notes

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 alivegetName() Gets and return this Thread's namegetPriority() Gets and returns the Thread's prioritysetName(String) Sets the Thread's NamesetPriority(int) sets the Thread's prioritytoString() Returns a string representation of the Thread, including the threads name,priority and thread groupRunnable interface

void run() Thread(Runnable threadob, String ThreadName)

Methods in ThreadisAlive() - 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

Page 52: Programming on Java -  Notes

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

Page 53: Programming on Java -  Notes

} 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 - 10MIN_PRIORITY - 1NORM_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"); }

Page 54: Programming on Java -  Notes

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

Page 55: Programming on Java -  Notes

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

Page 56: Programming on Java -  Notes

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

Page 57: Programming on Java -  Notes

} 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 HandlingThe 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. keyboard2. mouse3. disk4. network5. memory

Page 58: Programming on Java -  Notes

output goto1. screen2. printer3. disk4. memory5. networkStreamswe 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 streamsinput streamoutput streamStream classestwo types of stream classes1. byte stream classes2. character stream classesTypes of byte stream classes1. InputStream classes2. OutputStream classesInput stream classes1. FileInputStream2. SequenceInputStream3. PipeInputStream4. ByteArrayInputStream5. ObjectInputStream6. StringBufferInputStream7. FilterInputStream 1. BufferedInputStream

2. PushbackInputStream3. DataInputStream Class4. DataInput Interface

InputStream functions* Reading bytes* Closing Streams* Marking position in streams* Skipping ahead in a stream* Finding the number of bytes in a streamInputStream Methodsread() - Reads a byte from the input streamread(byte b[]) - read an array of bytes into b

Page 59: Programming on Java -  Notes

read(byte b[],int n,int m) - reads m bytes into b starting from the nth byteavailable() - give no.of bytes available in the inputskip(n) - skips over n bytes from the input streamreset() - goes back to the beginning of the streamclose() - close the input streamDataInput Interface methodsreadShort()readInt()readLong()readFloat()readDouble()readLine()readChar()readBoolean()OutputStream Classes1. FileOutputStream2. ObjectOutputStream3. PipedOutputStream4. ByteArrayOutputStream5. FilterOutputStream

1. BufferedOutputStream2. PushbackOutputStream3. DataOutputStream Class4. DataOutput Interface

OutputStream functions* Writing bytes* Closing streams* Flushing StreamsOutputStream Methodswrite() - Writes a byte to the output streamwrite(byte[] b) - Writes all bytes in the array b to the output streamwrite(byte b[],int n,int m) - Write m bytes from array b starting from the nth byteclose() - Close the outputstreamflush() - Flushed the outputstreamDataOutput Interface MethodswriteShort()writeInt()

Page 60: Programming on Java -  Notes

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://FileInputStreamDemoimport java.io.*;class FileInputStreamDemo{

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

FileInputStream f = new FileInputStream("sample.txt");int size = f.available();

Page 61: Programming on Java -  Notes

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

Page 62: Programming on Java -  Notes

System.out.println("File2 Written");FileOutputStream f3 = new FileOutputStream("file3.txt");f3.write(buf,0,10);System.out.println("File3 Written");

}}Eg: //Demonstrate ByteArrayOutputStreamimport 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";

Page 63: Programming on Java -  Notes

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;

Page 64: Programming on Java -  Notes

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

Page 65: Programming on Java -  Notes

} } }Character Stream classesTwo typesreader stream classeswriter stream classesReaderStream Classes1. BufferedReader2. StringReader3. CharArrayReader4. PipeReader5. InputStreamReader

1. FileReader6. FilterReader

1. PushbackReaderWriterStream classesBufferedWriterPrintWriterCharArrayWriterStringWriterFilterWriterPipeWriterOutputStreamWriter

1. FileWriterInput / Output ExceptionsEOFException - Signals that an end of file or end of stream has been reached unexpectedly during the inputFileNotFoundException - informs that a file could not be foundInterruptedIOException - Warns an I/O Operations has been interruptedIOException - Signals that an I/O Exception of some sort has occuredEg: //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);

Page 66: Programming on Java -  Notes

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

Page 67: Programming on Java -  Notes

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

Page 68: Programming on Java -  Notes

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

Page 69: Programming on Java -  Notes

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; } } } }NetworksConnection between Different peripheralsNetworks enables sharing of resources and communications. Internet is a network of networks. Networking in java is possible through the use of

Page 70: Programming on Java -  Notes

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 areHTTP - 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 ProtocolNNTP - 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 XMLSockets

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 maskSpecific ports are assigned to some protocols by TCP/IP.Client or HTTP : 8080Server : 9090FTP :21Telnet : 25Client/ServerA 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.0InetAddress Class

Page 71: Programming on Java -  Notes

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.Methodsstatic InetAddress getLocalHost() - Returns InetAddress object representing local hoststatic 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

Page 72: Programming on Java -  Notes

Datagram is a type of socket that represents an entire communication.There are two classes in java which enables communication with datagrams1. DatagramPacket - acts as a data container. contains data,sizeof data, destination ip address2. DatagramSocket - is a mechanism used to receive and send DatagramPacketsDatagramPacketConstructorsDatagramPacket(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.ConstructorsDatagramSocket s=new DatagramSocket();DatagramSocket s=new DatagramSocket(int port)Methodssend(DatagramPacket d) - Dispatches the given DatagramPacket objectreceive(DatagramPacket p) - Receives the DatagramPacket objectclose() - closes the socket connection

The send and receive methods of the DatagramSocket class throws an IOException.Drawback1. 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");

Page 73: Programming on Java -  Notes

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

Page 74: Programming on Java -  Notes

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

Socket class(Client)

ConstructorSocket s=new Socket(String hostname,int port)Socket s=new socket(InetAddress a,int port)MethodsInetAddress getInetAddress() - Returns InetAddress associated with the socket object.int getPort() - Returns remote port to which this socket object is connectedint getLocalPort() - Returns the local port to which the Socket object is connectedInputStream getInputStream() - Returns the InputStream associated with this socketOutputStream 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.ConstructorsServerSocket ss=new ServerSocket(int port);ServerSocket ss= new ServerSocket(int port[],int maxqueue);Eg:import java.io.*;

Receive Data Send Data

Server / Socket Client /Socket

Listen

Accept

Send Data

Connect

Receive Data

Page 75: Programming on Java -  Notes

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

Page 76: Programming on Java -  Notes

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 Applet1. Java appln are simple stand Java applets are run insidealone 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

Page 77: Programming on Java -  Notes

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 Methodsinit()start()paint(Graphics g)repaint() -> update() -> paint()stop()destroy()Passing Parameter to AppletTag - <PARAM> Two Attributes

NAME - Name of the parameterVALUE - Value of the parameter

public void init() - graphics method getParameter(NAME) - This method takes one argument the string representing the value of the parameterEg: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";

Page 78: Programming on Java -  Notes

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 activitiesinit () - gets called as soon as the applet startedstart() - This method is executed after the init() paint() - draws the object in the appletstop() - 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 appletrepaint() - 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"); }

Page 79: Programming on Java -  Notes

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' - Characters100,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 drawnoffset-> the start offset in the datalength-> the no.of bytes that are drawnx-> x co-ordinatey-> y co-ordinatevoid 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);

Page 80: Programming on Java -  Notes

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 pointwidth - width of the rectangleheight - 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 pointwidth - width of the rectangleheight - height of the rectanglewidth1 - width1 of the angle corners

height1 - height1 of the angle cornersdrawPolygon(int xs[],int ys[],int pts)fillPolygon(int xs[],int ys[],int pts)

xs - an array of integers representing x co_ordinatesys - an array of integers representing y co_ordinatespts- 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 ovalwidth,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.*;

Page 81: Programming on Java -  Notes

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,ITALICConstants Descriptionstatic int BOLD Font.BOLDstatic int PLAIN Font.PLAINstatic int ITALIC Font.ITALIC

Constructor DescriptionFont(String name,int style,int size) Creates a new font from the specified name,style and sizeMethods Description

Page 82: Programming on Java -  Notes

abstract void setFont(f) set this graphics contexts font to the specified font

String getStyle() returns a string value that indicating the current font style

int getSize() returns an integer value that indicating the current font size

String getFamily() Returns the font family name as a string

boolean isPlain() Returns true if the font is plainboolean isBold() Returns true if the font is boldboolean isItalic() Returns true if the font is italicEg: 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();

Page 83: Programming on Java -  Notes

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 Descriptionabstract font getFont() This will return a Font object

representing the current fontpublic int getAscent() returns a value representing the ascent of a font in pointspublic int getDescent() returns a value representing the

descent of a font in pointspublic int getLeading() returns a value representing the

leading of a font in pointspublic int getHeight() returns a value representing the height of a font in pointspublic fontMetrics getFontMetrics() returns current font metricsEg: 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);

Page 84: Programming on Java -  Notes

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 whiteColor c1 = new Color(100,150,250);Color Name RGB valueColor.gray 128,128,128Color.green 0,255,0Color.yellow 255,255,0Color.pink 255,175,175Color.red 255,0,0Color.blue 0,0,255Color.magenta 255,0,255Color.cyan 0,255,255setColor() - set color to an objectsetBackground() - sets background color of an appletsetForeground() - 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;

Page 85: Programming on Java -  Notes

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 imageimg = 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 filegetDocumentBase() - Which returns the URL of the .HTML file. http://www.rediff.com

file://c:/mydocument/getWidth() - return the width of the applet browsergetHeight() - return the height of the applet browserEg: import java.awt.*; import java.applet.*;

Page 86: Programming on Java -  Notes

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 moveMouse ClickMouse Dragkey typekey presseskey released

Page 87: Programming on Java -  Notes

EventAn event is an object that describes a state change in a source

Event SourcesA 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 listenerssyntax:public void addTypeListener(TypeEvent el) (interface)Type - Name of the eventel - reference to the event listenerFor Eg:Button b;b.addActionListener(this);void actionPerformed(ActionEvent e) {

statements;}java.awt.event packageEvent Class DescriptionActionEvent Generated when a button is pressed, a list item is

double clicked, or a menu item is selectedAdjustmentEvent Generated when a scroll bar is manipulated.Component Event Generated when a component is hidden,

moved,resized or becomes visibleContainer Event Generated when a component is added or

removed from a container focus Event Generated when a component gains or loses

keyboard focusItemEvent 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 keyboardMouseEvent 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

Page 88: Programming on Java -  Notes

The ActionListener InterfaceThis interface defines the actionPerformed() method that is

invoked when an action event occurs. void actionPerformed(ActionEvent ae)

The AdjustmentListener interfaceThis interface defines the adjustmentValueChanged() method that

is invoked when an adjustment event occurs.void adjustmentValueChanged(AdjustmentEvent ae)

The ComponentListener InterfaceThis 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 InterfaceThis 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 InterfaceComponents got or lost focus.void focusGained(FocusEvent fe)void focusLost(focusEvent fe)

The ItemListener InterfaceThis 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 Interfacemouse click,press,release,enter,exitvoid mouseClicked(MouseEvent me)void mouseEntered(MouseEvent me)void mouseExited(MouseEvent me)void mousePressed(MouseEvent me)void mouseReleased(MouseEvent me)

Page 89: Programming on Java -  Notes

The MouseMotionListener Interfacemouse drag,movevoid mouseDragged(MouseEvent me)void mouseMoved(MouseEvent me)

The TextListener interfaceText field,TextAreavoid textChanged(TextEvent te)

The WindowListener Interfaceopen,close,activate,deactivate,iconified,deiconifiedvoid 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();

Page 90: Programming on Java -  Notes

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

Page 91: Programming on Java -  Notes

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_F12VK_A - VK_ZVK_0 - VK_9VK_ENTERVK_ESCAPEVK_DOWNVK_PAGE_UPVK_LEFTVK_SHIFTVK_CANCELVK_RIGHTVK_UPVK_PAGE_DOWNVK_CONTROLVK_ALT

Page 92: Programming on Java -  Notes

VK_BACKDemonstration of Virtual keycodesimport 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(); }

Page 93: Programming on Java -  Notes

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

ComponentAdapterComponentListener

ContainerAdapterContainerListener

FocusAdapterFocusListener

KeyAdapterKeyListener

MouseAdapterMouseListener

MouseMotionAdapterMouseMotionListener

WindowAdapterWindowListenerEg:AdapterDemo1.javaimport java.awt.*;import java.awt.event.*;import java.applet.*;public class AdapterDemo1 extends Applet {

int x,y;String msg = new String();public void init(){

Page 94: Programming on Java -  Notes

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

Page 95: Programming on Java -  Notes

User Interface ComponentsObject

ComponentLabelButtonCheckBoxTextComponent

TextAreaTextField

ChoiceListScrollBar

Common MethodssetSize(int width,int height) - Resizes the correxponding component so that it has width and heightsetFont(font f) - Sets the font of the corresponding componentsetEnabled(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 bsetForeground(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 objectFont getFont() - gets the font of the corresponding componentColor getForeground() - gets the foreground color of the

corresponding componentSize getSize() - Returns the size of the corresponding component in the form of a Dimension object.

Page 96: Programming on Java -  Notes

ButtonConstructor DescriptionButton() Constructs a button with no labelButton(String label) Constructs a button with label specified.MethodsMethod DescriptionaddActionListener(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 buttonsetLabel(String label) sets the label of the button to the value specifiedgetSource() Returns the object name of the command buttoneg: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."; }

Page 97: Programming on Java -  Notes

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>CheckBoxConstructor DescriptionCheckbox() creates a checkbox with no label.Checkbox(String label) Creates a checkbox with specified labelCheckbox(String label,boolean state) Creates a checbox with the specified label and sets the stateCheckbox(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 interchangedMethod DescriptionCheckboxGroup getCheckboxGroup() Determines the group of the corresponding CheckboxgetLabel() Gets the name of the corresponding checkboxgetSelectedObjects() 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' stategetItem() returns the item objectsetCheckboxGroup(CheckboxGroup g) sets the corresponding checkbox group to the specified onesetLabel(String label) Set the label of the corresponding checkbox to the value specifiedsetState(boolean state) sets the state of the corresponding checkbox to the value specifiedCheckboxDemo.java

Page 98: Programming on Java -  Notes

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.javaimport java.awt.*;

Page 99: Programming on Java -  Notes

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>

ChoiceConstructor DescriptionChoice() Creates a new Choice itemChoice c = new Choice();Method Descriptionadd(String item) Adds an item to the corresponding choice menu

Page 100: Programming on Java -  Notes

addItem(String item) Adds an item to the corresponding choicegetItem(int index) Gets the string at the specified index of the corresponding choice menugetItemCount() Returns the number of items in the corresponding choice menugetSelectedIndex() Returns the index of the currently selected itemgetSelectedItem() Gets a representation of the current choice as a stringinsert(String item, int index) Inserts the item into the corresponding choice at the specified

positionremove(int position) Removes an item into the corresponding choice menu at the

specified positionremove(String item) Removes the first occurence of item from

the corresponding choice menuremoveAll() Removes all item from the corresponding choice menuselect(int pos) Sets the selected item in the corresponding

choice menu to be the item at the specified positionselect(String str) Sets the selected item in the coresponding Choice menu to be the item whose name is equal to the specified stringeg: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");

Page 101: Programming on Java -  Notes

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

Page 102: Programming on Java -  Notes

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

Page 103: Programming on Java -  Notes

} else if(ae.getSource() == ra) { names.removeAll(); cnt.setText("Count : " +names.getItemCount()); } }}//<applet code="ChoiceDemo1" width=400 height=400></applet>Label

For displaying textConstructor DescriptionLabel() Constructs an empty label.Label(String text) Constructs a string with the corresponding textLabel(String text,int alignment)Constructs a string with the text, with the specified alignment. the alignment could be CENTER,LEFT,RIGHT

Method DescriptiongetText() Gets the text of the coresponding label.setText(String text) set the text for the corresponding label to the specified textEg: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>*/ListList the items, the user can select a single or multiple items.

Page 104: Programming on Java -  Notes

Constructors DescriptionList() Creates a new scrolling list of items List(int rows) Creates a new scrolling list of items with the

specified number of visible linesList(int rows,Boolean mutilplemode) Creates a new scrolling list of

items to display the specified number of rows

Method Descriptionadd(String item) Adds the specified item at the end of the scrolling listadd(String item,int index) Adds the specified item at the position specifieddeselect(int index) deselects the item at the specified indexgetItem(int index) Gets the item at the specified indexgetItemCount() gets the number of items in the listgetItems() gets the items in the listgetRows() Gets the number of visible lines in the corresponding listint[] getSelectedIndexes() Gets the index of the selected item in the listgetSelectedItem() Gets the selected item in the corresponding listselect(int index) Selects the item at the specfied index in the corresponding listsetMultipleMode(boolean b) Sets the flag that allows multiple selection in the corresponding listEg: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");

Page 105: Programming on Java -  Notes

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

VerticalHorizontal

ScrollBar ContructorsScrollbar()Scrollbar(int style)Scrollbar(int style,int initial value,int thumbsize,int min, int max)

styleScrollbar.VERTICALScrollbar.HORIZONTAL

Page 106: Programming on Java -  Notes

initial value - Starting value of the scrollbarthumbsize - Defint the thumbsizemin - Minimum valuemax - Maximum valueMethodssetValues(int initialvalue,int thumbsize,int min,int max) - Set the valuesint getMinimum() - Get minimum valueint getMaximum() - Get Maximum valueint getValue() - Get the current valuevoid setUnitIncrement(int newincr) - Defualt 1,void setBlockIncrement(int newIncr) - Set the block increment (ie) click at the centre space of the scrollbar -> default 10To 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_DECREMENTA Page Down event has been generated

BLOCK_INCREMENTA Page Up event is generated TRACKAn absoulte tracking event is generated

UNIT_DECREMENTThe line down button in a scrollbar is pressed UNIT_INCREMENTThe line up button in a scrollbar is pressedEg: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);

Page 107: Programming on Java -  Notes

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)

MethodsString getText() Used to get the text from TextFieldvoid setText(String str) Used to set the textString getSelectedText() returns the selected textvoid select(int startindex,int endindex) Used to select the textvoid setEditable(boolean canEdit) If it is false, the text cannot be altered

Page 108: Programming on Java -  Notes

boolean isEditable() Used to check if the text is editable or notvoid setEchoChar(char ch) Set the printed character in text (password field)boolean echoCharIsSet() check if the echo char is set or notchar getEchoChar() get the echoed characterEg: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); }

Page 109: Programming on Java -  Notes

}//<applet code="TextFieldDemo" width=500 height=500></applet>TextArea

Multiline Data EntryConstructors

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)

sBarsSCROLLBARS_BOTH -0SCROLLBARS_HORIZONTAL_ONLY -2SCROLLBARS_NONE - 3SCROLLBARS_VERTICAL_ONLY -1

MethodsString 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 linevoid insert(String str,int index) - Insert the string in the correspoding index positionvoid repalceRange(String str,int startIndex,int ndIndex) - Replace the string with the corresponding start and end indexEg: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

Page 110: Programming on Java -  Notes

To Create dynamic windowAct as a container

ConstructorsFrame(String title)MethodssetVisible(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){

Page 111: Programming on Java -  Notes

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

elseSystem.out.println("Maybe clicked");

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

FrameDemo fm = new FrameDemo("Sample");}

}MenusCreate a Menu barCreate MenuInside menu create menu item

Page 112: Programming on Java -  Notes

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 MethodsMethods Descriptionadd(Menu) Adds the specified menuitem to the menuadd(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 menugetItem(int index) Returns the item at the specified index as a stringremove(int index) Deletes the item at the specified index from the menuMenuItem class MethodsMethods DescriptiongetLabel() Returns the label of the menu item as a stringsetLabel(String) Changes the label of the menuitem to the specified stringsetEnabled(boolean) Makes the menu item selectable/deselectable depending on

whether the parameter is true or falseCheckboxMenuItemCreates a dual state menu itemMethods DescriptiongetState() 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;

Page 113: Programming on Java -  Notes

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)

Page 114: Programming on Java -  Notes

{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 ClassFor Dialog box first create a frameThen 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 DescriptionDialog(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 constructorMethods DescriptionsetResizable(boolean) Sets the resizable flag of the dialog.if the boolean value is true, the dialog is made resizableboolean 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 closedboolean isResizable() Returns true is the dialog is resizable

Page 115: Programming on Java -  Notes

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.javaimport java.awt.*;

Page 116: Programming on Java -  Notes

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

Page 117: Programming on Java -  Notes

dispose();System.exit(0);

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

MessageBoxAppln mba = new MessageBoxAppln("MessageBox Demo");

}}

FileDialogUsed to display the modal dialog windows like open and saveConstructor DescriptionFileDialog(Frame parent) Creates a filedialog for loading a fileFileDialog(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 fileMethod DescriptiongetDirectory() Gets the directory of the corresponding file dialoggetFile() Gets the file of the corresponding file dialoggetFilenameFilter() Determines the file dialog's filename filtergetMode() Indicates whether the file dialog is in the save mode or open modesetDirectory(String) Sets the directory of the file dialog window to the one specifiedsetFile(String file) Sets the selected file for the corresponding file dialog window to the one specifiedsetFilenameFilter( sets the filename filter for thefilenamefilter filter) specified dialog window to the specified valuesetMode(int mode) Sets the mode of the file dialogEg:import java.awt.*;

Page 118: Programming on Java -  Notes

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

}}); }

Page 119: Programming on Java -  Notes

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

Page 120: Programming on Java -  Notes

dispose();System.exit(0);

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

MyApp m1 =new MyApp("NotepadAppln");}

}

Layouts - To set the applet orientationFour LayoutsFlowLayout-default (word processor) left,right,centerGridLayout - set as rows and columnsBorderLayout - Set as bordersCardLayout - Used for Slide preparationFlowLayoutConstructor DescriptionFlowLayout() Constructs a new flow layout with centered alignment leaving a vertical and horizontal gap of 5 pixelsFlowLayout(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 specifiedMethodgetAlignment()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;

Page 121: Programming on Java -  Notes

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>GridLayoutconstructor DescriptionGridLayout() Constructs a grid layout with a default one column per component in a single rowGridLayout(int rows,int cols) Constructs a grid layout with the specified rows and colsGridLayout(int rows,int cols,int hgap,int vgap) Creates a grid layout with the specified rows and cols and specified horizontal and vertical gapsMethodgetColumns()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++)

Page 122: Programming on Java -  Notes

{for(int j=1;j<=5;j++){

add(new Button("j = " + j));}

}}

}//<applet code=GLDemo width=400 height=400></applet>BorderLayoutConstructor DescriptionBorderLayout() Creates a new BorderLayout with no gap between the componentsBorderLayout(int hgap,int vgap) Creates a new BorderLayout with thespecified hgap and vgap between components

MethodsgetHgap()getVgap()setHgap(int hgap)setVgap(int vgap)Insets methodaround 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();

Page 123: Programming on Java -  Notes

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>CardLayoutCardLayout() Creates a new CardLayoutCardLayout(int hgap,int vgap) Create a new CardLayout with hgap and vgap valueMethodssetHgap(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);

}

Page 124: Programming on Java -  Notes

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

Page 125: Programming on Java -  Notes

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 Componentsjavax.swing.*;Class DescriptionAbstractButton Abstract superclass for swing buttonsButtonGroup Encapsulates a mutually exclusives set of buttonsImageIcon Encapsulates an iconJApplet The swing version of AppletJButton The swing push button classJCheckBox The swing checkbox classJComboBox 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 buttonJScrollPane Encapsulates a scrollable windowJTabbedPane Encapsulates a tabbed window

Page 126: Programming on Java -  Notes

JTable Encapsulates a table based controlJTextField The swing version of text fieldJTree Encapsulates a tree based controlswing related classes are contained in javax.swing.* packageJAppletsame as applet class in awt.Container c=getContentPane(); //Retrieves the browser settings.c.add(components);Icons and LabelsIcons 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 Descriptionint getIconHeight() Returns the height of the icon in pixels.int getIconWidth() Returns the width of the icon in pixelsvoid paintIcon(Component comp,Graphics g,int x,int y) Paints the icon at position x,y on the graphics context g. JLabelJLabel(icon i)JLabel(String s)JLabel(String s,icon i,int align)align = LEFT,RIGHT,CENTER,LEADING,TRAILINGMethodsIcon 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);

Page 127: Programming on Java -  Notes

}} //<applet code="JLabelDemo.class" width=500 height=500></applet>JTextFieldsJTextField()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>JButtonString 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());

Page 128: Programming on Java -  Notes

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

Page 129: Programming on Java -  Notes

ItemStateChanged() - event getText() methodgetItem() methodEg: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); }

Page 130: Programming on Java -  Notes

public void itemStateChanged(ItemEvent ie) { JCheckBox cb = (JCheckBox)ie.getItem();

jtf.setText(cb.getText()); }

}//<applet code="JCheckBoxDemo.class" width=400 height=400></applet>JRadioButtonJRadioButton(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); }

Page 131: Programming on Java -  Notes

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

Page 132: Programming on Java -  Notes

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

Page 133: Programming on Java -  Notes

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)

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

Page 134: Programming on Java -  Notes

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 formJTree(Object obj[]) obj is a child node in second formJTree(TreeNode tn) tree in the third formJTree(Vector v) child nodes

EventsaddTreeExpansionListener(TreeExpansionListener tel)removeTreeExpansionListener(TreeExpansionListener tel)TreePath getPathForLocation(int x,int y) - methodtoString() - used to return the treepath DefaultMutableTreeNode(Object obj)void add(MutableTreeNode child)

TreeExpansionListener interface provides two methodsvoid 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);

Page 135: Programming on Java -  Notes

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

Page 136: Programming on Java -  Notes

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 ConnectivityUsed to connect with database..ODBC - Open Database Connectivity

Page 137: Programming on Java -  Notes

SQL - Serverusername:sapassword:

Create table stud(sno int,sname varchar(20),course varchar(10),fees int)

sp_help studSelect * from studInsert 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 Backend1. Initialize the Driver File - Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");2. Establish the connection with database.3. Query the Database.java.sql.*;Connection -> Establish ConnectionResultSet -> Query the Database (Select)Statement -> Execute the commands

(DDL(Data Definition Language) - Create, Alter, DropDML(Data Manipulation Language)- Insert, Update, DeleteTCL(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 MethodscreateStatement() -> Initialize the Statement objectStatement Class MethodsexecuteUpdate(String qry) -> Execute Create, Alter, Drop,

Insert,Update, Delete CommandexecuteQuery(String qry) -> Execute Select command.TableCreationDemo.javaimport java.sql.*;

Page 138: Programming on Java -  Notes

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

Page 139: Programming on Java -  Notes

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.javaimport 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.javaimport java.sql.*;

Page 140: Programming on Java -  Notes

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

Page 141: Programming on Java -  Notes

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

Page 142: Programming on Java -  Notes

}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 modelCORBA -> Common Object Request Broker Architecture.

Java C++Working of an RMI Application

Page 143: Programming on Java -  Notes

* Server side* Client Side.

Server sideMethod 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> rmiregistryUnderstanding RMI ArchitectureApplication 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

Page 144: Programming on Java -  Notes

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.

ProgramsSimpleIntf.javaimport 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.javaimport 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

Client / JavaServer / Java

StubSkeleton

Network Layer

RMI Registry

Page 145: Programming on Java -  Notes

{ return a1-b1; }}Server.javaimport 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.javaimport 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.javajavac SimpleImpl.javarmic SimpleImpljavac Server.javajavac Client.javaFirst Command Prompt>rmiregistry

Page 146: Programming on Java -  Notes

Second Command Prompt>java ServerThird Command Prompt>java ClientChatIntf.javaimport java.rmi.*;public interface ChatIntf extends Remote{ public String get() throws RemoteException; public void set(String str) throws RemoteException;}ChatImpl.javaimport 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.javaimport 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);

Page 147: Programming on Java -  Notes

System.out.println("Registered...."); }}ChatClient.javaimport 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);

Page 148: Programming on Java -  Notes

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;

Page 149: Programming on Java -  Notes

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.javaimport 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.javaimport 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 {

Page 150: Programming on Java -  Notes

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

Page 151: Programming on Java -  Notes

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.javaimport 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 {

Page 152: Programming on Java -  Notes

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

ServletsServlets 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

Page 153: Programming on Java -  Notes

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;

Page 154: Programming on Java -  Notes

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

Page 155: Programming on Java -  Notes

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 cycle1. 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.javaimport 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

Page 156: Programming on Java -  Notes

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

ServletServletContextServletRequestServletResponse

And the classes are:ServletInputStreamServletOutputStreamTo 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.

Page 157: Programming on Java -  Notes

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 methodsgetInitParameters()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 directlydoDelete() - when the data deleted on the serverdoTrace() - when the data traced on the server

MVC - Model View Controller Architecture Design -> Applet or HTML

Page 158: Programming on Java -  Notes

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

Page 159: Programming on Java -  Notes

username password

Second Pagereq.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 pageCookie c[] = req.getCookies() -> read onlyfor(int i=0;i<c.length;i++)

if(c[i].getName().equals("uname"))Servlet Interface and its methods1. 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 interface1. 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 Interface1. ServletOutputStream getOutputStream()2. void setContentLength()3. void setContentType(String type)4. void writeHeaders()

Page 160: Programming on Java -  Notes

5. void setStatus(int status)6. void setHeader(String header_field,String header_value)status constantsSC_OKSC_CREATEDSC_NO_CONTENTSC_MOVED_PERMANENTLYSC_MOVED_TEMPORARILYSC_BAD_REQUESTSC_UNAUTHORIZEDSC_FORBIDDENSC_NOT_FOUNDServletContext Interface1. String getServletInfo()2. String getServlet()3. Enumeration getServlets()Applet to Servlet CommunicationSession TrackingSession 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.javaimport 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>");

}

Page 161: Programming on Java -  Notes

}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 ProgramFirst Command Prompt> Set classpath=%path%;d:\jsdk2.0\src;>javac First.java>copy First.java d:\jsdk2.0\examplesSecond Command promptd:\jsdk2.0\bin>servletrunnerInternet ExplorerFirst.htmlLogin.javaimport 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

Page 162: Programming on Java -  Notes

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

Page 163: Programming on Java -  Notes

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

Page 164: Programming on Java -  Notes

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

Page 165: Programming on Java -  Notes

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)

Page 166: Programming on Java -  Notes

{ out.println("Exception : " + e); } }}DateField.javaimport 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

Page 167: Programming on Java -  Notes

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

Page 168: Programming on Java -  Notes

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.javaimport 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{

Page 169: Programming on Java -  Notes

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

Page 170: Programming on Java -  Notes

}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.javaimport javax.servlet.*;import javax.servlet.http.*;import java.io.*;public class Cookie1 extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException

Page 171: Programming on Java -  Notes

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

Page 172: Programming on Java -  Notes

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.javaimport javax.servlet.*;import javax.servlet.http.*;import java.io.*;public class next extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {

Page 173: Programming on Java -  Notes

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

Page 174: Programming on Java -  Notes

private void pageFooter(HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("</body>"); out.println("</html>"); }}Session1.javaimport 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.javaimport javax.servlet.*;import javax.servlet.http.*;import java.io.*;

Page 175: Programming on Java -  Notes

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

Page 176: Programming on Java -  Notes

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

Page 177: Programming on Java -  Notes

{ out.println(e); } out.println("<h1 align=center>This Site has been visited " + count + " no of times</h1>"); }}myapplet.javaimport 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);

Page 178: Programming on Java -  Notes

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

Page 179: Programming on Java -  Notes

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

Page 180: Programming on Java -  Notes

}catch(Exception ex){} }}MarqueeServlet.javaimport 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.javaimport 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

Page 181: Programming on Java -  Notes

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

Page 182: Programming on Java -  Notes

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

Page 183: Programming on Java -  Notes

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

Page 184: Programming on Java -  Notes

4. Implemented as an architecture - independent and Platform IndependentArchitectureSingle Tier ArchitectureTwo 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, HTMLControlling -> business logic (Database Connectivity and

Functions - Java, Servlets, JSP, EJB)Server -> Storing and Retrieving Data (Oracle, SQL -

ServerTwo Types of Components1. Visual Component - CheckBox, ListBox2. Non Visual Component. - Timer Control, Spell Checker.Visual Software Components1. Visual Software Components are software components with visual representation.2. Button is an example for Visual software Component3. Visual component propogates the user - input events.4. Visual design tools/application builder tools provide support to graphically manipulate the buttons.Non Visual Software Components1. 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 Model1. Defines the architecture of components 2. Software component model defines two fundamental elements namely components and containers3. Containers are also referred to as forms, pages,frames (or) shells4. 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.

Page 185: Programming on Java -  Notes

2. Event Handling3. Persistance - Permanent.4. layout5. Application Builder Support. (BDK)6. Distributed Computing Support. (RMI, Servlets)Advantages of Java Beans1. 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 Bean1. Components of Data and Methods2. Capable of accessing private,public and protected methods3. 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 appletUsing an Application builder tool to build an appletSteps 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>runUsing beans in handwritten code

Page 186: Programming on Java -  Notes

Steps required in building up an application are given below:1. Layout the applications and appropriately position the bean2. Customize the beans3. Connect the bean that register event listeners and handlers the event4. 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 createdf-> 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 PropertyBoolean PropertyIndexed PropertySimple 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 PropertyA 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 PropertyAn indexed property is a property that can take an array of values.

Eg:Circle.javaimport java.awt.*;import java.applet.*;

Page 187: Programming on Java -  Notes

public class Circle extends Applet{ public void paint(Graphics g) { g.drawOval(10,10,80,80); }}javac Circle.java

Circle.mftName: Circle.classJava-Bean: trued:\demo\beans>jar cfm Circle.jar Circle.mft Circle.classcd..d:\demo\beans>copy Circle.jar c:\bdk\jarsc:\bdk\beanbox>runmyBean1.javaimport 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.mftName: myBean1.classJava-Bean: true

Page 188: Programming on Java -  Notes

MyBean.java// Implementing Simple and Boolean Propertyimport 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;

Page 189: Programming on Java -  Notes

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

Page 190: Programming on Java -  Notes

change(); } public void mouseEntered(MouseEvent me) { change(); } public void mouseExited(MouseEvent me) { change(); } public void mouseClicked(MouseEvent me) { change(); }}MyBean.mftName: MyBean.classJava-Bean: truemyBean2.java// Implementing Simple, Indexed and Boolean Propertyimport 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() {

Page 191: Programming on Java -  Notes

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.mftName: myBean2.classJava-Bean: true

Page 192: Programming on Java -  Notes

Java Server PagesServer 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 JSPInternet Information Server 5.0 (WindowsNT)JavaWebserver 2.0Apache Server - This Server provide full support for JSP(WindowsNT)J2EE serverWeblogicWebsphereLife cycle of JSP1. Browser Request HTML or JSP2. The Request are received by the server.3. Server sends request to Java Engine3. If needed, the Java engine reads the .jsp file4. The JSP is turned into a Servlet, compiled and loaded5. The servlet runs and generates HTML6. Java engine sends HTML to server7. Server sends HTML back to browserAdvantages1. Flexible Environment2. It supports direct beans information3. It is an Interpreter Language(Automatically compiled)4. It supports XML(Extensible Markup Language) tags5. Reuse of components and tag libraries.Structural syntax of JSPConstructorjspInit() - InitializationjspService() - Processing requestjspDestroy() - DestroyedComments<%-- ...text... --%>

JSP comments are stripped out by the JSP Engine at Translation time.Declarations

<%! type varname; %>

Page 193: Programming on Java -  Notes

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

Page 194: Programming on Java -  Notes

<%@ 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 independentlylanguage="java"This code will specifies what language will be used in scriplets.

Currently only java is supportedextends = "base class"This code can force the generated servlet to extend a specific class.

This should be used very rarelyimport="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|falseBy 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"

Page 195: Programming on Java -  Notes

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 JSPOut - output stream for page contentConfig - Servlet configuration dataRequest - Request data, including parametersResponse - Response dataSession - User specific session dataApplication - Data shared by all application pages.PageContext - Context data for page executionException - Uncaught error or exceptionPage - Page's servlet instance (Same as Server Object)Request Object

Used to get information from the client browserMethodsEnumeration getParameterNames() Returns the names of all request parametersString getParameter(name) Returns the first (or primary) value of a single request parameterEnumeration getParameterValues() Retrieves all of the values for a single request parametergetHeaderNames() Retrieves the names of all headers associated with request

Page 196: Programming on Java -  Notes

getHeader(name) Retrieves the value of a single request header, as a stringgetHeaders(name) Returns all of the values for a single request headergetIntHeader(name) Returns the value of a single request header,as an integergetDateHeader(name) Returns the value of a single request header, as a dategetCookies() Retrieves all of the cookies associated with the requestgetMethod() Returns the HTTP(eg.GET , POST) method for the request.getRequestURI() Returns the request URL, up to but not including any stringgetQueryString() Returns the query string that follows the request URL, if anygetSession() 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 URLgetRemoteHost() Returns the fully qulified name of the host that sent the request.getRemoteAddr() Returns the network address of the host that sent the requestgetRemoteUser() Returns the name of the user that sent the request, if known.getProtocol() Http/1.1Eg1:<html><body>Hello user! You are using a computercalled <%= request.getRemoteHost() %>!</body></html>Eg2:<html><body>

Page 197: Programming on Java -  Notes

Hello user! I am on a computer called<%= request.getServerName() %>, and you are using a computercalled <%= 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());

Page 198: Programming on Java -  Notes

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>

Page 199: Programming on Java -  Notes

<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 exactlyand <%= 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 {

Page 200: Programming on Java -  Notes

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){}%>demofileThis is a sample demofileEg9:<%@ 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

Page 201: Programming on Java -  Notes

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.MethodssetContentType(string) - Sets the Content type("text/html") and character encoding (ISO)getCharacterEncoding() - Default character EncodingsetContentLength(int) - OutputStream getOutputStream() Writer getWriter() addCookie(cookie) setStatus(int sc) - sendError(int sc)sendError(int sc,String sm)sendRedirect(String URL)Sc_constantsSC_CONTINUE = 100SC_OK = 200SC_CREATED = 201SC_ACCEPTED = 202SC_NOT_FOUND = 404SC_NOT_ACCEPTABLE = 406SC_BAD_GATEWAY = 502

response.sendRedirect Methodsample.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

Page 202: Programming on Java -  Notes

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

Page 203: Programming on Java -  Notes

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

Page 204: Programming on Java -  Notes

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>

Page 205: Programming on Java -  Notes

<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 JSP1. Security2. 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()ScopeSessionApplicationRequestResponseSteps to Create Bean file and extract in JSP1. Create a java file and compile it.2. Copy the class file to c:\javawebserver2.0\classes3. Create JSP file in public_html and run it.Eg:paintbrush.java

Page 206: Programming on Java -  Notes

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>CookiesFor Creating CookieCookie c = new Cookie("Cookie_name","Value")requestString getName() - Get the name of the CookieString getValue() - Get the value of the Cookieresponseresponse.addCookie(c);Cookie[] request.getCookies() - get the Cookies values.Eg:Login.html<html><body><h2 align=center> Login Form </h2><table align=center>

Page 207: Programming on Java -  Notes

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

Page 208: Programming on Java -  Notes

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

%>

Page 209: Programming on Java -  Notes

Enterprise Java BeansSun 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 JavaEJB 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

Home Interface

EJB ObjectRemote Intf

Bean Class

EJB Server which contains the EJB container.EJB container, which contains enterprise beansEnterprise 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:

ClientHome Interface

EJBHomeStub

Remote InterfaceEJBObjectStub

EJB Server

EJB Home

EJB Container

Page 210: Programming on Java -  Notes

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 ContainerThe 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 client’s 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. Security2. Transaction Management3. Persistance -> Permanent Storage4. Life Cycle Management

Enterprise BeanEnterprise 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 Bean2. Session Bean

Entity BeanEntity Beans are enterprise beans that persist across multiple sessions

and multiple clients. There are two types of Entity bean:1. Bean Managed Persistance2. Container Managed Persistance

Page 211: Programming on Java -  Notes

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 Bean2. 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 ComponentsEnterprise Bean (.jar files) Web Component (.war files)

| |-------------------------------------------------------

|J2EE Application(.ear Files)

| DeployedJ2EE Server

Jar -> Java ArchiveWar -> Web ArchieveEar -> Enterprise ArchieveSession BeanStateless BeanHome InterfaceRemote InterfaceBean ClassServer ClassClient Applications.batpath=%path%;d:\jdk1.2\bin;d:\j2sdkee1.2\binset classpath=d:\j2sdkee1.2\lib\j2ee.jar;d:\demo\ejb;set java_home=d:\jdk1.2set j2ee_home=d:\j2sdkee1.2

Page 212: Programming on Java -  Notes

Eg:Calculator.java//Remote Interfaceimport javax.ejb.EJBObject;import java.rmi.RemoteException;public interface Calculator extends EJBObject{ public double dollarToRs(double dollars) throws RemoteException;}

CalculatorHome.java// Home Interfaceimport 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 classimport 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) {}

Page 213: Programming on Java -  Notes

}Deploying an Enterprise JavaBeanCalculatorClient.javaimport 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);

Page 214: Programming on Java -  Notes

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 multiple method – calls The bean needs to store client – specific information across method

calls.Life Cycle of a Stateful session bean

Does not exists

Ready Passive

Create()newInstance()setSessionContext()ejbCreate()

remove()ejbRemove()

ejbPassivate()

ejbActivate()

Page 215: Programming on Java -  Notes

Eg:Problem Statement

Earnest Bank’s 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 applicationEg:Card.javaimport java.util.*;import javax.ejb.EJBObject;import java.rmi.RemoteException;public interface Card extends EJBObject{ public int validate(String CardNo) throws RemoteException;}CardHome.javaimport 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.javaimport javax.ejb.*;import java.rmi.RemoteException;public class CardEJB implements SessionBean

Page 216: Programming on Java -  Notes

{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.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import javax.naming.Context;

Page 217: Programming on Java -  Notes

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)

Page 218: Programming on Java -  Notes

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

Page 219: Programming on Java -  Notes

Entity Bean

Session Bean Entity BeanIt is used to carry out tasks based on request from clients

It is used to represent a business entity object in a data store

It can be accessed by just a single client

It can be accessed by multiple clients

It cannot model persistent Data

It can model persistent data

Problem StatementEarnest 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.DatabaseRegistrationcRegistrationID intcFirst_Name char(50)cLast_Name char(50)cAddress char(50)cAccount_tyoe char(30)mAnnual_Income money(8)cPhone_No char(10)Account_HoldercAccount_id char(10)cRegistrationID intmBalance money(8)Account_Holder_TransactioncAccount_id char(10)dDate_of_Trans datetimevcParticulars varchar(50)cCheck_No char(10)mAmount money