Sie sind auf Seite 1von 24

# www.jntuworld.com Compiled By : Bharath Annamaneni & Hari Vardhan Yerramsetty For http://www.jntuworld.com . JN TU W OR L D www.jntuworld.com www.jntuworld.

com 1 OBJECT ORIENTED PROGRAMMING LAB Week1 : a) Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b2-4ac is negative, display a message stating that there are no real solutions. import java.io.*; import java.io.*; class root { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int a=Integer.parseInt(br.readLine()); int b=Integer.parseInt(br.readLine()); int c=Integer.parseInt(br.readLine()); int d=((b*b)-(4*a*c)); if(d>0) { System.out.print("roots are real and distinct"); } if(d==0) { System.out.print("roots are real"); } if(d<0) { System.out.print("there is no solution"); } } JN TU W OR L D www.jntuworld.com www.jntuworld.com 2 OBJECT ORIENTED PROGRAMMING LAB } b) Write a Java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence. import java.io.*; import java.lang.*; class fibonacci { public static void main(String args[]) throws IOException { int a=Integer.parseInt(args[0]); int b=Integer.parseInt(args[1]); int n=Integer.parseInt(args[2]); int c=0; while(c<n) { c=a+b; System.out.print(c); a=b; b=c; } }

} Week 2 : a) Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that integer. JN TU W OR L D www.jntuworld.com www.jntuworld.com 3 OBJECT ORIENTED PROGRAMMING LAB import java.lang.*; import java.io.*; class prime { public static void main(String args[]) { int n=Integer.parseInt(args[0]); for(int r=0;r<n;r++) { int t=0; for(int i=1;i<r;i++) { if (r%i==0) { t++; } } if(t<2) { System.out.print(r); System.out.print(" "); } } } } b) Write a Java program to multiply two given matrices. import java.lang.*; import java.io.*; class arraymul JN TU W OR L D www.jntuworld.com www.jntuworld.com 4 OBJECT ORIENTED PROGRAMMING LAB { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("enter no of rows"); int m=Integer.parseInt(br.readLine()); System.out.print("enter no of columns"); int n=Integer.parseInt(br.readLine()); int a[][]=new int[m][n]; int i,j,k; { for( i=0;i<m;i++) { for(j=0;j<n;j++) { a[i][j]=Integer.parseInt(br.readLine()); } } System.out.print("enter no of rows"); int p=Integer.parseInt(br.readLine()); System.out.print("enter no of columns"); int q=Integer.parseInt(br.readLine());

int b[][]=new int[p][q]; { for( i=0;i<p;i++) { for( j=0;j<q;j++) { b[i][j]=Integer.parseInt(br.readLine()); } } JN TU W OR L D www.jntuworld.com www.jntuworld.com 5 OBJECT ORIENTED PROGRAMMING LAB } int c[][]=new int[m][i]; if(n==p) { for( i=0;i<m;i++) { for( j=0;j<q;j++) { c[i][j]=0; for( k=0;k<p;k++) { c[i][j]=c[i][j]+(a[i][k]*b[k][j]); } } } for(i=0;i<m;i++) { for(j=0;j<q;j++) { System.out.println(c[i][j]); } } } } } } . c) Write a Java Program that reads a line of integers, and then displays each in teger, and the sum of all the integers (Use StringTokenizer class of java.util) import java.io.*; class sum { public static void main(String args[])throws IOException JN TU W OR L D www.jntuworld.com www.jntuworld.com 6 OBJECT ORIENTED PROGRAMMING LAB { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,n,sum=0; System.out.print("enter the no of elements"); n=Integer.parseInt(br.readLine()); System.out.print("the elements are"); for(i=0;i<n;i++) { int ni=Integer.parseInt(br.readLine()); sum=sum+ni; } System.out.print("the sum is"+sum); } } Week 3 :

a) Write a Java program that checks whether a given string is a palindrome or no t. class Palindrome { public static void main(String args[]) { String s=args[0]; int len,i=0,n,c=0,p; len=s.length(); n=len/2; p=len-n+1; while(i<len/2) { JN TU W OR L D www.jntuworld.com www.jntuworld.com 7 OBJECT ORIENTED PROGRAMMING LAB if(s.charAt [i]==s.charAt(p)) c++; i++; p--; } if(c==len/2) { System.out.println("palindrom"); } else { System.out.println("not palindrom"); } } } b) Write a Java program for sorting a given list of names in ascending order. import java.lang.*; import java.io.*; class asc { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("enter how many strings"); int n=Integer.parseInt(br.readLine()); String x[]=new String[n]; System.out.print("enter "+n+" strings"); JN TU W OR L D www.jntuworld.com www.jntuworld.com 8 OBJECT ORIENTED PROGRAMMING LAB for(int i=0;i<n;i++) { x[i]=br.readLine(); } String s=new String(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(x[i].compareTo(x[j])<6) { s=x[i]; x[i]=x[j]; x[j]=s; } }

} System.out.print("string in alphebetical order are"); for(int i=0;i<n;i++) { System.out.println(x[i]); } } } c) Write a Java program to make frequency count of words in a given text. class Count { JN TU W OR L D www.jntuworld.com www.jntuworld.com 9 OBJECT ORIENTED PROGRAMMING LAB public static void main(String args[]) { int i,c=0; for(i=0;i<args.length;i++) { System.out.println(args[i]); c++; } System.out.println("number of words="+c); } } Week 4 : a) Write a Java program that reads a file name from the user, then displays info rmation about whether the file exists, whether the file is readable, whether the file is writable, the typ e of file and the length of the file in bytes. import java.io.*; class FileDemo { public static void main(String args[]) { File f1=new File("/java/copyright","Bharath.java"); System.out.println("file name"+f1.getName()); System.out.println("path"+f1.getPath()); System.out.println("parent"+f1.getParent()); System.out.println(f1.exists()); System.out.println(f1.canRead()); System.out.println(f1.canWrite()); System.out.println(f1.isDirectory()); JN TU W OR L D www.jntuworld.com www.jntuworld.com 10 OBJECT ORIENTED PROGRAMMING LAB System.out.println(f1.isFile()); System.out.println(f1.lastModified()); System.out.println(f1.length()); System.out.println(f1.delete()); } } b) Write a Java program that reads a file and displays the file on the screen, w ith a line number before each line. import java.io.*; class FileDemo1 { public static void main(String args[])throws Exception { int c=0; String s="i+ \n is \n java \n program \n"; char buffer[]=new char[s.length()];

s.getChars(0,s.length(),buffer,0); FileWriter f1=new FileWriter("c:/index.txt"); f1.write(buffer); f1.close(); FileReader fr=new FileReader("c:/index.txt"); BufferedReader br=new BufferedReader(fr); String t; while((t=br.readLine())!=null) { c++; JN TU W OR L D www.jntuworld.com www.jntuworld.com 11 OBJECT ORIENTED PROGRAMMING LAB System.out.println(c+t); } fr.close(); } } c) Write a Java program that displays the number of characters, lines and words in a text file. import javax.swing.*; import java.io.*; import java.util.*; public class Count { public static void main(String args[]) { try { String s=JOptionPane.showInputDialog("Enter the file name : "); FileInputStream f=new FileInputStream(s); DataInputStream d=new DataInputStream(f); String data; StringTokenizer st; int words=0,chars=0,i=0; while((data=d.readLine())!=null) { i++; st=new StringTokenizer(data); words+=st.countTokens(); chars+=data.length(); } System.out.println("total words \n" +words); JN TU W OR L D www.jntuworld.com www.jntuworld.com 12 OBJECT ORIENTED PROGRAMMING LAB System.out.println("total chras \n" +chars); System.out.println("total lines \n" +i ); f.close(); } catch(Exception) System.out.println("err"+e); } } } Week 5 : Write a Java program that: i) Implements stack ADT. import java.io.*; class stack { int stack[]=new int[10];

int tos; stack() { tos=-1; } void push(int item) { if(tos==9) System.out.println("stack is full"); else stack[++tos]=item; } JN TU W OR L D www.jntuworld.com www.jntuworld.com 13 OBJECT ORIENTED PROGRAMMING LAB int pop() { if(tos<0) { System.out.println("stack underflow"); return 0; } else return stack[tos--]; } } class teststack { public static void main(String args[]) { stack mystack1=new stack(); stack mystack2=new stack(); for(int i=0;i<10;i++) mystack1.push(i); for(int i=10;i<20;i++) mystack2.push(i); System.out.println("stack in my stack1:"); for(int i=0;i<10;i++) System.out.println(mystack1.pop()); System.out.println("stack in my stack2:"); for(int i=0;i<10;i++) System.out.println(mystack2.pop()); } } JN TU W OR L D www.jntuworld.com www.jntuworld.com 14 OBJECT ORIENTED PROGRAMMING LAB ii) Converts infix expression into Postfix form . import java.io.*; class stack { char stack1[]=new char[20]; int top; void push(char ch) { top++; stack1[top]=ch; } char pop() { char ch; ch=stack1[top];

top--; return ch; } int pre(char ch) { switch(ch) { case '-':return 1; case '+':return 1; case '*':return 2; case '/':return 2; } return 0; } boolean operator(char ch) { JN TU W OR L D www.jntuworld.com www.jntuworld.com 15 OBJECT ORIENTED PROGRAMMING LAB if(ch=='/'||ch=='*'||ch=='+'||ch=='-') return true; else return false; } boolean isAlpha(char ch) { if(ch>='a'&&ch<='z'||ch>='0'&&ch=='9') return true; else return false; } void postfix(String str) { char output[]=new char[str.length()]; char ch; int p=0,i; for(i=0;i<str.length();i++) { ch=str.charAt(i); if(ch=='(') { push(ch); } else if(isAlpha(ch)) { output[p++]=ch; } else if(operator(ch)) { if(stack1[top]==0||(pre(ch)>pre JN TU W OR L D www.jntuworld.com www.jntuworld.com 16 OBJECT ORIENTED PROGRAMMING LAB (stack1[top]))||stack1[top]=='(') { push(ch); } } else if(pre(ch)<=pre(stack1[top])) { output[p++]=pop(); push(ch);

} else if(ch=='(') { while((ch=pop())!='(') { output[p++]=ch; } } } while(top!=0) { output[p++]=pop(); } for(int j=0;j<str.length();j++) { System.out.print(output[j]); } } } class InToPost { public static void main(String[] args)throws Exception JN TU W OR L D www.jntuworld.com www.jntuworld.com 17 OBJECT ORIENTED PROGRAMMING LAB { String s; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); stack b=new stack(); System.out.println("Enter input string"); s=br.readLine(); System.out.println("Input String:"+s); System.out.println("Output String:"); b.postfix(s); } } iii) Evaluates the postfix expression. import java.io.*; import java.util.*; class StackDemo { static int index,pos; int T; float stk[]; StackDemo() { stk=new float[10]; T=-1; index=0; pos=0; } void push(float s) { JN TU W OR L D www.jntuworld.com www.jntuworld.com 18 OBJECT ORIENTED PROGRAMMING LAB if(T>=19) { System.out.println("Stack overflow"); System.exit(0); }else{

T=T+1; stk[T]=s; } } float pop() { float num; if(T==-1) { System.out.println("Stack is empty"); return(0); } else { num=stk[T]; T--; } return(num); } float ExpEval(char sfix[],float data[]) { int j=0; float op1,op2,fs; char ch; while(sfix[j]!='\0') { JN TU W OR L D www.jntuworld.com www.jntuworld.com 19 OBJECT ORIENTED PROGRAMMING LAB ch=sfix[j]; if(sfix[j]>='a'||sfix[j]>= 'A'&&sfix[j]<='z'||sfix[j]<='Z') { push(data[j]); } else { op2=pop(); op1=pop(); switch(ch) { case '+':push(op1+op2); break; case '-':push(op1-op2); break; case '*':push(op1*op2); break; case '/':push(op1/op2); break; case '%':push(op1%op2); break; } } j++; } fs=pop(); return(fs); } } class EvalPostFix JN TU W OR L D www.jntuworld.com www.jntuworld.com

20 OBJECT ORIENTED PROGRAMMING LAB { public static void main(String args[]) { String str; char postfix[]=new char[25]; float number[]=new float[25]; int j=0; try{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a postfix expression:"); str=br.readLine(); str.getChars(0,str.length(),postfix,0); while(postfix[j]!='\0') { if(postfix[j]>='a'||postfix[j] >='A'&&postfix[j]<='z'||postfix[j]<='Z') { System.out.println("enter a number for%c:"+postfix[j]); number[j]=Integer.parseInt(br.readLine()); } j++; } } catch(Exception e) { System.out.println("Exception \n Read:"+e); } StackDemo s1=new StackDemo(); System.out.println("The result is "+s1.ExpEval(postfix,number)); JN TU W OR L D www.jntuworld.com www.jntuworld.com 21 OBJECT ORIENTED PROGRAMMING LAB } } Week 6 : a) Develop an applet that displays a simple message. //<applet code="AppletDemo.class" height="300" width="300" > </applet> import java.applet.*; import java.awt.*; public class AppletDemo extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.drawString("BANDARI SRINIVAS INSTITUTE OF TECHNOLOGY ",70,70); } } b) Develop an applet that receives an integer in one text field, and computes it s factorial Value and returns it in another text field, when the button named Compute is clicked. //<applet code="FactorialApplet.class" width="300" height="500" > </applet> import javax.swing.*; import java.awt.*; import java.awt.event.*; public class FactorialApplet extends JApplet implements ActionListener { JPanel p1,p2; JLabel label1,label2;

JTextField input,result; JButton compute; public void init() { JN TU W OR L D www.jntuworld.com www.jntuworld.com 22 OBJECT ORIENTED PROGRAMMING LAB Container con=getContentPane(); con.setLayout(new BorderLayout()); label1=new JLabel("Enter the number : "); label2=new JLabel("Factorial is : "); input= new JTextField(5); result= new JTextField(5); compute =new JButton("Compute"); compute.addActionListener(this); p1=new JPanel(); p2=new JPanel(); p1.setBackground(Color.pink); p2.setBackground(Color.green); p1.add(label1); p1.add(input); p1.add(label2); p1.add(result); p2.add(compute); con.add(p1,BorderLayout.NORTH); con.add(p2,BorderLayout.CENTER); } public void actionPerformed(ActionEvent ae) { int fact=1; int number=Integer.parseInt(input.getText()); if (ae.getSource()==compute) { for (int i=1;i<=number;i++) { fact=fact*i; } result.setText(""+fact); JN TU W OR L D www.jntuworld.com www.jntuworld.com 23 OBJECT ORIENTED PROGRAMMING LAB } } } Week 7 : Write a Java program that works as a simple calculator. Use a grid layout to arr ange buttons for the digits and for the +, -,*, % operations. Add a text field to display the result. //<applet code="Calculator.class" height="150" width="700"> </applet> import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Calculator extends Applet implements ActionListener { JTextField t1,t2,t3; JLabel l1,l2,l3; JButton b1,b2,b3,b4; JPanel p1,p2; public void init() { p1=new JPanel();

int mul=x*y; t3.setText(" "+mul); } if (ae.getSource()==b4) { int x=Integer.parseInt(t1.getText()); int y=Integer.parseInt(t2.getText()); int div=x/y; t3.setText(" "+div); } } catch (Exception e) { JOptionPane.showMessageDialog(null,e); } JN TU W OR L D www.jntuworld.com www.jntuworld.com 26 OBJECT ORIENTED PROGRAMMING LAB } } Week 8 : a) Write a Java program for handling mouse events. import java.awt.*; import java.applet.Applet; import java.awt.event.*; /*<applet code="Mouseevents"width=200 height=100> </applet>*/ public class Mouseevents extends Applet implements MouseListener,MouseMotionList ener { String msg=""; int x=0,y=0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { x=10; y=20; msg="mouse clicked"; repaint(); } public void mouseEntered(MouseEvent me) { x=10; y=20; JN TU W OR L D www.jntuworld.com www.jntuworld.com 27 OBJECT ORIENTED PROGRAMMING LAB msg="mouse entered"; repaint(); } public void mouseExited(MouseEvent me) { x=10; y=20; msg="mouse exited"; repaint(); } public void mousePressed(MouseEvent me)

{ x=me.getX(); y=me.getY(); msg="down"; repaint(); } public void mouseReleased(MouseEvent me) { x=me.getX(); y=me.getY(); msg="up"; repaint(); } public void mouseDragged(MouseEvent me) { x=me.getX(); y=me.getY(); msg="*"; showStatus("dragging mouse at"+x+","+y); repaint(); JN TU W OR L D www.jntuworld.com www.jntuworld.com 28 OBJECT ORIENTED PROGRAMMING LAB } public void mouseMoved(MouseEvent me) { showStatus("moving mouse at"+me.getX()+","+me.getY()); } public void paint(Graphics g) { g.drawString(msg,x,y); } } Week 9 : a) Write a Java program that creates three threads. First thread displays Good Mo rning every one second, the second thread displays Hello every two seconds and the third thread displays lcome every three seconds. class A extends Thread { synchronized public void run() { try { while(true) { sleep(10); System.out.println("good morning"); } } catch(Exception e) { } JN TU W OR L D www.jntuworld.com www.jntuworld.com 29 OBJECT ORIENTED PROGRAMMING LAB } } class B extends Thread { synchronized public void run() {

We

try { while(true) { sleep(20); System.out.println("hello"); } } catch(Exception e) { } } } class C extends Thread { synchronized public void run() { try { while(true) { sleep(30); JN TU W OR L D www.jntuworld.com www.jntuworld.com 30 OBJECT ORIENTED PROGRAMMING LAB System.out.println("welcome"); } } catch(Exception e) { } } } class ThreadDemo { public static void main(String args[]) { A t1=new A(); B t2=new B(); C t3=new C(); t1.start(); t2.start(); t3.start(); } } b) Write a Java program that correctly implements producer consumer problem usin g the concept of inter thread communication. class Q { boolean valueSet=false; JN TU W OR L D www.jntuworld.com www.jntuworld.com 31 OBJECT ORIENTED PROGRAMMING LAB int n; synchronized int get() { if(!valueSet) try { wait(); } catch(InterruptedException e) {

System.out.println("Exception is:"+e); } System.out.println("got:"+n); notify(); return n; } synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println JN TU W OR L D www.jntuworld.com www.jntuworld.com 32 OBJECT ORIENTED PROGRAMMING LAB ("\n Exception in put:"+e); } this.n=n; valueSet=true; System.out.println("\nput:"+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++); } } class Consumer implements Runnable { Q q; Consumer(Q q) JN TU W OR L D www.jntuworld.com www.jntuworld.com 33 OBJECT ORIENTED PROGRAMMING LAB { this.q=q; new Thread(this,"Consumer").start(); } public void run() { while(true) q.get(); } } class ProdConsDemo { public static void main(String args[])

{ Q q=new Q(); new Producer(q); new Consumer(q); System.out.println("\n press ctrl+c to stop"); } } Week 10 : Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the textfields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a NumberFormatException. If Num2 were Zero, the program would throw an ArithmeticE xception Display the exception in a message dialog box. import java.awt.*; JN TU W OR L D www.jntuworld.com www.jntuworld.com 34 OBJECT ORIENTED PROGRAMMING LAB import java.awt.event.*; import java.applet.*; /*<applet code="Div"width=230 height=250> </applet>*/ public class Div extends Applet implements ActionListener { String msg; TextField num1,num2,res;Label l1,l2,l3; Button div; public void init() { l1=new Label("Number 1"); l2=new Label("Number 2"); l3=new Label("result"); num1=new TextField(10); num2=new TextField(10); res=new TextField(10); div=new Button("DIV"); div.addActionListener(this); add(l1); add(num1); add(l2); add(num2); add(l3); add(res); add(div); } JN TU W OR L D www.jntuworld.com www.jntuworld.com 35 OBJECT ORIENTED PROGRAMMING LAB public void actionPerformed(ActionEvent ae) { String arg=ae.getActionCommand(); if(arg.equals("DIV")) { String s1=num1.getText(); String s2=num2.getText(); int num1=Integer.parseInt(s1); int num2=Integer.parseInt(s2); if(num2==0) {

try { System.out.println(" "); } catch(Exception e) { System.out.println("ArithematicException"+e); } msg="Arithemetic"; repaint(); } else if((num1<0)||(num2<0)) { try { System.out.println(""); JN TU W OR L D www.jntuworld.com www.jntuworld.com 36 OBJECT ORIENTED PROGRAMMING LAB } catch(Exception e) { System.out.println("NumberFormat"+e); } msg="NumberFormat"; repaint(); } else { int num3=num1/num2; res.setText(String.valueOf(num3)); } } } public void paint(Graphics g) { g.drawString(msg,30,70); } } Week 11 : Write a Java program that implements a simple client/server application. The cli ent sends data to a server. The server receives the data, uses it to produce a result, and then sends the re sult back to the client. The client displays the result on the console. For ex: 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. (Use java.net). server.java import java.net.*; JN TU W OR L D www.jntuworld.com www.jntuworld.com 37 OBJECT ORIENTED PROGRAMMING LAB import java.io.*; public class server { public static void main(String args[]) throws Exception { ServerSocket ss=new ServerSocket(2000); Socket s=ss.accept(); BufferedReader br=new BufferedReader (new InputStreamReader(s.getInputStream())); double rad,area;