Vous êtes sur la page 1sur 62

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=rectangle1.first();

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

System.out.println(" The area of a rectangle in first constructor is : Rectangle rectangle2=new Rectangle(5); int areaInSecondConstructor=rectangle2.second(); System.out.println(" The area of a rectangle in first constructor is : Rectangle rectangle3=new Rectangle(2.0f); float areaInThirdConstructor=rectangle3.third(); System.out.println(" The area of a rectangle in first constructor is : Rectangle rectangle4=new Rectangle(3.0f,2.0f); float areaInFourthConstructor=rectangle4.fourth(); System.out.println(" The area of a rectangle in first constructor is : } } Output: Compile: javac ConstructorOverload.java 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

Md.Arif 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() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("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() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } Output: Compile: javac MethodOverload.java Run: java MethodOverload No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 = ob.width; height = ob.height; depth = ob.depth; } // 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

Md.Arif 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 = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } } Output: Compile: javac DemoBoxWeight.java 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

Md.Arif 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 = ob.width; height = ob.height; depth = ob.depth; } // 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 = ob.weight; }

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 = ob.cost; } // 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 Md.Arif 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 = shipment1.volume(); System.out.println(Volume of shipment1 is + vol); System.out.println(Weight of shipment1 is + shipment1.weight); System.out.println(Shipping cost: $ + shipment1.cost); System.out.println(); vol = shipment2.volume(); System.out.println(Volume of shipment2 is + vol); System.out.println(Weight of shipment2 is + shipment2.weight); System.out.println(Shipping cost: $ + shipment2.cost); } } Output: Compile: javac DemoShipment.java 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

Md.Arif 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() { System.out.println("Inside A's callme method"); } } class B extends A { // override callme() void callme() { System.out.println("Inside B's callme method"); } } class C extends A { // override callme() void callme() { System.out.println("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 r.callme(); // calls A's version of callme r = b; // r refers to a B object r.callme(); // calls B's version of callme r = c; // r refers to a C object r.callme(); // calls C's version of callme } } Output: Compile: javac Dispatch.java Run: java Dispatch Inside A's callme method Inside B's callme method Inside C's callme method

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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() { System.out.println("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() { System.out.println("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; System.out.println("Area is " + figref.area()); figref = t;

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

System.out.println("Area is " + figref.area()); } } Output: Compile: javac AbstractAreas.java Run: java AbstractAreas Inside Area for Rectangle. Area is 45.0 Inside Area for Triangle. Area is 40.0

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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"); System.out.println("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--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("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--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } Output: Compile: javac ExtendThread.java Run: java ExtendThread

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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

Md.Arif 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"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("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--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } Output: Compile: javac ThreadDemo.java Run: java ThreadDemo

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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

Md.Arif 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); System.out.println("New thread: " + t); t.start(); // Start the thread } // This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(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"); System.out.println("Thread One is alive: " + ob1.t.isAlive()); System.out.println("Thread Two is alive: " + ob2.t.isAlive()); System.out.println("Thread Three is alive: " + ob3.t.isAlive()); // wait for threads to finish try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch (InterruptedException e) {

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

System.out.println("Main thread Interrupted"); } System.out.println("Thread One is alive: "+ ob1.t.isAlive()); System.out.println("Thread Two is alive: "+ ob2.t.isAlive()); System.out.println("Thread Three is alive: "+ ob3.t.isAlive()); System.out.println("Main thread exiting."); } } Ouput: Compile: javac MultiThreadDemo.java 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 Md.Arif 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) { 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(); } // synchronize calls to call() public void run() { synchronized(target) { // synchronized block 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"); // wait for threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join();

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

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

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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) { System.out.println("InterruptedException caught"); } System.out.println("Got: " + n); valueSet = false; notify(); return n; } synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } this.n = n; valueSet = true; System.out.println("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) { q.put(i++);

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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) { q.get(); } } } class PCFixed { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } } Output: Compile: javac PCFixed.java 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

Md.Arif 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 java.util.*; public class StringTokenizing{ public static void main(String[] args) { StringTokenizer stringTokenizer = new StringTokenizer("You are tokenizing a string"); System.out.println("The total no. of tokens generated : " + stringTokenizer.countTokens()); while(stringTokenizer.hasMoreTokens()){ System.out.println(stringTokenizer.nextToken()); } } } Output: Compile: javac StringTokenizing.java Run: java StringTokenizing The total no. of tokens generated : 5 You are tokenizing a string

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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==stck.length-1) System.out.println("The stack has over flow"); else stck[++tos]=item; } public int pop(){ if(tos==-1){ System.out.println("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); System.out.println("Start Push Objects in Stack"); for(int i=0;i<5;i++) Stack1.push(2*i); for(int i=0;i<6;i++) Stack2.push(3*i); for(int i=0;i<6;i++) { System.out.print("The "+(5-i)+" element in stack 1 is "+Stack1.pop());

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

System.out.print("\t The "+(5-i)+" element in stack 2 is "+Stack2.pop()+"\n"); } } } Output: Compile: javac StackTest.java 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

Md.Arif 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 java.util.*; class ArrayListDemo { public static void main(String args[]) { // create an array list ArrayList al = new ArrayList(); System.out.println("Initial size of al: " +al.size()); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " +al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove elements from the array list al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " +al.size()); System.out.println("Contents of al: " + al); } } Output: Compile: javac ArrayListDemo.java 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

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

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

DEPARTMENT OF INFORMATION TECHNOLOGY

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

System.out.println(); } } Output: Compile: javac IteratorDemo.java 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

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

c)HashSet Program: import java.util.*; class HashSetDemo { public static void main(String args[]) { HashSet hs=new HashSet(); hs.add("A"); hs.add("D"); Iterator i=hs.iterator(); while(i.hasNext()) { System.out.println(i.next()); } } }

Output: Compile: HashSetDemo.java Run: java HashSetDemo D A

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

d)TreeMap Program: import java.util.*; class TreeMapDemo { public static void main(String args[]) { TreeMap tm=new TreeMap(); tm.put("John",new Integer(5)); tm.put("Robin",new Integer(10)); tm.put("Stephen",new Integer(15)); Set se=tm.entrySet(); Iterator i=se.iterator(); while(i.hasNext()) { Map.Entry me=(Map.Entry)i.next(); System.out.println(me.getKey()+":"); System.out.println(me.getValue()); } System.out.println(); } } Output: Compile: javac TreeMapDemo.java Run: java TreeMapDemo John: 5 Robin: 10 Stephen: 15

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 java.util.*; // 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 bStr.compareTo(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 ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); // Get an iterator Iterator i = ts.iterator(); // Display elements while(i.hasNext()) { Object element = i.next(); System.out.print(element + " "); } System.out.println(); } } Output: Compile: javac CompDemo.java Run: java CompDemo F E D C B A

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

f)LinkedList Program: import java.util.*; class LinkedListDemo { public static void main(String args[]) { LinkedList ll=new LinkedList(); ll.add("A"); ll.add("B"); ll.add("C"); Iterator i=ll.iterator(); while(i.hasNext()) { System.out.println(i.next()); } } }

Output: Compile: javac LinkedListDemo.java Run: java LinkedListDemo

A B C

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 java.io.*; class OnlyExt implements FilenameFilter{ String ext; public OnlyExt(String ext){ this.ext="." + ext; } public boolean accept(File dir,String name){ return name.endsWith(ext); } }

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

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

Output: Compile: javac FilterFiles.java Run: java FilterFiles

Please enter the directory name : E:\Java Pgms\ Please enter file type : java AbstractAreas.java ArrayListDemo.java ConstructorOverload.java COverload.java DemoBoxWeight.java DemoShipment.java Dispatch.java emp.java ExtendThread.java FilterFiles.java HashSetDemo.java IFStack.java IteratorDemo.java MethodOverload.java MultiThreadDemo.java SInheritanceEx.java StringTokenizing.java Synch1.java TestStack.java ThreadDemo.java

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

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

DEPARTMENT OF INFORMATION TECHNOLOGY

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

catch (Exception e) { } } } Output: Compile: javac ReadWriteData.java 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

Md.Arif 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

Md.Arif 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.


Md.Arif 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"} document.write(personObj.firstname + " is " + personObj.age + " years old."); </script> </body> </html> Output: John is 50 years old

18.

Publishing XML document using XSLT

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

Program: XSL File: layout.xsl <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 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: Page1.xml


BIT-282JAVA PROGRAMMING & WT LAB Md.Arif 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="layout.xsl"?> <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 Page1.xml The output is as follows.

19.

Write a program to create a database using Jdbc.


Md.Arif 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 java.sql.*; public class OdbcAccessCreateTable { public static void main(String [] args) { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:HY_ACCESS"); // Creating a database table Statement sta = con.createStatement(); int count = sta.executeUpdate("CREATE TABLE HY_Address (ID INT, StreetName VARCHAR(20),"+ " City VARCHAR(20))"); System.out.println("Table created."); sta.close(); con.close(); } catch (Exception e) { System.err.println("Exception: "+e.getMessage()); } } }

Output: Table created.

20.

Write a program to execute a statement query using Jdbc.


Md.Arif 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 java.sql.*; public class DbConnect { public static void main(String a[]) throws Exception { Connection con; Statement st; ResultSet rs; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //String dsn="datasource1"; //String url="Jdbc:Odbc"+ dsn; con=DriverManager.getConnection("Jdbc:Odbc:dsn1"); st=con.createStatement(); rs=st.executeQuery("SELECT * FROM Table1"); while(rs.next()) { System.out.println("\nname=\t "+rs.getString(1)+"\nrollno=\t ="+rs.getInt(2)); } } }

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

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 java.sql.*; public class SqlServerPreparedSelect { public static void main(String [] args) { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:HY_ACCESS"); // PreparedStatement for SELECT statement PreparedStatement sta = con.prepareStatement("SELECT * FROM Profile WHERE ID = 2"); // Execute the PreparedStatement as a query ResultSet res = sta.executeQuery(); // Get values out of the ResultSet res.next(); String firstName = res.getString("FirstName"); String lastName = res.getString("LastName"); System.out.println("User ID 2: "+firstName+' '+lastName); // Close ResultSet and PreparedStatement res.close(); con.close(); } catch (Exception e) { System.err.println("Exception: "+e.getMessage()); } } }

Output: User ID 2: Anas Jabri

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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=document.forms["contact_form"]["email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { 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

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

Output:

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 java.awt.*; import java.applet.*; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world", 20, 20); } } Output:

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

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

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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: CountServlet.ujava import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CheckingTheSession extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Checking whether the session is new or old<br>"); HttpSession session = request.getSession(); if(session.isNew()){ pw.println("You have created a new session"); } else{ pw.println("Session already exists"); } } } Deployment Descriptor: web.xml <?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

Md.Arif 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 http://localhost:8080/Vani/CheckingTheSession

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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: //WindowListenerDemo.java import java.awt.*; import java.awt.event.*; class WindowListenerDemo extends Frame implements WindowListener { WindowListenerDemo() { addWindowListener(this); setSize(200,200); setVisible(true); } public void windowOpened(WindowEvent we) { System.out.println("opened"); } public void windowActivated(WindowEvent we) { System.out.println("activated"); } public void windowDeactivated(WindowEvent we) { System.out.println("deactivated"); } public void windowIconified(WindowEvent we) { System.out.println("iconified"); } public void windowDeiconified(WindowEvent we) { System.out.println("deiconified"); } public void windowClosing(WindowEvent we) { System.out.println("closing"); System.exit(0); } public void windowClosed(WindowEvent we) { System.out.println("closed"); } public static void main(String ar[]) { new WindowListenerDemo(); }}

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

Output: Compile: javac WindowListenerDemo.java Run: java WindowListenerDemo activated opened

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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: //ActionListenerDemo.java import java.awt.*; import java.awt.event.*; 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); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); setSize(400,400); setVisible(true); }//construcotr public void actionPerformed(ActionEvent ae) { if(ae.getSource().equals(b1)) { setBackground(Color.red); }else if(ae.getSource().equals(b2)) { setBackground(Color.BLUE); } else if(ae.getSource().equals(b3)) { setBackground(Color.cyan); } else { System.exit(0); } }

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 ActionListenerDemo.java Run: java ActionListenerDemo

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 java.awt.event.*; import java.applet.*; /* <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 = me.getX(); mouseY = me.getY(); msg = "Down";

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 = me.getX(); mouseY = me.getY(); msg = "Up"; repaint(); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } }

Output: Compile: javac MouseEvents.java Run: java MouseEvents

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 java.util.Date() %> </FONT> </H3> </BODY> </HTML> Output:

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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) (Math.random() * 100) %> </FONT> </H3> <H4 ALIGN="">Refresh the page to see the next number.</H4> </BODY> </HTML> Output:

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CookieExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); // print out cookies Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; String name = c.getName(); String value = c.getValue(); out.println(name + " = " + value); } // set a cookie String name = request.getParameter("cookieName"); if (name != null && name.length() > 0) { String value = request.getParameter("cookieValue"); Cookie c = new Cookie(name, value); response.addCookie(c); } } } Output:

BIT-282JAVA PROGRAMMING & WT LAB

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

DEPARTMENT OF INFORMATION TECHNOLOGY

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

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

Output: Compile: javac EmailValidator.java Run: java EmailValidator abc@yahoo.com abc@yahoo.com is a valid email address.

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif 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 java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body><h1>HELLO WORLD!</h1></body></html>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } } Deployment Descriptor - web.xml <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" 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

Md.Arif Ali (1604-10-737-048)

PAGE NO:

DEPARTMENT OF INFORMATION TECHNOLOGY

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

BIT-282JAVA PROGRAMMING & WT LAB

Md.Arif Ali (1604-10-737-048)

PAGE NO:

Vous aimerez peut-être aussi