java programs
-
Upload
mahek-fatima -
Category
Documents
-
view
78 -
download
7
description
Transcript of java programs
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 : " + areaInFirstConstructor);Rectangle rectangle2=new Rectangle(5);int areaInSecondConstructor=rectangle2.second();System.out.println(" The area of a rectangle in first constructor is : " + areaInSecondConstructor);Rectangle rectangle3=new Rectangle(2.0f);float areaInThirdConstructor=rectangle3.third();System.out.println(" The area of a rectangle in first constructor is : " + areaInThirdConstructor); Rectangle rectangle4=new Rectangle(3.0f,2.0f);float areaInFourthConstructor=rectangle4.fourth();System.out.println(" The area of a rectangle in first constructor is : " + areaInFourthConstructor);}}
Output:Compile: javac ConstructorOverload.javaRun: java ConstructorOverload
The area of a rectangle in first constructor is : 8The area of a rectangle in first constructor is : 25The area of a rectangle in first constructor is : 4.0The area of a rectangle in first constructor is : 6.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
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 parameterdouble 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.javaRun: java MethodOverload
No parametersa: 10a and b: 10 20double a: 123.25Result 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 objectBox(Box ob) { // pass object to constructorwidth = ob.width;height = ob.height;depth = ob.depth;}// constructor used when all dimensions specifiedBox(double w, double h, double d) {width = w;height = h;depth = d;}// constructor used when no dimensions specifiedBox() {width = -1; // use -1 to indicateheight = -1; // an uninitializeddepth = -1;} // box// constructor used when cube is createdBox(double len) {width = height = depth = len;}// compute and return volumedouble volume() {return width * height * depth;}}// Here, Box is extended to include weight.class BoxWeight extends Box {double weight; // weight of box// constructor for BoxWeightBoxWeight(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.javaRun: java DemoBoxWeight
Volume of mybox1 is 3000.0Weight of mybox1 is 34.3
Volume of mybox2 is 24.0Weight 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 objectBox(Box ob) { // pass object to constructorwidth = ob.width;height = ob.height;depth = ob.depth;}// constructor used when all dimensions specifiedBox(double w, double h, double d) {width = w;height = h;depth = d;}// constructor used when no dimensions specifiedBox() {width = -1; // use -1 to indicateheight = -1; // an uninitializeddepth = -1; // box}// constructor used when cube is createdBox(double len) {width = height = depth = len;}// compute and return volumedouble volume() {return width * height * depth;}}// Add weight.Class BoxWeight extends Box {double weight; // weight of box// construct clone of an objectBoxWeight(BoxWeight ob) { // pass object to constructorsuper(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 specifiedBoxWeight(double w, double h, double d, double m) {super(w, h, d); // call superclass constructorweight = m;}// default constructorBoxWeight() {super();weight = -1;}
// constructor used when cube is createdBoxWeight(double len, double m) {super(len);weight = m;}}// Add shipping costsclass Shipment extends BoxWeight {double cost;// construct clone of an objectShipment(Shipment ob) { // pass object to constructorsuper(ob);cost = ob.cost;}// constructor when all parameters are specifiedShipment(double w, double h, double d,double m, double c) {super(w, h, d, m); // call superclass constructorcost = c;}// default constructorShipment() {super();cost = -1;}// constructor used when cube is createdShipment(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.javaRun: java DemoShipment
Volume of shipment1 is 3000.0Weight of shipment1 is 10.0Shipping cost: $3.41
Volume of shipment2 is 24.0Weight of shipment2 is 0.76Shipping 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 AB b = new B(); // object of type BC c = new C(); // object of type CA r; // obtain a reference of type Ar = a; // r refers to an A objectr.callme(); // calls A's version of callmer = b; // r refers to a B objectr.callme(); // calls B's version of callmer = c; // r refers to a C objectr.callme(); // calls C's version of callme}}
Output:Compile: javac Dispatch.javaRun: java Dispatch
Inside A's callme methodInside B's callme methodInside 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 methodabstract double area();}class Rectangle extends Figure {Rectangle(double a, double b) {super(a, b);}// override area for rectangledouble 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 triangledouble 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 nowRectangle r = new Rectangle(9, 5);Triangle t = new Triangle(10, 8);Figure figref; // this is OK, no object is createdfigref = 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.javaRun: java AbstractAreas
Inside Area for Rectangle.Area is 45.0Inside 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 threadsuper("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 threadtry {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.javaRun: 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: 5Child Thread: 5Child Thread: 4Main Thread: 4Child Thread: 3Child Thread: 2Child Thread: 1Main Thread: 3Exiting child thread.Main Thread: 2Main Thread: 1Main 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 threadt = 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 threadtry {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.javaRun: 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: 5Child Thread: 5Child Thread: 4Main Thread: 4Child Thread: 3Child Thread: 2Main Thread: 3Child Thread: 1Exiting child thread.Main Thread: 2Main Thread: 1Main 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 threadThread 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 finishtry {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.javaRun: java MultiThreadDemo
New thread: Thread[One,5,main]New thread: Thread[Two,5,main]One: 5New thread: Thread[Three,5,main]Thread One is alive: trueTwo: 5Thread Two is alive: trueThree: 5Thread Three is alive: trueWaiting for threads to finish.One: 4Three: 4Two: 4One: 3Three: 3Two: 3One: 2Three: 2Two: 2One: 1Three: 1Two: 1One exiting.Two exiting.Three exiting.Thread One is alive: falseThread Two is alive: falseThread Three is alive: falseMain 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 blocktarget.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 endtry {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.javaRun: 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.javaRun: java PCFixed
Put: 1 Got: 1Put: 2Got: 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.javaRun: java StringTokenizing
The total no. of tokens generated : 5Youaretokenizingastring
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");elsestck[++tos]=item;}public int pop(){if(tos==-1){System.out.println("There is nothing to PoP");return 0;}elsereturn 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.javaRun: java StackTest
Start Push Objects in StackThe stack has over flowThe 5 element in stack 1 is 8 The 5 element in stack 2 is 12The 4 element in stack 1 is 6 The 4 element in stack 2 is 9The 3 element in stack 1 is 4 The 3 element in stack 2 is 6The 2 element in stack 1 is 2 The 2 element in stack 2 is 3The 1 element in stack 1 is 0 The 1 element in stack 2 is 0There is nothing to PoPThe 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 listArrayList al = new ArrayList();System.out.println("Initial size of al: " +al.size());// add elements to the array listal.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 listSystem.out.println("Contents of al: " + al);// Remove elements from the array listal.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.javaRun: java ArrayListDemo
Initial size of al: 0Size of al after additions: 7Contents of al: [C, A2, A, E, B, D, F]Size of al after deletions: 5Contents 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 listArrayList al = new ArrayList();// add elements to the array listal.add("C");al.add("A");al.add("E");al.add("B");al.add("D");al.add("F");// use iterator to display contents of alSystem.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 iteratedListIterator 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 backwardsSystem.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.javaRun: java IteratorDemo
Original contents of al: C A E B D FModified 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.javaRun: java FilterFiles
Please enter the directory name :E:\Java Pgms\Please enter file type :javaAbstractAreas.javaArrayListDemo.javaConstructorOverload.javaCOverload.javaDemoBoxWeight.javaDemoShipment.javaDispatch.javaemp.javaExtendThread.javaFilterFiles.javaHashSetDemo.javaIFStack.javaIteratorDemo.javaMethodOverload.javaMultiThreadDemo.javaSInheritanceEx.javaStringTokenizing.javaSynch1.javaTestStack.javaThreadDemo.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.javaRun: java readWriteData
write DataRead DataEnter your choice1write successfully128132950
write DataRead Data
Enter your choice2128132950
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 LAB- B2<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.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: <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 & 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.xmlThe output is as follows.
19. Write a program to create a database using Jdbc.
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:
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.
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:
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= sakinarollno=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 ResultSetres.next(); String firstName = res.getString("FirstName"); String lastName = res.getString("LastName");System.out.println("User ID 2: "+firstName+' '+lastName); // Close ResultSet and PreparedStatementres.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
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) browser-
Program: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.ujavaimport 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 Tomcat2. Call the servlet as followshttp://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.javaimport 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");}
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 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.javaimport 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);}//construcotrpublic 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
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 void init() {addMouseListener(this);
}// Handle mouse clicked.public void mouseClicked(MouseEvent me) {// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse clicked.";repaint();}// Handle mouse entered.public void mouseEntered(MouseEvent me) {// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse entered.";repaint();}// Handle mouse exited.public void mouseExited(MouseEvent me) {// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse exited.";repaint();}// Handle button pressed.public void mousePressed(MouseEvent me) {// save coordinatesmouseX = me.getX();mouseY = me.getY();msg = "Down";
repaint();}// Handle button released.public void mouseReleased(MouseEvent me) {// save coordinatesmouseX = me.getX();mouseY = me.getY();msg = "Up";repaint();}// Display msg in applet window at current X,Y location.public void paint(Graphics g) {
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
g.drawString(msg, mouseX, mouseY);}}
Output:Compile: javac MouseEvents.java Run: java MouseEvents
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">
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
<%=new java.util.Date() %></FONT></H3></BODY></HTML>
Output:
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) %>
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
</FONT></H3><H4 ALIGN="">Refresh the page to see the next number.</H4></BODY></HTML>
Output:
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 {
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
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.");
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.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 {System.out.println(args[0] + " is a valid email address."); } }}
Output:Compile: javac EmailValidator.javaRun: java EmailValidator [email protected]@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
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/web-app_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:
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: