0% found this document useful (0 votes)
1K views62 pages

Java Programming: Constructors & Inheritance

The document contains 6 code examples that illustrate object-oriented programming concepts in Java including: 1. Constructor overloading using a Rectangle class. 2. Method overloading using an OverloadDemo class. 3. Single inheritance by extending the Box class to include weight. 4. Multilevel inheritance extending Box to BoxWeight to Shipment. 5. Dynamic polymorphism by overriding a callme() method in subclasses of class A. 6. Abstract classes using abstract area() methods in Figure subclasses Rectangle and Triangle.

Uploaded by

Mahek Fatima
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views62 pages

Java Programming: Constructors & Inheritance

The document contains 6 code examples that illustrate object-oriented programming concepts in Java including: 1. Constructor overloading using a Rectangle class. 2. Method overloading using an OverloadDemo class. 3. Single inheritance by extending the Box class to include weight. 4. Multilevel inheritance extending Box to BoxWeight to Shipment. 5. Dynamic polymorphism by overriding a callme() method in subclasses of class A. 6. Abstract classes using abstract area() methods in Figure subclasses Rectangle and Triangle.

Uploaded by

Mahek Fatima
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • Class Constructor Overloading
  • Method Overloading
  • Single Inheritance
  • Multilevel Inheritance
  • Dynamic Polymorphism
  • Abstract Classes
  • Threading with Thread Class
  • Threading with Runnable Interface
  • Multi-threading Concept
  • Thread Synchronization
  • Producer-Consumer Problem
  • String Tokenizer
  • Interfaces Implementation
  • Using Collection Classes
  • I/O Streams
  • HTML and JavaScript Programs
  • XML and XSLT
  • Database Interaction using JDBC
  • HTML Form with JavaScript Validation
  • Applet Programming
  • Servlet Session Tracking
  • Event Handling with Listeners
  • Date and Random Numbers in JSP
  • Servlet for Cookie Handling
  • Text Processing with Regular Expressions
  • Servlet Program for HelloWorld

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

1.

A program to illustrate the concept of class with constructors overloading. Program: class Rectangle{ int l, b; float p, q; public Rectangle(int x, int y){ l = x; b = y; } public int first(){ return(l * b); } public Rectangle(int x){ l = x; b = x; } public int second(){ return(l * b); } public Rectangle(float x){ p = x; q = x; } public float third(){ return(p * q); } public Rectangle(float x, float y){ p = x; q = y; } public float fourth(){ return(p * q); } } class ConstructorOverload { public static void main(String args[]) { Rectangle rectangle1=new Rectangle(2,4); int areaInFirstConstructor=[Link]();

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

[Link](" The area of a rectangle in first constructor is : Rectangle rectangle2=new Rectangle(5); int areaInSecondConstructor=[Link](); [Link](" The area of a rectangle in first constructor is : Rectangle rectangle3=new Rectangle(2.0f); float areaInThirdConstructor=[Link](); [Link](" The area of a rectangle in first constructor is : Rectangle rectangle4=new Rectangle(3.0f,2.0f); float areaInFourthConstructor=[Link](); [Link](" The area of a rectangle in first constructor is : } } Output: Compile: javac [Link] Run: java ConstructorOverload The area of a rectangle in first constructor is : The area of a rectangle in first constructor is : The area of a rectangle in first constructor is : The area of a rectangle in first constructor is : 8 25 4.0 6.0

" + areaInFirstConstructor);

" + areaInSecondConstructor);

" + areaInThirdConstructor);

" + areaInFourthConstructor);

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

2.

A program to illustrate the concept of class with Method overloading. Program: class OverloadDemo { void test() { [Link]("No parameters"); } // Overload test for one integer parameter. void test(int a) { [Link]("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { [Link]("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { [Link]("double a: " + a); return a*a; } } class MethodOverload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() [Link](); [Link](10); [Link](10, 20); result = [Link](123.25); [Link]("Result of [Link](123.25): " + result); } } Output: Compile: javac [Link] Run: java MethodOverload No parameters a: 10 a and b: 10 20 double a: 123.25 Result of [Link](123.25): 15190.5625

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

3.

A program to illustrate the concept of Single inheritance Program: // This program uses inheritance to extend Box. class Box { double width; double height; double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = [Link]; height = [Link]; depth = [Link]; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1;} // box // constructor used when cube is created Box(double len) { width = height = depth = len;} // compute and return volume double volume() { return width * height * depth; } } // Here, Box is extended to include weight. class BoxWeight extends Box { double weight; // weight of box // constructor for BoxWeight BoxWeight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m;

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

} } class DemoBoxWeight { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = [Link](); [Link]("Volume of mybox1 is " + vol); [Link]("Weight of mybox1 is " + [Link]); [Link](); vol = [Link](); [Link]("Volume of mybox2 is " + vol); [Link]("Weight of mybox2 is " + [Link]); } } Output: Compile: javac [Link] Run: java DemoBoxWeight Volume of mybox1 is 3000.0 Weight of mybox1 is 34.3 Volume of mybox2 is 24.0 Weight of mybox2 is 0.076

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

4.

A program to illustrate the concept of Multilevel inheritance Program: // Start with Box. class Box { private double width; private double height; private double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = [Link]; height = [Link]; depth = [Link]; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len;} // compute and return volume double volume() { return width * height * depth; } } // Add weight. Class BoxWeight extends Box { double weight; // weight of box // construct clone of an object BoxWeight(BoxWeight ob) { // pass object to constructor super(ob); weight = [Link]; }

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

// constructor when all parameters are specified BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } // default constructor BoxWeight() { super(); weight = -1; } // constructor used when cube is created BoxWeight(double len, double m) { super(len); weight = m; } } // Add shipping costs class Shipment extends BoxWeight { double cost; // construct clone of an object Shipment(Shipment ob) { // pass object to constructor super(ob); cost = [Link]; } // constructor when all parameters are specified Shipment(double w, double h, double d, double m, double c) { super(w, h, d, m); // call superclass constructor cost = c; } // default constructor Shipment() { super(); cost = -1; } // constructor used when cube is created Shipment(double len, double m, double c) { super(len, m); cost = c; } }
BIT-282JAVA PROGRAMMING & WT LAB [Link] Ali (1604-10-737-048) PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

class DemoShipment { public static void main(String args[]) { Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41); Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28); double vol; vol = [Link](); [Link](Volume of shipment1 is + vol); [Link](Weight of shipment1 is + [Link]); [Link](Shipping cost: $ + [Link]); [Link](); vol = [Link](); [Link](Volume of shipment2 is + vol); [Link](Weight of shipment2 is + [Link]); [Link](Shipping cost: $ + [Link]); } } Output: Compile: javac [Link] Run: java DemoShipment Volume of shipment1 is 3000.0 Weight of shipment1 is 10.0 Shipping cost: $3.41 Volume of shipment2 is 24.0 Weight of shipment2 is 0.76 Shipping cost: $1.28

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

5.

A program to illustrate the concept of Dynamic Polymorphism. Program: class A { void callme() { [Link]("Inside A's callme method"); } } class B extends A { // override callme() void callme() { [Link]("Inside B's callme method"); } } class C extends A { // override callme() void callme() { [Link]("Inside C's callme method"); } } class Dispatch { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A r = a; // r refers to an A object [Link](); // calls A's version of callme r = b; // r refers to a B object [Link](); // calls B's version of callme r = c; // r refers to a C object [Link](); // calls C's version of callme } } Output: Compile: javac [Link] Run: java Dispatch Inside A's callme method Inside B's callme method Inside C's callme method

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

6.

A program to illustrate the concept of Abstract Classes. Program: abstract class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } // area is now an abstract method abstract double area(); } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { [Link]("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { [Link]("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class AbstractAreas { public static void main(String args[]) { // Figure f = new Figure(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; // this is OK, no object is created figref = r; [Link]("Area is " + [Link]()); figref = t;

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

[Link]("Area is " + [Link]()); } } Output: Compile: javac [Link] Run: java AbstractAreas Inside Area for Rectangle. Area is 45.0 Inside Area for Triangle. Area is 40.0

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

7.

A program to illustrate the concept of threading using Thread Class Program: class NewThread extends Thread { NewThread() { // Create a new, second thread super("Demo Thread"); [Link]("Child thread: " + this); start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { [Link]("Child Thread: " + i); [Link](500); } } catch (InterruptedException e) { [Link]("Child interrupted."); } [Link]("Exiting child thread."); } } class ExtendThread { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { [Link]("Main Thread: " + i); [Link](1000); } } catch (InterruptedException e) { [Link]("Main thread interrupted."); } [Link]("Main thread exiting."); } } Output: Compile: javac [Link] Run: java ExtendThread

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Child Thread: 1 Main Thread: 3 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

8.

A program to illustrate the concept of threading using runnable Interface. Program: class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); [Link]("Child thread: " + t); [Link](); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { [Link]("Child Thread: " + i); [Link](500); } } catch (InterruptedException e) { [Link]("Child interrupted."); } [Link]("Exiting child thread."); } } class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { [Link]("Main Thread: " + i); [Link](1000); } } catch (InterruptedException e) { [Link]("Main thread interrupted."); } [Link]("Main thread exiting."); } } Output: Compile: javac [Link] Run: java ThreadDemo

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

9.

A program to illustrate the concept of multi-threading. Program: class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); [Link]("New thread: " + t); [Link](); // Start the thread } // This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { [Link](name + ": " + i); [Link](1000); } } catch (InterruptedException e) { [Link](name + " interrupted."); } [Link](name + " exiting."); }} class MultiThreadDemo { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); NewThread ob3 = new NewThread("Three"); [Link]("Thread One is alive: " + [Link]()); [Link]("Thread Two is alive: " + [Link]()); [Link]("Thread Three is alive: " + [Link]()); // wait for threads to finish try { [Link]("Waiting for threads to finish."); [Link](); [Link](); [Link](); } catch (InterruptedException e) {

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

[Link]("Main thread Interrupted"); } [Link]("Thread One is alive: "+ [Link]()); [Link]("Thread Two is alive: "+ [Link]()); [Link]("Thread Three is alive: "+ [Link]()); [Link]("Main thread exiting."); } } Ouput: Compile: javac [Link] Run: java MultiThreadDemo New thread: Thread[One,5,main] New thread: Thread[Two,5,main] One: 5 New thread: Thread[Three,5,main] Thread One is alive: true Two: 5 Thread Two is alive: true Three: 5 Thread Three is alive: true Waiting for threads to finish. One: 4 Three: 4 Two: 4 One: 3 Three: 3 Two: 3 One: 2 Three: 2 Two: 2 One: 1 Three: 1 Two: 1 One exiting. Two exiting. Three exiting. Thread One is alive: false Thread Two is alive: false Thread Three is alive: false Main thread exiting.
BIT-282JAVA PROGRAMMING & WT LAB [Link] Ali (1604-10-737-048) PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

10.

A program to illustrate the concept of Thread synchronization. Program: class Callme { void call(String msg) { [Link]("[" + msg); try { [Link](1000); } catch (InterruptedException e) { [Link]("Interrupted"); } [Link]("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); [Link](); } // synchronize calls to call() public void run() { synchronized(target) { // synchronized block [Link](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"); // wait for threads to end try { [Link](); [Link](); [Link]();

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

} catch(InterruptedException e) { [Link]("Interrupted"); } } } Output: Compile: javac [Link] Run: java Synch1 [Hello] [World] [Synchronized]

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

11.

A program to illustrate the concept of Producer consumer problem using multi-threading. Program: class Q { int n; boolean valueSet = false; synchronized int get() { if(!valueSet) try { wait(); } catch(InterruptedException e) { [Link]("InterruptedException caught"); } [Link]("Got: " + n); valueSet = false; notify(); return n; } synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { [Link]("InterruptedException caught"); } this.n = n; valueSet = true; [Link]("Put: " + n); notify(); } } class Producer implements Runnable { Q q; Producer(Q q) { this.q = q; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) { [Link](i++);

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

} } } class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while(true) { [Link](); } } } class PCFixed { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); [Link]("Press Control-C to stop."); } } Output: Compile: javac [Link] Run: java PCFixed Put: 1 Got: 1 Put: 2 Got: 2 Put: 3 Got: 3 Put: 4 Got: 4 Put: 5 Got: 5

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

12.

A program using String Tokenizer. Program: import [Link].*; public class StringTokenizing{ public static void main(String[] args) { StringTokenizer stringTokenizer = new StringTokenizer("You are tokenizing a string"); [Link]("The total no. of tokens generated : " + [Link]()); while([Link]()){ [Link]([Link]()); } } } Output: Compile: javac [Link] Run: java StringTokenizing The total no. of tokens generated : 5 You are tokenizing a string

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

13.

A program using Interfaces. Program: interface stack { void push(int x); int pop(); } class StcksizeFix implements stack { private int tos; private int stck[]; StcksizeFix(int size) { stck=new int[size]; tos=-1; } public void push(int item) { if(tos==[Link]-1) [Link]("The stack has over flow"); else stck[++tos]=item; } public int pop(){ if(tos==-1){ [Link]("There is nothing to PoP"); return 0; } else return stck[tos--]; } } class TestStack { public static void main(String args[]) { StcksizeFix Stack1= new StcksizeFix(5); StcksizeFix Stack2= new StcksizeFix(5); [Link]("Start Push Objects in Stack"); for(int i=0;i<5;i++) [Link](2*i); for(int i=0;i<6;i++) [Link](3*i); for(int i=0;i<6;i++) { [Link]("The "+(5-i)+" element in stack 1 is "+[Link]());

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

[Link]("\t The "+(5-i)+" element in stack 2 is "+[Link]()+"\n"); } } } Output: Compile: javac [Link] Run: java StackTest Start Push Objects in Stack The stack has over flow The 5 element in stack 1 is 8 The 5 element in stack 2 is 12 The 4 element in stack 1 is 6 The 4 element in stack 2 is 9 The 3 element in stack 1 is 4 The 3 element in stack 2 is 6 The 2 element in stack 1 is 2 The 2 element in stack 2 is 3 The 1 element in stack 1 is 0 The 1 element in stack 2 is 0 There is nothing to PoP The 0 element in stack 1 is 0There is nothing to PoP The 0 element in stack 2 is 0

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

14.

A program using Collection classes. a) Array List Class Program: import [Link].*; class ArrayListDemo { public static void main(String args[]) { // create an array list ArrayList al = new ArrayList(); [Link]("Initial size of al: " +[Link]()); // add elements to the array list [Link]("C"); [Link]("A"); [Link]("E"); [Link]("B"); [Link]("D"); [Link]("F"); [Link](1, "A2"); [Link]("Size of al after additions: " +[Link]()); // display the array list [Link]("Contents of al: " + al); // Remove elements from the array list [Link]("F"); [Link](2); [Link]("Size of al after deletions: " +[Link]()); [Link]("Contents of al: " + al); } } Output: Compile: javac [Link] Run: java ArrayListDemo

Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, F] Size of al after deletions: 5 Contents of al: [C, A2, E, B, D]

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

b) Collection using Iterator Program: import [Link].*; class IteratorDemo { public static void main(String args[]) { // create an array list ArrayList al = new ArrayList(); // add elements to the array list [Link]("C"); [Link]("A"); [Link]("E"); [Link]("B"); [Link]("D"); [Link]("F"); // use iterator to display contents of al [Link]("Original contents of al: "); Iterator itr = [Link](); while([Link]()) { Object element = [Link](); [Link](element + " "); } [Link](); // modify objects being iterated ListIterator litr = [Link](); while([Link]()) { Object element = [Link](); [Link](element + "+"); } [Link]("Modified contents of al: "); itr = [Link](); while([Link]()) { Object element = [Link](); [Link](element + " "); } [Link](); // now, display the list backwards [Link]("Modified list backwards: "); while([Link]()) { Object element = [Link](); [Link](element + " "); }
BIT-282JAVA PROGRAMMING & WT LAB [Link] Ali (1604-10-737-048) PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

[Link](); } } Output: Compile: javac [Link] Run: java IteratorDemo Original contents of al: C A E B D F Modified contents of al: C+ A+ E+ B+ D+ F+ Modified list backwards: F+ D+ B+ E+ A+ C+

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

c)HashSet Program: import [Link].*; class HashSetDemo { public static void main(String args[]) { HashSet hs=new HashSet(); [Link]("A"); [Link]("D"); Iterator i=[Link](); while([Link]()) { [Link]([Link]()); } } }

Output: Compile: [Link] Run: java HashSetDemo D A

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

d)TreeMap Program: import [Link].*; class TreeMapDemo { public static void main(String args[]) { TreeMap tm=new TreeMap(); [Link]("John",new Integer(5)); [Link]("Robin",new Integer(10)); [Link]("Stephen",new Integer(15)); Set se=[Link](); Iterator i=[Link](); while([Link]()) { [Link] me=([Link])[Link](); [Link]([Link]()+":"); [Link]([Link]()); } [Link](); } } Output: Compile: javac [Link] Run: java TreeMapDemo John: 5 Robin: 10 Stephen: 15

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

e)Comparator Program: //Use a custom comparator. import [Link].*; // A reverse comparator for strings. class MyComp implements Comparator { public int compare(Object a, Object b) { String aStr, bStr; aStr = (String) a; bStr = (String) b; // reverse the comparison return [Link](aStr); } // no need to override equals } class CompDemo { public static void main(String args[]) { // Create a tree set TreeSet ts = new TreeSet(new MyComp()); // Add elements to the tree set [Link]("C"); [Link]("A"); [Link]("B"); [Link]("E"); [Link]("F"); [Link]("D"); // Get an iterator Iterator i = [Link](); // Display elements while([Link]()) { Object element = [Link](); [Link](element + " "); } [Link](); } } Output: Compile: javac [Link] Run: java CompDemo F E D C B A

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

f)LinkedList Program: import [Link].*; class LinkedListDemo { public static void main(String args[]) { LinkedList ll=new LinkedList(); [Link]("A"); [Link]("B"); [Link]("C"); Iterator i=[Link](); while([Link]()) { [Link]([Link]()); } } }

Output: Compile: javac [Link] Run: java LinkedListDemo

A B C

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

15.

A program using Buffered and Filter I/O Streams. a) Input Stream

Program: import [Link].*; class OnlyExt implements FilenameFilter{ String ext; public OnlyExt(String ext){ [Link]="." + ext; } public boolean accept(File dir,String name){ return [Link](ext); } }

public class FilterFiles{ public static void main(String args[]) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader([Link])); [Link]("Please enter the directory name : "); String dir = [Link](); [Link]("Please enter file type : "); String extn = [Link](); File f = new File(dir); FilenameFilter ff = new OnlyExt(extn); String s[] = [Link](ff); for (int i = 0; i < [Link]; i++){ [Link](s[i]); } } }

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

Output: Compile: javac [Link] Run: java FilterFiles

Please enter the directory name : E:\Java Pgms\ Please enter file type : java [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link]

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

b) Output Stream Program: import [Link].*; class ReadWriteData { public static void main(String args[]) { int ch=0; int[] numbers = { 12, 8, 13, 29, 50 }; try { [Link]("1. write Data"); [Link]("2. Read Data"); [Link]("Enter your choice "); BufferedReader br=new BufferedReader(new InputStreamReader([Link])); ch=[Link]([Link]()); switch(ch){ case 1: FileOutputStream fos = new FileOutputStream("[Link]"); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream out =new DataOutputStream (bos); for (int i = 0; i < [Link]; i ++) { [Link](numbers[i]); } [Link]("write successfully"); [Link](); case 2: FileInputStream fis = new FileInputStream("[Link]"); BufferedInputStream bis=new BufferedInputStream(fis); DataInputStream in =new DataInputStream (bis); while (true){ [Link]([Link]()); } default: [Link]("Invalid choice"); } }
BIT-282JAVA PROGRAMMING & WT LAB [Link] Ali (1604-10-737-048) PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

catch (Exception e) { } } } Output: Compile: javac [Link] Run: java readWriteData write Data Read Data Enter your choice 1 write successfully 12 8 13 29 50 write Data Read Data Enter your choice 2 12 8 13 29 50

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

16.

HTML Program for creating class time table.

Program: <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> <table width="792" height="388" border="2" cellpadding="2" cellspacing="2"> <tr bgcolor="#66FF00"> <th width="107" height="68" scope="col"><div align="center">Days/Time</div></th> <th width="104" scope="col"><div align="center">9.10AM - 10.00AM </div></th> <th width="81" scope="col"><div align="center">10.00AM - 10.50AM </div></th> <th width="92" scope="col"><div align="center">10.50AM - 11.40AM </div></th> <th width="94" scope="col"><div align="center">11.40AM - 12.30PM </div></th> <th width="79" scope="col"><div align="center">12.30PM - 1.20PM </div></th> <th width="173" scope="col"><div align="center">2.10PM - 3.00PM</div></th> </tr> <tr> <th height="34" bgcolor="#66FF00" scope="row">Monday</th> <td bgcolor="#0033FF"><div align="center">COMP</div></td> <td bgcolor="#FF00FF"><div align="center">WT</div></td> <td colspan="2" bgcolor="#FFFF66"><div align="center">DDC</div></td> <td rowspan="5" bgcolor="#00CC00"><p> L U N C K </p> <p>B R E A K </p></td> <td bgcolor="#00FFFF"><div align="center"></div> <div align="center">MP LAB - B1 <br> WT LAB - B2 <br> MINI PROJECT LAB - B3 </div><div align="center"></div></td> </tr> <tr> <th bgcolor="#66FF00" scope="row">Tuesday</th> <td colspan="2" bgcolor="#006699"><div align="center"></div> <div align="center">OOPS USING JAVA </div></td> <td bgcolor="#0033FF"><div align="center">COMP</div></td> <td bgcolor="#339966"><div align="center">SS</div></td> <td bgcolor="#FFFF66"><div align="center"></div> <div align="center">DDC</div></td> </tr> <tr> <th height="63" bgcolor="#66FF00" scope="row">Wednesday</th> <td bgcolor="#339966"><div align="center">SS</div></td>

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

<td colspan="3" bgcolor="#00FFFF"><div align="center"></div><div align="center"> MP LABB2<br> WT LAB - B3<br> MINI PROJECT LAB - B1</div><div align="center"></div></td> <td bgcolor="#006699"><div align="center"></div> <div align="center">OOPS USING JAVA </div></td> </tr> <tr> <th height="63" bgcolor="#66FF00" scope="row">Thursday</th> <td colspan="2" bgcolor="#FF00FF"><div align="center"></div><div align="center">WT</div></td> <td colspan="2" bgcolor="#FFFFFF"><div align="center"></div> <div align="center">PRP</div></td> <td bgcolor="#00FFFF"><div align="center"></div><div align="center"> MP LAB - B3<br> WT LAB - B1<br> MINI PROJECT LAB - B2 </div><div align="center"></div></td> </tr> <tr> <th bgcolor="#66FF00" scope="row">Friday</th> <td><div align="center"></div></td> <td bgcolor="#FF00FF"><div align="center">WT</div></td> <td colspan="2" bgcolor="#339966"><div align="center"></div> <div align="center">SS</div></td> <td bgcolor="#0033FF"><div align="center"></div><div align="center">COMP</div></td> </tr> </table> </body> </html>

Output: Open the document in the browser. It looks like as follows.

17.

Write a code for creating a javascript object.


[Link] Ali (1604-10-737-048) PAGE NO:

BIT-282JAVA PROGRAMMING & WT LAB

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

Program: <html> <body> <script type="text/javascript"> personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"} [Link]([Link] + " is " + [Link] + " years old."); </script> </body> </html> Output: John is 50 years old

18.

Publishing XML document using XSLT

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

Program: XSL File: [Link] <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="[Link] version="1.0"> <!-- set output mode as html --> <xsl:output method="html"/> <!-- template that matches the root node --> <xsl:template match="searchdata"> <html> <head> <title>Search Results For <xsl:value-of select="query/search" /></title> </head> <body> <h1>Search results for <xsl:value-of select="query/search" /></h1> <!-- results table --> <table border="1" cellpadding="5"> <tr> <th>Class ID</th> <th>Name</th> <th>Teacher</th> <th>Description</th> <th>Date &amp; Time</th> </tr> <!-- run the template that renders the classes in table rows --> <xsl:apply-templates select="results/class" /> </table> </body> </html> </xsl:template> <!-- template that matches classes --> <xsl:template match="class"> <tr> <td><xsl:value-of select="@id" /></td> <td><xsl:value-of select="@name" /></td> <td><xsl:value-of select="teacher" /></td> <td><xsl:value-of select="description" /></td> <td><xsl:value-of select="datetime" /></td> </tr> </xsl:template> </xsl:stylesheet>

Now create XML file. XML File: [Link]


BIT-282JAVA PROGRAMMING & WT LAB [Link] Ali (1604-10-737-048) PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="[Link]"?> <searchdata> <query> <search>XSLT</search> </query> <results> <class id="12" name="XSLT 101"> <datetime>Feb 1, 2010 8:00pm PST</datetime> <description>A basic introduction to XSLT.</description> <teacher>Steven Benner</teacher> </class> <class id="18" name="Advanced XSLT"> <datetime>Feb 2, 2010 8:00pm PST</datetime> <description>Advanced XSLT techniques and concepts.</description> <teacher>Steven Benner</teacher> </class> <class id="35" name="XSLT History"> <datetime>Feb 1, 2010 2:00pm PST</datetime> <description>The history of XSLT.</description> <teacher>Steven Benner</teacher> </class> </results> </searchdata> Open Browser and open the file [Link] The output is as follows.

19.

Write a program to create a database using Jdbc.


[Link] Ali (1604-10-737-048) PAGE NO:

BIT-282JAVA PROGRAMMING & WT LAB

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

Program: import [Link].*; public class OdbcAccessCreateTable { public static void main(String [] args) { Connection con = null; try { [Link]("[Link]"); con = [Link]("jdbc:odbc:HY_ACCESS"); // Creating a database table Statement sta = [Link](); int count = [Link]("CREATE TABLE HY_Address (ID INT, StreetName VARCHAR(20),"+ " City VARCHAR(20))"); [Link]("Table created."); [Link](); [Link](); } catch (Exception e) { [Link]("Exception: "+[Link]()); } } }

Output: Table created.

20.

Write a program to execute a statement query using Jdbc.


[Link] Ali (1604-10-737-048) PAGE NO:

BIT-282JAVA PROGRAMMING & WT LAB

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

Program: import [Link].*; public class DbConnect { public static void main(String a[]) throws Exception { Connection con; Statement st; ResultSet rs; [Link]("[Link]"); //String dsn="datasource1"; //String url="Jdbc:Odbc"+ dsn; con=[Link]("Jdbc:Odbc:dsn1"); st=[Link](); rs=[Link]("SELECT * FROM Table1"); while([Link]()) { [Link]("\nname=\t "+[Link](1)+"\nrollno=\t ="+[Link](2)); } } }

Output: name= RAihan rollno= 28 name= sakina rollno= 44

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

21.

Write a program to execute a prepared statement query using Jdbc. Program: import [Link].*; public class SqlServerPreparedSelect { public static void main(String [] args) { Connection con = null; try { [Link]("[Link]"); con = [Link]("jdbc:odbc:HY_ACCESS"); // PreparedStatement for SELECT statement PreparedStatement sta = [Link]("SELECT * FROM Profile WHERE ID = 2"); // Execute the PreparedStatement as a query ResultSet res = [Link](); // Get values out of the ResultSet [Link](); String firstName = [Link]("FirstName"); String lastName = [Link]("LastName"); [Link]("User ID 2: "+firstName+' '+lastName); // Close ResultSet and PreparedStatement [Link](); [Link](); } catch (Exception e) { [Link]("Exception: "+[Link]()); } } }

Output: User ID 2: Anas Jabri

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

22.

Develop a HTML Form with client validations using Java Script.

Program: <html> <head> <title>A Simple Form with JavaScript Validation</title> <script type="text/javascript"> <!-function validate_form ( ) { valid = true; var x=[Link]["contact_form"]["email"].value; var atpos=[Link]("@"); var dotpos=[Link]("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=[Link]) { alert("Not a valid e-mail address"); valid=false; } if ( document.contact_form.contact_name.value == "" ) { alert ( "Please fill in the 'Your Name' box." ); valid = false; } return valid; } --> </script> </head> <body bgcolor="#FFFFFF"> <form name="contact_form" method="post" onSubmit="return validate_form ( );"> <h1>Please Enter Your Name</h1> <p>Your Name: <input type="text" name="contact_name"></p> <p>Email Id : <input type="text" name="email"></p> <p><input type="submit" name="send" value="Send Details"></p> </form> </body> </html>

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

Output:

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

23.

Write a code for helloworld applet using

a) applet viewer Program: import [Link].*; import [Link].*; public class HelloWorld extends Applet { public void paint(Graphics g) { [Link]("Hello world", 20, 20); } } Output:

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

b) browserProgram: import [Link].*; import [Link].*; /* <applet code="HelloWorld" width=200 height=60> </applet> */ public class HelloWorld extends Applet { public void paint(Graphics g) { [Link]("Hello World", 20, 20); } } Output:

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

24.

Write a Java Servlet Program for Session Tracking.

Servlet Program: [Link] import [Link].*; import [Link].*; import [Link].*; public class CheckingTheSession extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { [Link]("text/html"); PrintWriter pw = [Link](); [Link]("Checking whether the session is new or old<br>"); HttpSession session = [Link](); if([Link]()){ [Link]("You have created a new session"); } else{ [Link]("Session already exists"); } } } Deployment Descriptor: [Link] <?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <display-name>Web Application</display-name> <description> Web Application </description> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>CheckingTheSession</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/CheckingTheSession</url-pattern> </servlet-mapping> </web-app>

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

Output: 1. Start Tomcat 2. Call the servlet as follows [Link]

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

25.

Write a program to demonstrate the concept of WindowListener.

Program: //[Link] import [Link].*; import [Link].*; class WindowListenerDemo extends Frame implements WindowListener { WindowListenerDemo() { addWindowListener(this); setSize(200,200); setVisible(true); } public void windowOpened(WindowEvent we) { [Link]("opened"); } public void windowActivated(WindowEvent we) { [Link]("activated"); } public void windowDeactivated(WindowEvent we) { [Link]("deactivated"); } public void windowIconified(WindowEvent we) { [Link]("iconified"); } public void windowDeiconified(WindowEvent we) { [Link]("deiconified"); } public void windowClosing(WindowEvent we) { [Link]("closing"); [Link](0); } public void windowClosed(WindowEvent we) { [Link]("closed"); } public static void main(String ar[]) { new WindowListenerDemo(); }}

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

Output: Compile: javac [Link] Run: java WindowListenerDemo activated opened

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

26.

Write a program to demonstrate the concept of ActionListener.

Program: //[Link] import [Link].*; import [Link].*; class ActionListenerDemo extends Frame implements ActionListener { Button b1, b2, b3, b4; ActionListenerDemo() { b1 = new Button("RED"); b2 = new Button("BLUE"); b3 = new Button("CYAN"); b4 = new Button("EXIT"); setLayout(new FlowLayout()); add(b1); add(b2); add(b3); add(b4); [Link](this); [Link](this); [Link](this); [Link](this); setSize(400,400); setVisible(true); }//construcotr public void actionPerformed(ActionEvent ae) { if([Link]().equals(b1)) { setBackground([Link]); }else if([Link]().equals(b2)) { setBackground([Link]); } else if([Link]().equals(b3)) { setBackground([Link]); } else { [Link](0); } }

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

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

Output: Compile: javac [Link] Run: java ActionListenerDemo

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

27.

Write a program to demonstrate the concept of MouseListener.

Program: import [Link].*; import [Link].*; /* <applet code="MouseEvents" width=300 height=100> </applet> */ public class MouseEvents extends Applet implements MouseListener { String msg = ""; int mouseX = 0, mouseY = 0; // coordinates of mouse public void init() { addMouseListener(this); } // Handle mouse clicked. public void mouseClicked(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse clicked."; repaint(); } // Handle mouse entered. public void mouseEntered(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse entered."; repaint(); } // Handle mouse exited. public void mouseExited(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse exited."; repaint(); } // Handle button pressed. public void mousePressed(MouseEvent me) { // save coordinates mouseX = [Link](); mouseY = [Link](); msg = "Down";

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

repaint(); } // Handle button released. public void mouseReleased(MouseEvent me) { // save coordinates mouseX = [Link](); mouseY = [Link](); msg = "Up"; repaint(); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { [Link](msg, mouseX, mouseY); } }

Output: Compile: javac [Link] Run: java MouseEvents

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

28.

Write a code to print date using JSP.

Code: <HTML> <HEAD> <TITLE>Date in jsp</TITLE> </HEAD> <BODY> <H3 ALIGN="CENTER"> CURRENT DATE <FONT COLOR="RED"> <%=new [Link]() %> </FONT> </H3> </BODY> </HTML> Output:

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

29.

Write a code for random number generator using JSP.

Code: <html> <HEAD> <TITLE>Random in jsp</TITLE> </HEAD> <BODY> <H3 ALIGN="CENTER"> Ramdom number from 10 to 100 : <FONT COLOR="RED"> <%= (int) ([Link]() * 100) %> </FONT> </H3> <H4 ALIGN="">Refresh the page to see the next number.</H4> </BODY> </HTML> Output:

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

30.

Write a program of servlet for handling cookies.

Program: import [Link].*; import [Link].*; import [Link].*; public class CookieExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { [Link]("text/html"); PrintWriter out = [Link](); // print out cookies Cookie[] cookies = [Link](); for (int i = 0; i < [Link]; i++) { Cookie c = cookies[i]; String name = [Link](); String value = [Link](); [Link](name + " = " + value); } // set a cookie String name = [Link]("cookieName"); if (name != null && [Link]() > 0) { String value = [Link]("cookieValue"); Cookie c = new Cookie(name, value); [Link](c); } } } Output:

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

31.

Write a program for text processing using regular expressions.

Program: import [Link].*; public class EmailValidator { public static void main(String[] args) { String email=""; if([Link] < 1) { [Link]("Command syntax: java EmailValidator <emailAddress>"); [Link](0); } else { email = args[0]; } //Look for for email addresses starting with //invalid symbols: dots or @ signs. Pattern p = [Link]("^\\.+|^\\@+"); Matcher m = [Link](email); if ([Link]()) { [Link]("Invalid email address: starts with a dot or an @ sign."); [Link](0); } //Look for email addresses that start with www. p = [Link]("^www\\."); m = [Link](email); if ([Link]()) { [Link]("Invalid email address: starts with www."); [Link](0); } p = [Link]("[^A-Za-z0-9\\@\\.\\_]"); m = [Link](email); if([Link]()) { [Link]("Invalid email address: contains invalid characters"); } else
BIT-282JAVA PROGRAMMING & WT LAB [Link] Ali (1604-10-737-048) PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

{ [Link](args[0] + " is a valid email address."); } } }

Output: Compile: javac [Link] Run: java EmailValidator abc@[Link] abc@[Link] is a valid email address.

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

32.

Write a servlet program to print a message Hello World.

Program: import [Link].*; import [Link].*; import [Link].*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { [Link]("text/html"); PrintWriter out = [Link](); [Link]("<html><body><h1>HELLO WORLD!</h1></body></html>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } } Deployment Descriptor - [Link] <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="[Link] xmlns:xsi="[Link] xsi:schemaLocation="[Link] [Link] version="2.5"> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app> Output:

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

M.J.C.E.T., HYD - 34

BIT-282JAVA PROGRAMMING & WT LAB

[Link] Ali (1604-10-737-048)

PAGE NO:

You might also like