java manual

55
J.B.INSTITUTE OF ENGINEERING & TECHNOLOGY YENKAPALLY(V), MOINABAD(M), HYDERABAD-500075 DEPARTMENT OF CSE & IT OOP THROUGH JAVA LAB MANUAL

Upload: sneha-tiwari

Post on 25-Nov-2014

191 views

Category:

Documents


1 download

TRANSCRIPT

J.B.INSTITUTE OF ENGINEERING & TECHNOLOGY

YENKAPALLY(V), MOINABAD(M), HYDERABAD-500075

DEPARTMENT OF CSE & IT

OOP THROUGH JAVALAB MANUAL

J.B.INSTITUTE OF ENGINEERING & TECHNOLOGY

YENKAPALLY(V), MOINABAD(M), HYDERABAD-500075

S.NO Name of the Experiment1. Write a java program that prints all real solutions to the

quadratic equation ax 2+bx+c=0.Read in a,b,c and use the quadratic formula. If the discriminant b 2-4ac in negative a display message stating that there are no real solutions.

2. The Fibonacci sequence is defined by the following rule.The first two values in the sequence are 1 and 1. Every subsequent value is the run of the two values preceeding it. Write a java program that uses both recursive and non-recursive functions to print the nth value in the Fibonacci sequence.

3. Write a java program that prompts the user for an integer and then print out all prime numbers upto that integer.

4. Write a java program that checks whether a given string is Palindrome or not. Ex: madam is not palindrome.

5. Write a program for sorting a given list of names in ascending order.

6. Write a java program to multiply two given matrices.7. Write a java program that reads a line of integers and then

displays each integer and the sum of all the integers.8. Write a java program that reads on file name from the user

then the displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and length of the file in bytes.

9. Write a java program that reads a file and displays a file and displays the file on the screen, with a line no before each line.

10. Write a java program that displays the no of characters, lines and words in a text file.

11. Write a java program that a)implements Stack ADT.b)converts infix expr and postfix form.

12. Write an applet that displays a simple massage.14. Write a java program that works as a simple calculator.

Use a grid layout to arrange buttons for the digits and for the +,-,*,% operations. Add a text field to display the results.

15. Write a java program for handling Mouse Events.

16. Write a java program for creating Multithreads.17. Write a java program that correctly implements Producer

consumer problem using the concept of inter thread communication.

18. .Write a java program that let’s users create PIE charts. Design your own interface.

19. Write a java program that allows the user to draw lines rectangles and Ovels

20. Write a java program that implements a simple client/server application. The client sends data to a server. The server receives the data, uses it to produce a result and then sends the result back to the client. The client displays result on the console. For eg., the data sent from the client is the radius of a circle and the result produced by the server is the area of the circle.

21. Write a java program that illustrates how runtime polymorphism is achieved.

1. WAP to print all real solutions to the Quadratic Equation. ax²+bx+c=0

class Quadratic{ public static void main(String args[]) { int a=2,b=8,c=2; double root1,root2; double y=(b*b)-4*a*c; if(y<0) { System.out.println("No real root exists."); } else { root1=(-b)+(Math.sqrt(y))/2*a; root2=(-b)-(Math.sqrt(y))/2*a; System.out.println("Roots are: "+root1+" \n"+root2); } }}

OUTPUT:

C:\>javac Quadratic.java

C:\>java Quadratic

Roots are: -1.0717967697244912-14.928203230275509

2. WAP to print the Fibonacci series for given no.

import java.util.*;class fibonacci{

public static void main(String[] args){

int f1=1,f2=1,f3,i=3,n; n=Integer.parseInt(args[0]); System.out.println(f1); System.out.println(f2); while(i<=n) { f3=f1+f2; System.out.println(f3); f1=f2; f2=f3; i++; }

}}

OUTPUT:

C:\ >javac fibonacci.java

C:\>java fibonacci 511235

3. WAP to print all prime numbers in given range

class prime { public static void main(String args[]) { int i,j,n,count; System.out.println("Enter any number: "); n=Integer.parseInt(args[0]); for(i=1; i<=n; i++) { count=0; for(j=1; j<=n; j++) { if(i%j==0) { count++; } if(count==2) System.out.println("Prime no's: "+count); } } }}

OUTPUT :

C:\ >javac prime.java

C:\ >java prime 6

Enter any number:Prime no's: 2Prime no's: 3Prime no's: 5

4. A program to find given Sting is whether palindrome or not?

import java.io.*; public class Palindrome { public static void main(String args[])throws IOException { int m=0; boolean b=false; System.out.println("Enter any String"); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String s=br.readLine(); m=s.length(); for(int i=0,j=m-1; i<=j; j--,i++) { if(s.charAt(i)==s.charAt(j)) { b=true; continue; } b=false; break; } if(b==true) System.out.println("Given String is palindrome"); else System.out.println("Given String is not palindrome"); } }

OUTPUT

C:\ >javac Palindrome.javaC:\>java PalindromeEnter any StringmadamGiven String is palindromeC:\>java PalindromeEnter any StringmasterGiven String is not palindrome

5. A program to compute the product of two matrices

import java.io.*; class matrixmul { public static void main(String args[])throws Exception { int i,j,k;int a[][]=new int[2][2];int b[][]=new int[2][2]; int c[][]=new int[2][2]; System.out.println("Enter elements into first matrix"); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); for(i=0;i<2;i++) for(j=0;j<2;j++) { String n=br.readLine(); a[i][j]=Integer.parseInt(n);} System.out.println("Enter elements into second matrix"); for(i=0;i<2;i++) for(j=0;j<2;j++) { String s=br.readLine(); b[i][j]=Integer.parseInt(s); } System.out.println("Elements of first matrix"); for(i=0;i<2;i++) { for(j=0;j<2;j++) System.out.print(a[i][j]+"\t"); System.out.println(" \n "); } System.out.println("Elements of second matrix"); for(i=0;i<2;i++) { for(j=0;j<2;j++) System.out.print(b[i][j]+"\t"); System.out.println(" \n"); } for(i=0;i<2;i++) for(j=0;j<2;j++) { c[i][j]=0; for(k=0;k<2;k++) c[i][j]=c[i][j]+a[i][k]*b[k][j]; } System.out.println("Elements of resultant matrix");

for(i=0;i<2;i++) { for(j=0;j<2;j++) System.out.print(c[i][j]+"\t"); System.out.println(" \n "); } } }

OUTPUTC:\ >javac matrixmul.java

C:\ >java matrixmul

Enter elements into first matrix2222

Enter elements into second matrix2222Elements of first matrix2 2

2 2

Elements of second matrix2 2

2 2

Elements of resultant matrix8 8

8 8

6. Write a program to draw a Line, Rectangle and Oval

import java.awt.*; class DrawOvals extends Frame {

DrawOvals() { setSize(400,400); setVisible(true); } public void paint(Graphics g) { g.drawLine(70,60,350,350); g.setColor(Color.green);g.drawRect(100,150,100,150); g.setColor(Color.cyan); g.drawOval(240,70,70,70); } public static void main(String args[]) { new DrawOvals(); } }

OUTPUT

C:\ >javac drawoval.java

C:\ >java DrawOvals

7. Demonstrate multiple catch statements.

class multicatch{ public static void main(String args[]) {

try { int a=args.length; System.out.println("a= "+a); int b=42/a; int c[]={1}; c[42]=99; } catch(ArithmeticException e) { System.out.println("Divide by 0: "+e); } catch(ArrayIndexOutOfBoundsException e) { System.out.print("Array index oob: " + e); } System.out.println("After try/catch blocks."); }}

OUTPUT

C:\>javac multicatch.java

C:\>java multicatcha= 0Divide by 0: java.lang.ArithmeticException: / by zeroAfter try/catch blocks.

8. Program to display a simple message on the screen by using an applet. A simple applet that sets the foreground and background colors and outputs a string.

import java.awt.*;import java.applet.Applet;/*

<applet code="Sample" width=300 height=50></applet>*/

public class Sample extends Applet{String msg;public String set(){return "first";}public void init(){ setBackground(Color.cyan); setForeground(Color.red); msg = set();}public void start(){ }public void stop(){ }public void paint(Graphics g){ g.drawString(msg,10, 30);}}

OUTPUT

C:\>javac Sample.java

C:\>appletviewer Sample.java

9. Key events

import java.awt.*;import java.awt.event.*;import java.applet.*;

/*<applet code="But1" height=400 width=500></applet>*/

public class But1 extends Applet implements ActionListener,ItemListener{Label L1,L2,L3;TextField t1;TextField t2;TextField t3;Button b1;public void init(){L1 =new Label(" Enter first value :");add(L1);t1=new TextField(20);add(t1);L2 =new Label(" Enter second value :");add(L2);t2=new TextField(30);add(t2);L3 =new Label("Result :");add(L3);t3=new TextField(30);add(t3);b1=new Button("ADD");add(b1);b1.addActionListener(this);}public void paint(Graphics g){}public void actionPerformed(ActionEvent e){if(e.getSource()==b1){int x=Integer.parseInt(t1.getText());int y=Integer.parseInt(t2.getText());int sum = x + y;t3.setText(""+sum);}}public void itemStateChanged(ItemEvent ie){}

}

OUTPUT:

C:\>javac KeyEvents.java

C:\>appletviewer KeyEvents.java

10. Runtime Polymorphism

class g{public void m1(){System.out.println("I am in m1 of G");}public void m2(){System.out.println("I am in m2 of G");}}class g1 extends g{public void m3(){System.out.println("I am in m3 of g1");}public void m1(){System.out.println("I am in m1 of g1");}}class runtimepolymarphisum{public static void main(String args[]){g ob1=new g();g1 ob2=new g1();g baseref;ob1.m1();ob1.m2();baseref=ob1;baseref.m1();baseref.m2();ob2.m1();ob2.m2();ob2.m3();baseref=ob2;baseref.m1();baseref.m2();}}

OUTPUT

C:\>javac runtimepolymarphisum.java

C:\>java runtimepolymarphisum

I am in m1 of GI am in m2 of GI am in m1 of GI am in m2 of GI am in m1 of g1I am in m2 of GI am in m3 of g1I am in m1 of g1I am in m2 of G

11. WAP to demonstrate Method Overloading.

class OverloadDemo{

void test(){

System.out.println("No parameters.");}void test(int a){

System.out.println("A: "+a);}

void test(int a, int b){

System.out.println("A and B: "+a+" "+b);}double test(double a){

System.out.println("Double A: "+a);return a*a;

}}class Overload{

public static void main(String args[]){

OverloadDemo ob=new OverloadDemo();double result;ob.test();ob.test(40);ob.test(20,30);result=ob.test(123.45);System.out.println("Result of ob.test(123.45): "+result);

}}

OUTPUT:

C:\>javac Overload.java

C:\>java Overload

No parameters.A: 40A and B: 20 30Double A: 123.45Result of ob.test(123.45): 15239.9025

12. WAP to demonstrate Constitutor overloading

class OverloadConsDemo{

doble width;double height;double depth;Box(double w, double h, double d){

width=w;height=h;depth=d;

}Box(){

width=-1;height=-1;depth=-1;

}Box(double len){

width=height=depth=len;}double volume(){

return width*height*depth;}

}class OverloadCons{

public static void main(String args[]){

Box box1=new Box(10,20,30);Box box2=new Box();Box box3=new Box(9);double vol;vol=box1.volume();System.out.println("Volume of Box1 is: "+vol);vol=box2.volume();System.out.println("Volume of Box2 is: "+vol);vol=box3.volume();System.out.println("Volume of Box3 is: "+vol);

}}

OUTPUT:C:\>javac OverloadCons.java

C:\>java OverloadCons

Volume of Box1 is: 6000.0Volume of Box2 is: -1.0Volume of Box3 is: 729.0

13. WAP to Demonstrate finally keyword

class finallydemo {

static void procA( ) {

try {System.out.println("inside procA);throw new RuntimeException("demo");} finally {System.out.println("procA' s finally");}

}static void procB( ) {

try {System.out.println("inside procB);return;} finally {System.out.println("procB's finally");}

}static void procC( ) {

try {System.out.println("inside procC);

} finally {System.out.println("procC's finally");}

}

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

{procA( );} catch (Exception e) {System.out.println("Exception caught");}procB( );procC( );}}

OUTPUT:

C:\>javac OverloadCons.java

C:\>java OverloadCons

14. WAP to Demonstrate Method Overriding

class A{ int i,j; A(int a,int b) { i=a; j=b; } void show() { System.out.println("i and j="+i+" "+j); }}class B extends A{ int k; B(int a,int b,int c) { super(a,b); k=c; } void show() { System.out.println("k: "+k); }}class override{ public static void main(String args[]) { B subob = new B(1,2,3); subob.show(); }}

OUTPUT: C:\>javac override.java

C:\>java override

k: 3

15. WAP that reads a line of integers, and then displays each integer, and the sum of all integers (using string tokenize class).

import java.util.StringTokenizer;import javax.swing.*;class tokendemo { public static void main(String[] args) throws exception

{ String s; int a=0,sum=0; s=JOptionPane.showInputDialog("Enter the string"); StringTokenizer t=new StringTokenizer(s,"="); System.out.println(t.countTokens());

while(t.hasMoreTokens()){

a=Integer.parseInt(t.nextToken()); sum +=a;

} System.out.println("Total="+sum);

}}

OUTPUT:

C:\>javac tokendemo.java

C:\>java tokendemo

3Total=60

16.WAP to calculate area of a rectangle

import java.io.*; class Rect{ double len; double bre; double area(){ return len*bre; } public static void main(String args[])throws IOException { Rect r1=new Rect(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter len"); String s=br.readLine(); r1.len=Double.parseDouble(s); System.out.println("enter bre"); s=br.readLine(); r1.bre=Double.parseDouble(s); double x=r1.area(); System.out.println("area of Rectangle:"+x); } }

OUTPUT:

C:\>javac Rect.java

C:\>java Rectenter len4enter bre7area of Rectangle:28.0

17.WAP to arrange given numbers in ascending order

import java.io.*;public class Sorting{public static void main(String args[])throws IOException{int a[]=new int[10];DataInputStream dis=new DataInputStream(System.in);System.out.println("Enter Array of values ");

for(int i=0;i<10;i++)a[i]=Integer.parseInt(dis.readLine());System.out.println("Array of values before Sorting ");for(int i=0;i<a.length;i++)System.out.println("a["+i+"]="+a[i]);for(int i=0;i<a.length;i++)for(int j=i;j<(a.length-1);j++)if(a[i]>a[j+1]){int t=a[i];a[i]=a[j+1];a[j+1]=t;}System.out.println("Array of values after Sorting ");for(int i=0;i<a.length;i++)System.out.println("a["+i+"]="+a[i]);}}

OUTPUT:

C:\>javac Sorting.javaNote: Sorting.java uses or overrides a deprecated API.Note: Recompile with -Xlint:deprecation for details.

C:\>java Sorting 5Enter Array of values46738Array of values before Sortinga[0]=4a[1]=6a[2]=7a[3]=3a[4]=8Array of values after Sortinga[0]=3a[1]=4a[2]=6a[3]=7a[4]=8

18. WAP to Demonstrate Call by valueclass test{ void meth(int i,int j) { i*=2; j/=2; }}class callbyvalue{ public static void main(String args[]) { test ob=new test(); int a=15,b=20; System.out.println(" a and b before call:"+a+" "+b); ob.meth(a,b); System.out.println(" a and b after call:"+a+" "+b); }}

OUTPUT:

C:\>javac callbyvalue.java

C:\>java callbyvalue a and b before call:15 20 a and b after call:15 20

19. WAP to demonstrate Call by Reference

class test{int a,b; test(int i,int j) { a=i; b=j; } void meth(test ob) { ob.a*=2; ob.b/=2; }}class callbyref{ public static void main(String args[]) { test ob1=new test(15,20); System.out.println(" ob1.a and ob1.b before call:"+ob1.a+" "+ob1.b); ob1.meth(ob1); System.out.println(" ob1.a and ob1.b after call:"+ob1.a+" "+ob1.b); }}

OUTPUT:

C:\>javac callbyref.java

C:\>java callbyref ob1.a and ob1.b before call:15 20 ob1.a and ob1.b after call:30 10

20. A program to demonstrate Dynamic Method Dispatch

class A { void callme() { System.out.println("Inside A's callme method"); } } class B extends A { void callme() { System.out.println("Inside B's callme method"); } } class C extends A { void callme() { System.out.println("Inside C's callme method"); }} class Dispatch { public static void main(String args[]) { A a=new A(); B b=new B(); C c=new C(); A r; r=a; r.callme(); r=b; r.callme(); r=c; r.callme(); } }

OUTPUT:

C:\>javac Dispatch.java

C:\>java DispatchInside A's callme methodInside B's callme methodInside C's callme method

21.WAP to creates a custom exception type.

class CustomException extends Exception {private int detail;

CustomException(int a) {detail = a;

}public String toString() {

return "MyException[" + detail + "} ";}

}class ExceptionDemo {static void compute(int a ) throws CustomException {

System.out.println("Called compute(" + a + ")");if(a>10)throw new CustomException(a);System.out.println("Normal exit");}

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

compute(1);compute(20);

} catch (CustomException e) { System.out.println("Caught " + e);}

}}

OUTPUT:

C:\>javac ExceptionDemo.java

C:\>java ExceptionDemo

Called compute(1)Normal exitCalled compute(20)Caught MyException[20}

22. WAP to demonstrate interface implementation.

interface A {void meth1();void meth2();}interface B extends A {void meth3();}class MyClass implements B {public void meth1() {

System.out.println(“Implement meth1().”);}public void meth2() {

System.out.println(“Implement meth2().”);}public void meth3() {

System.out.println(“Implement meth3().”);}

}class IfExtend {public static void main(String arg[]) {

Myclass ob = new MyClass( );

ob.meth1();ob.meth2();ob.meth3();}

}

OUTPUT:

C:\>javac InterfaceDemo.java

C:\>java InterfaceDemo

Implement meth1()Implement meth2()Implement meth3()

23. WAP to demonstrate Multithreading using Thread class

class DemoThread extends Thread{ String name; Thread t; DemoThread(String threadname) { name=threadname; t=new Thread(this,name); System.out.println("New Thread: "+t); t.start(); } 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[]){

new DemoThread("One");new DemoThread("Two");new DemoThread("Three");

try{

Thread.sleep(10000);}catch(InterruptedException e){

System.out.println("main Thread Interrupted ");}

System.out.println("main Thread exiting ");}

}

OUTPUT:

C:\>javac MultiThreadDemo.javaC:\>java MultiThreadDemo

New Thread: Thread[One,5,main]New Thread: Thread[Two,5,main]One: 5New Thread: Thread[Three,5,main]Two: 5Three: 5One: 4Two: 4Three: 4One: 3Three: 3Two: 3One: 2Three: 2Two: 2Two: 1One: 1Three: 1ThreeexitingOneexitingTwoexitingmain Thread exiting

24. WAP to demonstrate Multithreading using Runnable interfaceclass DemoThread Impliments Runnable{ String name; Thread t; DemoThread(String threadname) { name=threadname; t=new Thread(this,name); System.out.println("New Thread: "+t); t.start(); } 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[]){

new DemoThread("One");new DemoThread("Two");new DemoThread("Three");

try{

Thread.sleep(10000);}catch(InterruptedException e){

System.out.println("main Thread Interrupted ");}

System.out.println("main Thread exiting ");}}

OUTPUT:

C:\>javac MultiThreadDemo.javaC:\>java MultiThreadDemo

New Thread: Thread[One,5,main]New Thread: Thread[Two,5,main]One: 5New Thread: Thread[Three,5,main]Two: 5Three: 5One: 4Two: 4Three: 4One: 3Three: 3Two: 3One: 2Three: 2Two: 2Two: 1One: 1Three: 1ThreeexitingOneexitingTwoexitingmain Thread exiting

25. WAP to demonstrate Thread Synchronization

class Callme{synchronized void call(String msg) {

System.out.print( " [ " + msg);try {Thread.sleep(1000);}catch(InterruptedException e){System.out.println("Interrupted");

}System.out.println(" ] ");

}}class Caller implements Runnable {String msg;Callme target;Thread t;

public Caller (Callme targ, String s) {target=targ;msg=s;t=new Thread(this);t.start();}public void run(){target.call(msg);}}class Synch1{public static void main(String args[ ]) {Callme target =new Callme();Caller ob1=new Caller(target,"Hello");Caller ob2=new Caller(target,"Synchronized");Caller ob3=new Caller(target,"World");try {ob1.t.join();ob2.t.join();ob3.t.join();}catch(InterruptedException e) {System.out.println("Interrupted");}

}}

OUTPUT:

C:\>javac ThreadSync.java

C:\>java ThreadSync

[ Synchronized ] [ Hello ] [ World ]

26.WAP to demonstrate Inter Thread Communication

class Queue { int exchangeValue; boolean busy = false;synchronized int get() { if (!busy) try { wait(); } catch (InterruptedException e) { System.out.println("Get: InterruptedException"); } System.out.println("Got: " + exchangeValue); busy=false; notify(); return exchangeValue; }

synchronized void put (int exchangeValue) { if (busy) try { Thread.sleep(1); wait();

} catch (InterruptedException e) { System.out.println("Put: InterruptedException"); } this.exchangeValue = exchangeValue; busy = true;

System.out.println("Put: " + exchangeValue); notify(); }}class Publisher implements Runnable { Queue q; Publisher(Queue q) { this.q = q; Thread t= new Thread (this, "Publisher"); t.start(); }

public void run() { for (int i = 0; i < 7; i++){ q.put(i); } }}class Consumer implements Runnable { Queue q; Consumer (Queue q) { this.q = q; Thread t=new Thread (this, "Consumer"); t.start(); } public void run() { for (int i = 0; i < 7; i++){int s= q.get(); } }}class InterThreadDemo { public static void main(String args []) { Queue q = new Queue (); new Publisher (q); new Consumer (q); }}

OUTPUT:C:\>javac InterThread.java

C:\>java InterThread

Put: 0Got: 0Put: 1Got: 1Put: 2Got: 2Put: 3Got: 3Put: 4Got: 4Put: 5Got: 5Put: 6

Got: 6