You are on page 1of 81

/* Write a Java program to Illustrate a concept of class box with constructor.

*/ class Box { private double length; double breadth; Box() { System.out.println("From default Constructor"); length=0; breadth=0; } Box(double l,double b) { System.out.println("From Parameterised"); length=l; breadth=b; } Box(Box b) { System.out.println("using Copy Constructor"); this.length=b.length; this.breadth=b.breadth; } void set_dimensions(double c,double d) { length=c; breadth=d; } double area() { return length*breadth; } double perimeter() { return (2*(length+breadth));

Page No. 1

} } class BoxDemo { public static void main(String args[]) { Box mybox1=new Box(); mybox1.set_dimensions(10.25,20.35); System.out.println("Area of a MyBox1 is:"+mybox1.area()); System.out.println("Perimeter of a MyBox1 is:"+mybox1.perimeter()); Box mybox2=new Box(10.25,15.75); System.out.println("Area of a MyBox2 is:"+mybox2.area()); System.out.println("Perimeter of a MyBox2 is:"+mybox2.perimeter()); Box mybox3=new Box(mybox2); System.out.println("Area of a MyBox3 is:"+mybox3.area()); System.out.println("Perimeter of a MyBox3 is:"+mybox3.perimeter()); } }

Page No. 2

OUTPUT: From default Constructor Area of a MyBox1 is:208.5875 Perimeter of a MyBox1 is:61.2 From Parameterised Area of a MyBox2 is:161.4375 Perimeter of a MyBox2 is:52.0 using Copy Constructor Area of a MyBox3 is:161.4375 Perimeter of a MyBox3 is:52.0

Page No. 3

// Write a Java Program to demonstrate Method Overloading. class Value { int arr[]={1,7,90,3,67}; void max_min(int v) { System.out.println("The maximum & minimum Values are same:"+v); } void max_min(int v1,int v2) { if(v1>v2) { System.out.println("The Max is"+v1); System.out.println("The Min is"+v2); } else { System.out.println("The Max is:"+v2); System.out.println("The Min is:"+v1); } } void max_min(int v1,int v2,int v3) { if((v1>v2)&&(v1>v3)) { System.out.println("The Maximun is:"+v1); } else if(v2>v3) System.out.println("The Maximun is :"+v2); else System.out.println("The Maximum is :"+v3); if((v1<v2)&&(v1<v3)) System.out.println("The Minimum is:"+v1); else if(v2<v3) System.out.println("The Minimum is:"+v2); else System.out.println("The Minimum is:"+v3); }

Page No. 4

void max_min(int arr[]) { for(int i=0;i<=4;i++) { for(int j=i+1;j<5;j++) { if(arr[i]>arr[j]) { int temp; temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } System.out.println("The Minimum is:"+arr[0]); System.out.println("The Maximum is:"+arr[4]); } } class Maxmin { public static void main(String args[]) { Value v=new Value(); v.max_min(10); v.max_min(20,10); v.max_min(20,10,30); System.out.println("The Max & Min of a given array of Elements is:" ); v.max_min(v.arr); } }

Page No. 5

OUTPUT: The The The The The The The The

maximum & minimum Values are same:10 Max is20 Min is10 Maximum is :30 Minimum is:10 Max & Min of a given array of Elements is: Minimum is:1 Maximum is:90

Page No. 6

// Write a Java Program to demonstrate Inheritence. class Person { String name; int age; Person(String si,int age) { name=si; this.age=age; } } //Person Class class Student extends Person { int rollnumber; Student(String s1,int age,int rollnumber) { super(s1,age); this.rollnumber=rollnumber; } } // Student class class Ugstudent extends Student { int marks; Ugstudent(String s2,int age,int rollnumber,int marks) { super(s2,age,rollnumber); this.marks=marks; } void display() { System.out.println("\n Ug Student Details"); System.out.println("\n Name:"+name+"\n Age:"+age+"\n Roll Number:"+rollnumber+"\n Marks:"+marks); } } //Ug Class class Pgstudent extends Student { int markspg;

Page No. 7

Pgstudent(String s3,int age,int rollnumber,int markspg) { super(s3,age,rollnumber); this.markspg=markspg; } void display() { System.out.println("\n Pg Student Details"); System.out.println("\n Name"+name+"\n Age:"+age+"\n Rollno:"+rollnumber+"\n Marks PG:"+markspg); } }// Pg Class class Multy { public static void main(String args[]) { Ugstudent ug=new Ugstudent("Hari",23,32,789); ug.display(); Pgstudent pg=new Pgstudent("Ram",25,47,456); pg.display(); } } //Multi Class

Page No. 8

OUTPUT: Ug Student Details Name:Hari Age:23 Roll Number:3 Marks:789 Pg Student Details NameRam Age:25 Rollno:47 Marks PG:456

Page No. 9

//Write a Java Program to demonstrate Dynamic Polymorphism. class Animal { public void eat() { System.out.println("Every Animals eats to live"); } } // Animal Class class Elephant extends Animal { public void eat() { System.out.println("Elephant eats Leaves"); } } // Elephant Class class Lion extends Animal { public void eat() { System.out.println("Lion eats Flesh"); } }// Lion Class class DynamicDispatch { public static void main(String args[]) { Animal a1=new Animal(); a1.eat(); Elephant e1=new Elephant(); a1=e1; a1.eat(); Lion l1=new Lion(); a1=l1; a1.eat(); } } //DynamicDispatch Class

Page No. 10

OUTPUT: Every Animals eats to live Elephant eats Leaves Lion eats Flesh

Page No. 11

//Program to implement the following Hierarchy and find area abstract class Shape { double a,b; final double PI=3.14156; Shape(double a) { this.a=a; } Shape(double a,double b) { this.a=a; this.b=b; } abstract double area(); } class Square extends Shape { Square(double a) { super(a); } double area() { return a*a; } } class Triangle extends Shape { Triangle(double a,double b) { super(a,b); } double area() { return(a*b)/2; } } class Circle extends Shape

Page No. 12

{ Circle(double a) { super(a); } double area() { return PI*a*a; } } class HierarchyDemo { public static void main(String args[]) { Square s=new Square(10.5); System.out.println("the area of square is:"+s.area()); Triangle t=new Triangle(20.25,30.15); System.out.println("the area of triangle is:"+t.area()); Circle c=new Circle(15.75); System.out.println("the area of circle is:"+c.area()); } }

Page No. 13

OUTPUT: The area of square is:110.25 The area of triangle is:305.26875 The Area of circle is:779.3032275

Page No. 14

/*Write a Java program to implement an Animal Abstract class.*/ abstract class Animal { public void eat() { System.out.println("Om nom nom, food is delicious!"); } public abstract void speak(); } class Cat extends Animal { public void speak() { System.out.println("Meow!"); } } class Dog extends Animal { public void speak() { System.out.println("Bark! Bark!"); } } class AbstractDemo { public static void main(String args[]) { Animal a= new Cat(); a.speak(); Animal a1 = new Dog(); a1.speak(); } }

Page No. 15

OUTPUT: Meow! Bark! Bark!

Page No. 16

//Program on multithreading by using runnable interface class Critical { public void m1() { System.out.println("entered m1"); try { Thread.sleep(2000); } catch(InterruptedException ie) { ie.printStackTrace(); } System.out.println("exit m1"); } public void m2() { System.out.println("entered m2"); try { Thread.sleep(2000); } catch(InterruptedException ie) { ie.printStackTrace(); } System.out.println("exit m2"); } } class Runnable1 implements Runnable { Critical c; Runnable1(Critical c1) { c=c1; } public void run() {

Page No. 17

c.m1(); } } class Runnable2 implements Runnable { Critical c; Runnable2(Critical c1) { c=c1; } public void run() { c.m2(); } } class TestCritical { public static void main(String args[]) { Critical c1=new Critical(); Runnable1 r1=new Runnable1(c1); Runnable2 r2=new Runnable2(c1); Thread t1=new Thread(r1); Thread t2=new Thread(r2); t1.start(); t2.start(); } }

Page No. 18

OUTPUT:entered m1 entered m2 exit m1 exit m2

Page No. 19

//Write a Java program on multithreading by using the thread class. class NewThread extends Thread { NewThread() { super("Demo Thread"); System.out.println("Child thread: " + this); start(); } 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(); try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000);

Page No. 20

} } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }

Page No. 21

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

Page No. 22

/*Write a Java program to demonstrate the concept of synchronization by using Bank Account class.*/ public class { Deposit static int bal=1000; public static void main(String[] args) { Account ac=new Account(); DepositThread first,second; first=new DepositThread(ac,1000,"#1"); second=new DepositThread(ac,1000,"#2"); first.start(); second.start(); try{ first.join(); second.join(); } catch(InterruptedException e) { } System.out.println("final balance"+bal); } } class Account { synchronized void deposit(int amount,String name) { int bal; System.out.println(name+"trying to deposite"+amount); System.out.println(name+"getting balance"); bal=getBalance(); System.out.println(name+"got balance"+bal);

Page No. 23

bal+=amount; System.out.println(name+"setting balance"); setBalance(bal); System.out.println(name+"new balance"+Deposit.bal); } int getBalance() { return Deposit.bal;} void setBalance(int bal) { Deposit.bal=bal; } } class DepositThread extends Thread { Account ac; String msg; int depamt; DepositThread(Account ac,int amt,String msg) { this.ac=ac; this.depamt=amt; this.msg=msg; } public void run() { ac.deposit(depamt,msg); } }

Page No. 24

OUTPUT: #1trying to deposite1000 #1getting balance #1got balance1000 #1setting balance #1new balance2000 #2trying to deposite1000 #2getting balance #2got balance2000 #2setting balance #2new balance3000 final balance3000

Page No. 25

// Program to implement producers-consumer problem class communicate { public static void main(String[] args)throws Exception { //producer produces some data which consumer consumes producer obj1=new producer(); //pass producer object to consumer so that it is then available to consumer Consumer obj2=new Consumer(obj1); //create 2 threads and attach to producer and consumer Thread t1=new Thread(obj1); Thread t2=new Thread(obj2); //run the threads t2.start(); t1.start(); } } class producer extends Thread { //to add data,we use string buffer object StringBuffer sb; producer() { sb=new StringBuffer(); } public void run() { synchronized(sb) { //go on appending data (numbers)to string buffer for(int i=1;i<=10;i++) { try{

Page No. 26

sb.append(i+":"); Thread.sleep(100); System.out.println("appending"); }catch(Exception e){} } //data production is over,so notify to consumer thread sb.notify(); } } } class Consumer extends Thread { //create producer reference to refer to producer object from consuner class producer prod; Consumer(producer prod) { this.prod=prod; } public void run() { synchronized(prod.sb) { //wait till a notification is recieved from the producer //Thread.hear(); //there is no wastage of time of even a single millisecond try{ prod.sb.wait(); }catch(Exception e){} //when data production is over ,display data of stringbuffer

Page No. 27

System.out.println(prod.sb); } } }

Page No. 28

OUTPUT: c:\>java Communicate appending appending appending appending appending appending appending appending appending appending 1:2:3:4:5:6:7:8:9:10:

Page No. 29

// Program to Demonstrate String Tokenizer import java.util.*; public class StringTokenizerDemo { public static void main(String args[]) { String str1="hello world; how,do you/do, all are/ok; thank/you"; StringTokenizer st=new StringTokenizer(str1,",;/"); System.out.println("Number of tokens:"+st.countTokens()); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); } } }

Page No. 30

OUTPUT: Number of tokens: 8 hello world how do you do all are ok thank you

Page No. 31

/* Java class for matrix operations such as read,write,add,sub and multiply */ import java.io.*; public class MyMatrix { int array1[ ][ ]=new int[2][3]; int array2[ ][ ]={{10,20,30},{40,50,60}}; int array3[ ][ ]=new int [2][3]; public void readMatrix() throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); for(int i=0;i<2;i++) { for(int j=0;j<3;j++) { System.out.println("enter an integer number"); String str=br.readLine(); int num=Integer.parseInt(str); array1[i][j]=num; } } br.close(); } public void writeMatrix() { for(int i=0;i<2;i++) { for(int j=0;j<3;j++) { System.out.print(array1[i][j]+"\t"); } System.out.println(); } } public void addMatrix() { for(int i=0;i<2;i++)

Page No. 32

{ for(int j=0;j<3;j++) { array3[i][j]=array1[i][j]+array2[i][j]; System.out.print(array3[i][j]+"\t"); } System.out.println(); } } public void subMatrix() { for(int i=0;i<2;i++) { for(int j=0;j<3;j++) { array3[i][j]=array1[i][j]array2[i][j]; System.out.print(array3[i][j]+"\t"); } System.out.println(); } } public void multiplyMatrix() { for(int i=0;i<2;i++) { for(int j=0;j<3;j++) { array3[i][j]=array1[i][j]*array2[i][j]; System.out.print(array3[i][j]+"\t"); } System.out.println(); } }

Page No. 33

public static void main(String args[]) throws Exception { MyMatrix mm=new MyMatrix(); mm.readMatrix(); System.out.println("result of write matrix"); mm.writeMatrix(); System.out.println("result of addition matrix"); mm.addMatrix(); System.out.println("result of subtraction matrix"); mm.subMatrix(); System.out.println("result of multiplication matrix"); mm.multiplyMatrix(); } }

Page No. 34

OUTPUT: enter an integer number 1 enter an integer number 2 enter an integer number 3 enter an integer number 4 enter an integer number 5 enter an integer number 6 result of write matrix 1 2 3 4 5 6 result of addition matrix 11 22 33 44 55 66 result of subtraction matrix -9 -18 -27 -36 -45 -54 result of multiplication matrix 10 40 90 160 250 360

Page No. 35

// java program to illustrate linkedlist using list interface import java.util.*; public class LinkedListDemo { public static void main(String args[]) { LinkedList LL=new LinkedList(); Integer i1=new Integer(5); LL.add("5"); LL.add(new Double(3.5)); LL.add("hello"); LL.add(new Boolean(true)); LL.add(0,new Float(2.3f)); LL.add(new Character('A')); LL.addFirst(new Short("5")); LL.add(i1); LL.add(new Byte("3")); LL.set(2,"hari"); LL.remove(1); LL.removeFirst(); LL.removeLast(); System.out.println("index of il elements:"+LL.indexOf(i1)); System.out.println("Last of il elements:"+ LL.lastIndexOf(i1)); System.out.println("object of index 1:"+LL.get(1)); System.out.println("first elements:"+LL.getFirst()); System.out.println("last elements:"+LL.getLast()); System.out.println("size of LinkedList:"+LL.size()); System.out.println("list is empty:"+LL.isEmpty()); System.out.println("printing the elements through an iterator"); ListIterator L1=LL.listIterator(); while(L1.hasNext()) { System.out.println(L1.next()); }

Page No. 36

} }

Page No. 37

OUTPUT: index of il elements:5 Last of il elements:5 objects of index 1:3.5 first elements:hari last elements:5 size of LinkedList:6 list is empty:false printing the elements through an iterator hari 3.5 hello true A 5

Page No. 38

/*Java program for implementation of stack operations like push and pop*/ import java.util.*; public class StackDemo { public static void main(String[] args) { Stack st=new Stack(); System.out.println(st.empty()); st.push(new Integer(5)); st.push(new Boolean(true)); st.push(new Float(59.7f)); st.push(new Double(100.5)); Iterator it=st.iterator(); while(it.hasNext()) { Object obj=it.next(); System.out.println(obj); } System.out.println("poping the element is: "+st.pop()); System.out.println("stack is empty before while loop: "+st.empty()); while(!st.empty()) { System.out.println(st.pop()); } System.out.println("stack is empty after while loop: "+st.empty()); } }

Page No. 39

OUTPUT: true poping the element is: 100.5 stack is empty before while loop: false 59.7 true 5 stack is empty after while loop: true

Page No. 40

//Java program to implement TreeSet class import java.util.*; public class TreeSetInfo { public static void main(String args[]) { TreeSet ts=new TreeSet(); ts.add("Hemanth"); ts.add("Shekar"); ts.add("Manoj"); System.out.println("Number of elements present:"+ts.size()); System.out.println(ts); } }

Page No. 41

OUTPUT:Number of elements present:3 [Hemanth,Shekar,Manoj]

Page No. 42

/* Write a java program to demonstrate methods of Tree Set class*/ import java.util.*; class TreeSetDemo { public static void main(String args[]) { TreeSet ts= new TreeSet(); ts.add("Anu"); ts.add("Benny"); ts.add("Som"); ts.add("Sonu"); ts.add("Kevin"); ts.add("Christy"); System.out.println("Elements of treeset:"+ts); System.out.println("Size of treeset:"+ts.size()); ts.remove("Kevin"); System.out.println("Elements of treeset:"+ts); System.out.println("First element:"+ts.first()); System.out.println("Last element:"+ts.last()); System.out.println("Solly is an element of treeset: "+ts.contains("Solly")); ts.clear(); System.out.println("Elements of treeset:"+ts); } }

Page No. 43

OUTPUT: Elements of treeset:[Anu, Benny, Christy, Kevin, Som, Sonu] Size of treeset:6 Elements of treeset:[Anu, Benny, Christy, Som, Sonu] First element:Anu Last element:Sonu Solly is an element of treeset: false Elements of treeset:[]

Page No. 44

//Write a java program to implement Hash Set Class import java.util.*; public class HashSetInfo { public static void main(String args[]) { HashSet hs=new HashSet(); Integer i1=new Integer(10); hs.add(i1); Double d1=new Double(10.5); hs.add(d1); hs.add(new Integer(20)); hs.add("Sandeep"); hs.add(new String("author")); System.out.println("number of elements:"+hs.size()); System.out.println("i1 exists:"+hs.contains(i1)); System.out.println("elements before removed"); System.out.println(hs); hs.remove(hs); System.out.println(hs); } }

Page No. 45

Output: numberofelements:5 i1 exists:true elements before removed [Sandeep,10.5,20,10,author] [Sandeep,10.5,20,10,author]

Page No. 46

/*Create student class with particulars like name, rno, marks etc and print them in ascending order using iterator (list iterator).*/ import java.util.*; class Student { String name; int rno; int marks; Student(String name,int rno,int marks) { this.name= name; this.rno= rno; this.marks= marks; } public String toString() { return "Name "+name+" RollNo "+rno+" Marks "+marks; } } class IteratorDemo { public static void main(String args[]) { LinkedHashSet hs= new LinkedHashSet(); hs.add(new Student("Christy",333,445)); hs.add(new Student("Johaan",111,480)); hs.add(new Student("Justin",222,456)); hs.add(new Student("Sonu",444,467)); Iterator i= hs.iterator(); while(i.hasNext()) { System.out.println(i.next()); } } }

Page No. 47

OUTPUT: Name Name Name Name

Christy RollNo 333 Marks 445 Johaan RollNo 111 Marks 480 Justin RollNo 222 Marks 456 Sonu RollNo 444 Marks 467

Page No. 48

//Write Java program by using Tree Map Class. import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class MarksMap { public static void main(String args[]) { String subjects[]={"English","Maths","Science","Social","Drawin g"}; double marks[]={40,50,60,70,80}; TreeMap tm = new TreeMap(); for(int i=0;i<subjects.length;i++) { tm.put(subjects[i],new Double(marks[i])); } Set keys=tm.keySet(); Iterator it=keys.iterator(); while (it.hasNext()) { Object obj=it.next(); System.out.println(obj+""+tm.get(obj)); } } }

Page No. 49

OUTPUT: Drawing80.0 English40.0 Maths50.0 Science60.0 Social70.0

Page No. 50

//Write a Java program to illustrate the methods of vector import java.util.*; public class VectorTest { public static void main(String[] args) { Vector vect = new Vector(); vect.addElement(new Integer(5)); vect.addElement(new Float(5.7F)); vect.addElement(new String("Hello")); vect.addElement("Sure"); Double d=new Double(15.76); vect.addElement(d); String str="World"; vect.insertElementAt(str,1); System.out.println("First element:"+vect.firstElement()); System.out.println("Last element:"+vect.lastElement()); System.out.println("4th element:"+vect.elementAt(3)); System.out.println("Index of Hello:"+vect.indexOf("Hello")); System.out.println("Element Sure exists:"+vect.contains("Sure")); System.out.println("Size of vector:"+vect.size()); System.out.println("Capacity of vector before trimming:"+vect.capacity()); vect.trimToSize(); System.out.println("Capacity of vector after trimming:"+vect.capacity()); System.out.println(vect); Enumeration e=vect.elements(); while (e.hasMoreElements()) { System.out.println(e.nextElement()); }

Page No. 51

String s=(String)vect.elementAt(1); System.out.println("Str is "+s); } }

Page No. 52

OUTPUT: First element:5 Last element:15.76 4th element:Hello Index of Hello:3 Element Sure exists:true Size of vector:6 Capacity of vector before trimming:10 Capacity of vector after trimming:6 [5, World, 5.7, Hello, Sure, 15.76] 5 World 5.7 Hello Sure 15.76 Str is World

Page No. 53

// Program to Illustrate the Comparator Interface import java.util.*; class Animal implements Comparator<String> { public int compare(String str1,String str2) { return str2.compareTo(str1); } }; public class ComparatorDemo { public static void main(String args[]) { TreeSet<String>ts1=new TreeSet<String>(); TreeSet<String>ts2=new TreeSet<String>(new Animal()); ts1.add("camel"); ts1.add("zebra"); ts1.add("rabbit"); ts1.add("allegator"); ts1.add("tortise"); ts2.add("zebra"); ts2.add("camel"); ts2.add("rabbit"); ts2.add("allegator"); ts2.add("tortise"); System.out.println("Default value"); System.out.println("\t"+ts1); System.out.println("value with comparator:"); System.out.println("\t"+ts2); } }

Page No. 54

OUTPUT: Default value [allegator, camel, rabbit, tortise, zebra] value with comparator: [zebra, tortise, rabbit, camel, allegator]

Page No. 55

/* Write a Java program to print table using Buffered Reader and Buffered writer */ import java.io.*; class Table { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a number for multiplication table"); int n = Integer.parseInt(br.readLine()); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); for(int i=1;i<=10;i++) { int t= i*n; String s=((Integer)i).toString()+"*"+((Integer)n).toString()+"= "+((Integer)t).toString()+"\n"; bw.write(s,0,s.length()); } bw.flush(); br.close(); bw.close(); } }

Page No. 56

OUTPUT: Enter a number for multiplication table 7 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 7*8=56 7*9=63 7*10=70

Page No. 57

// Program to read and write files import java.io.*; class FileDemo { public static void main(String args[]) throws IOException { BufferedReader br1=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the file name"); String fname=br1.readLine(); FileOutputStream fo=new FileOutputStream(fname); BufferedReader br2=new BufferedReader(new InputStreamReader(System.in)); String s; System.out.println("Enter the lint of Text here"); System.out.flush(); s=br2.readLine(); for(int i=0;i<s.length();i++) fo.write(s.charAt(i)); fo.close(); FileInputStream fi=new FileInputStream(fname); int read; System.out.println("\n Content in the"+fname); while((read=fi.read())!=-1) System.out.print((char)read); fi.close(); } }

Page No. 58

OUTPUT: Enter the file name NewText Enter the lint of Text here Hi Content in the NewText Hi

Page No. 59

//Write a Java program to illustrate serialization. import java.io.*; public class SerializationDemo { public static void main(String args[]) { try { MyClass ob1=new MyClass("hello",-7,2.7e10); System.out.println("object1"+ob1); FileOutputStream fos=new FileOutputStream("serial"); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(ob1); oos.flush(); oos.close(); } catch(Exception e) { System.out.println("Exception during serialization"+e); System.exit(0); } try { MyClass ob2; FileInputStream fis=new FileInputStream("serial"); ObjectInputStream ois=new ObjectInputStream(fis); ob2=(MyClass)ois.readObject(); ois.close(); System.out.println("object2"+ob2); } catch(Exception e) {

Page No. 60

System.out.println("Exception during deserialization"+e); System.exit(0); } } } class MyClass implements Serializable { String s; int i; double d; public MyClass(String s,int i,double d) {this.s=s; this.i=i; this.d=d; } public String toString() { return "s="+s+";i="+";d="+d; } }

Page No. 61

OUTPUT: object1s=hello;i=;d=2.7E10 object2s=hello;i=;d=2.7E10

Page No. 62

/* Write a Java program which count the number of customers in the bank(use static variable)*/ class Customer { static int count; String name; int acno,bal; Customer(String name,int acno,int bal) { this.name=name; this.acno=acno; this.bal=bal; } void display() { count++; System.out.println(name+" "+acno+" "+bal); } public static void main(String args[]) { Customer c1= new Customer("Kevin",111,20000); Customer c2= new Customer("Johan",222,15000); Customer c3= new Customer("Jusin",333,18000); Customer c4= new Customer("Relin",444,25000); System.out.println("Customer details\n"); System.out.println("Name "+"Account No "+"Balance "); c1.display(); c2.display(); c3.display();

Page No. 63

c4.display(); System.out.println("Total customer:"+Customer.count); } }

Page No. 64

OUTPUT: Customer details Name Account No Kevin 111 Johan 222 Jusin 333 Relin 444 Total customer:4 Balance 20000 15000 18000 25000

Page No. 65

// Write a Java applet to implement a simple calculator. package javaapplication2; import java.awt.*; import java.awt.event.*; public class calculator extends java.applet.Applet implements ActionListener { TextField txtTotal = new TextField(""); Button button[] = new Button[10]; Button divide = new Button("/"); Button mult = new Button("*"); Button plus = new Button ("+"); Button minus = new Button("-"); Button isequalto = new Button("="); Button clear = new Button("CA"); double num ,numtemp ; int counter; String strnum = "",strnumtemp = "" ; String op = ""; public void operation() { counter ++; if (counter == 1) { numtemp = num; strnum = ""; num = 0; } else { if (op == "+") numtemp += num; else if (op == "-") numtemp -= num; else if (op == "*") numtemp = numtemp * num; else if (op == "/") numtemp = numtemp / num; strnumtemp = Double.toString(numtemp); txtTotal.setText(strnumtemp);

Page No. 66

strnum = ""; num = 0; } } public void init() { setLayout(null); for(int i = 0;i <= 9; i ++) { button[i] = new Button(String.valueOf(i)); button[i].setBackground(Color.WHITE); button[i].setForeground(Color.black); } button[1].setBounds(0,53,67,53); button[2].setBounds(67,53,67,53); button[3].setBounds(134,53,67,53); button[4].setBounds(0,106,67,53); button[5].setBounds(67,106,67,53); button[6].setBounds(134,106,67,53); button[7].setBounds(0,159,67,53); button[8].setBounds(67,159,67,53); button[9].setBounds(134,159,67,53); for (int i = 1;i <= 9; i ++) { add(button[i]); } txtTotal.setBounds(0,0,200,53); add(txtTotal); plus.setBounds(0,212,67,53); add(plus); button[0].setBounds(67,212,67,53); add(button[0]); minus.setBounds(134,212,67,53); add(minus); divide.setBounds(134,264,67,53); add(divide); isequalto.setBounds(67,264,67,53); add(isequalto);

Page No. 67

mult.setBounds(0,264,67,53); add(mult); add(clear); } public void start() { for(int i = 0;i <= 9; i ++) { button[i].addActionListener(this); } plus.addActionListener(this); minus.addActionListener(this); divide.addActionListener(this); mult.addActionListener(this); isequalto.addActionListener(this); clear.addActionListener(this); } public void stop() { for(int i = 0;i <= 9; i ++) { button[i].addActionListener(null); } plus.addActionListener(null); minus.addActionListener(null); divide.addActionListener(null); mult.addActionListener(null); isequalto.addActionListener(null); clear.addActionListener(null); } public void actionPerformed(ActionEvent e) { for(int i = 0;i <= 9; i++) { if (e.getSource() == button[i]) { play(getCodeBase(),i + ".au"); strnum += Integer.toString(i); txtTotal.setText(strnum);

Page No. 68

num = Double.valueOf(strnum).doubleValue(); } } if (e.getSource() == plus) { operation(); op = "+"; } if (e.getSource() == minus) { operation(); op = "-"; } if (e.getSource() == divide) { operation(); op = "/"; } if (e.getSource() == mult) { operation(); op = "*"; } if (e.getSource() == isequalto) { if (op == "+") numtemp += num; else if (op == "-") numtemp -= num; else if (op == "*") numtemp = numtemp * num; else if (op == "/") numtemp = numtemp / num; strnumtemp = Double.toString(numtemp); txtTotal.setText(strnumtemp); strnumtemp = ""; numtemp = 0; strnum = ""; num = 0; counter = 0;

Page No. 69

} if (e.getSource() == clear) { txtTotal.setText("0"); strnumtemp = ""; numtemp = 0; strnum = ""; num = 0; counter = 0; } } }

Page No. 70

OUTPUT:

Page No. 71

//Write a JavaProgram to demonstrate banner applet import java.awt.*; import java.applet.*; public class SampleBanner extends Applet implements Runnable { String str = "This is a simple Banner developed by Roseindia.net. "; Thread t ; boolean b; public void init() { setLayout(null); setBackground(Color.gray); setForeground(Color.yellow); } public void start() { t = new Thread(this); b = false; t.start(); } public void run () { char ch; for( ; ; ) { try { repaint(); Thread.sleep(250); ch = str.charAt(0); str = str.substring(1, str.length()); str = str + ch; } catch(InterruptedException e)

Page No. 72

{ } } } public void paint(Graphics g) { g.drawRect(1,1,300,150); g.setColor(Color.yellow); g.fillRect(1,1,300,150); g.setColor(Color.red); g.drawString(str, 1, 150); } }

Page No. 73

OUTPUT:

Page No. 74

/* Write a Java program validate user name and password text fields.*/ import java.awt.*; import java.awt.event.*; public class PassDemo extends Frame implements ActionListener { TextField usr,passwd; Button b; String ur="sophia",pw="jonu"; Label l,user,pass; public PassDemo() { user= new Label("User Name "); usr= new TextField(15); pass= new Label("Password "); passwd= new TextField(15); passwd.setEchoChar('*'); add(user); add(pass); l= new Label(" "); b= new Button("Enter"); setLayout(new FlowLayout()); add(user); add(usr); add(pass); add(passwd); add(b); add(l); b.addActionListener(this); setVisible(true); setBackground(Color.WHITE); setSize(250,250); } public void actionPerformed(ActionEvent ae) { String u,p;

Page No. 75

u=usr.getText(); p=passwd.getText(); if (u.equals(ur) & p.equals(pw)) l.setText("You are a valid user"); else l.setText("You are not a valid user"); } public static void main(String args[]) { new PassDemo(); } }

Page No. 76

OUTPUT:

Page No. 77

/* Write a Java program to demonstrate an application involving GUI with controls menus and event handling.*/ import javax.swing.*; import java.awt.*; import java.awt.event.*; class MenuFrame extends JFrame implements ActionListener { JMenuBar mb; JMenu fileMenu,editMenu; JLabel response; FileDialog fd; static MenuFrame mf; JButton b; public MenuFrame() { fileMenu= new JMenu("File"); editMenu= new JMenu("Edit"); response= new JLabel("Menu Tester...."); response.setBounds(200,100,250,50); setSize(600,300); setLocation(450,100); Container contentPane= getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(response); contentPane.setBackground(Color.CYAN); contentPane.setForeground(Color.ORANGE); b= new JButton("OK"); contentPane.add(b); b.addActionListener(this); JMenuItem item; item= new JMenuItem("New"); item.addActionListener(this); fileMenu.add(item); item= new JMenuItem("Open");

Page No. 78

item.addActionListener(this); fileMenu.add(item); item= new JMenuItem("Save"); item.addActionListener(this); fileMenu.add(item); item= new JMenuItem("Exit"); item.addActionListener(this); fileMenu.add(item); item= new JMenuItem("Cut"); item.addActionListener(this); editMenu.add(item); item= new JMenuItem("Copy"); item.addActionListener(this); editMenu.add(item); item= new JMenuItem("Paste"); item.addActionListener(this); editMenu.add(item); mb = new JMenuBar(); setJMenuBar(mb); mb.add(fileMenu); mb.add(editMenu); addMouseListener(new MyAdapter()); setDefaultCloseOperation(EXIT_ON_CLOSE); setTitle("Menu & Mouse events"); } public static void main(String args[]) { mf= new MenuFrame(); mf.setVisible(true); } class MyAdapter extends MouseAdapter { public void mouseClicked(MouseEvent me) { int x=me.getX();

Page No. 79

int y= me.getY(); response.setText("You have clicked at ("+x+","+y+")"); } } public void actionPerformed(ActionEvent ae) { String menuName; menuName=ae.getActionCommand(); if(menuName.equals("Exit")) System.exit(0); else if(menuName.equals("Save")) { fd = new FileDialog(mf,"File Dialog",FileDialog.SAVE); fd.setVisible(true); } else if(menuName.equals("Open")) { fd = new FileDialog(mf,"File Dialog",FileDialog.LOAD); fd.setVisible(true); String r1=fd.getFile();response.setText(r1); } else if(menuName.equals("OK")) response.setText("You have clicked OK button"); else response.setText("You have selected "+menuName); } }

Page No. 80

OUTPUT:

Page No. 81

You might also like