Object Oriented Programming Lab Manual

45
SARADA INSTITUTE OF TECHOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM DEPARTMENT OF COMPUTER SCIENCE ENGINEERING & INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING LAB MANUAL PREPARED BY: L. CHANDRA SEKHAR Asst. Professor.(Dept of CSE)

Transcript of Object Oriented Programming Lab Manual

Page 1: Object Oriented Programming Lab Manual

SARADA INSTITUTE OF TECHOLOGY & SCIENCE

SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

& INFORMATION TECHNOLOGY

OBJECT ORIENTED PROGRAMMING LAB MANUAL

PREPARED BY: L. CHANDRA SEKHAR

Asst. Professor.(Dept of CSE)

Page 2: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 2 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

INDEX 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. b) The Fibonacci sequence is defined by the following rule: The fist two values in the sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it. Write a Java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence. 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. b) Write a Java program to multiply two given matrices. c) Write a Java Program that reads a line of integers, and then displays each integer, and the sum of all the integers (Use StringTokenizer class of java.util) Week 3 : a) Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome. b) Write a Java program for sorting a given list of names in ascending order. c) Write a Java program to make frequency count of words in a given text. Week 4 : a) Write a Java program that reads a file name from the user, then displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes. b) Write a Java program that reads a file and displays the file on the screen, with a line number before each line. c) Write a Java program that displays the number of characters, lines and words in a text file. Week 5 : a) Write a Java program that:

i) Implements stack ADT. ii) Converts infix expression into Postfix form iii) Evaluates the postfix expression

Week 6 : a) Develop an applet that displays a simple message. b) Develop an applet that receives an integer in one text field, and computes its factorial Value and returns it in another text field, when the button named “Compute” is clicked. Week 7 : 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 result.

Week 8 : a) Write a Java program for handling mouse events. Week 9 : a) Write a Java program that creates three threads. First thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three seconds. b) Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication. 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 ArithmeticException Display the exception in a message dialog box.

Week 11 : 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 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)

Page 3: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 3 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Week 12 : a) Write a java program that simulates a traffic light. The program lets the user select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a time No light is on when the program starts. b) Write a Java program that allows the user to draw lines, rectangles and ovals. Week 13 : a) Write a java program to create an abstract class named Shape that contains an empty method named numberOfSides ( ).Provide three classes named Trapezoid, Triangle and Hexagon such that each one of the classes extends the class Shape. Each one of the classes contains only the method numberOfSides ( ) that shows the number of sides in the given geometrical figures. b) Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and the remaining lines correspond to rows in the table. The elements are _eparated by commas. Write a java program to display the table using Jtable component.

Page 4: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 4 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Week 1: 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.*; class Quard { int a,b,c; double r1,r2; int d; DataInputStream dis=new DataInputStream(System.in); void getdata() throws IOException { System.out.println("enter a,b,c values"); a=Integer.parseInt(dis.readLine()); b=Integer.parseInt(dis.readLine()); c=Integer.parseInt(dis.readLine()); d=(b*b)-(4*a*c); } void logic() { if(d>0) { System.out.println("roots are real....."); r1=((-b)+Math.sqrt(d))/(2*a); r2=((-b)-Math.sqrt(d))/(2*a); System.out.println("roots are r1:"+r1+"\t r2:"+r2); } else System.out.println("roots are imaginary...."); } public static void main(String[] args) throws IOException { Quard q=new Quard(); q.getdata(); q.logic(); } } output: E:\java programs>javac Quard.java E:\java programs>java Quard enter a,b,c values 1 -5 6 roots are real..... roots are r1:3.0 r2:2.0

Page 5: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 5 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

b). The Fibonacci sequence is defined by the following rule: The fist two values in the sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it. Write a Java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence. import java.io.*; class Fibo { int a=0,b=1,c; int n; void non_recursive(int n) { for(;c<n;) { c=a+b; System.out.println("\t"+c); a=b; b=c; } } void recursive(int a,int b,int n) { int t3; t3=a+b; if(t3<n) { System.out.println("\t"+t3); recursive(b,t3,n); } else return; } public static void main(String[] args) throws IOException { Fibo f=new Fibo(); DataInputStream dis=new DataInputStream(System.in); System.out.println("enter n value"); int n=Integer.parseInt(dis.readLine()); f.a=0;f.b=1; System.out.println("using non-recursive method fibonacci series ......."); System.out.println(f.a+"\t"+f.b); f.non_recursive(n); System.out.println("using recursiv method fibonacci series...."); f.recursive(0,1,n); } }

Page 6: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 6 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Output: E:\java programs>javac Fibo.java Note: Fibo.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. E:\java programs>java Fibo enter n value 30 using non-recursive method fibonacci series ....... 0 1 1 2 3 5 8 13 21 34 using recursive method fibonacci series.... 1 2 3 5 8 13 21

Page 7: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 7 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

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. import java.io.*; class Prime { DataInputStream dis=new DataInputStream(System.in); int n; void getdata() throws IOException { System.out.println("enter n value"); n=Integer.parseInt(dis.readLine()); } void logic() { for(int i=1;i<=n;i++) { int count=0; for(int j=1;j<=i;j++) { if(i%j==0) { count++; } } if(count==2) { System.out.println(i+"\t"); } } } public static void main(String[] args) throws IOException { Prime p=new Prime(); p.getdata(); p.logic(); } }

Page 8: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 8 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

output: E:\java programs>javac Prime.java Note: Prime.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. E:\java programs>java Prime enter n value 20 2 3 5 7 11 13 17 19

Page 9: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 9 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

b). Write a Java program to multiply two given matrices. import java.io.*; class Matrics { int a[][]=new int[3][3]; int b[][]=new int[3][3]; int c[][]=new int[3][3]; int i,j,k; DataInputStream dis=new DataInputStream(System.in); void getdata() throws IOException { System.out.println("enter 9 values"); for(i=0;i<3;i++) for(j=0;j<3;j++) a[i][j]=Integer.parseInt(dis.readLine()); System.out.println("enter 9 values"); for(i=0;i<3;i++) for(j=0;j<3;j++) b[i][j]=Integer.parseInt(dis.readLine()); } void logic() { for(i=0;i<3;i++) { for(j=0;j<3;j++) { c[i][j]=0; for(k=0;k<3;k++) c[i][j]+=a[i][k]*b[k][j]; } } } void printdata() { System.out.println("multiplication of two matrics is:"); for(i=0;i<3;i++) { for(j=0;j<3;j++) System.out.print(c[i][j]+"\t"); System.out.println(); } } public static void main(String[] args) throws IOException { Matrics m=new Matrics(); m.getdata(); m.logic(); m.printdata(); } }

Page 10: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 10 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

output: E:\java programs>javac Matrics.java Note: Matrics.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. E:\java programs>java Matrics enter 9 values 1 2 3 4 5 6 7 8 9 enter 9 values 1 2 3 4 5 6 7 8 9 multiplication of two matrics is: 30 36 42 66 81 96 102 126 150

Page 11: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 11 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

c) Write a Java Program that reads a line of integers, and then displays each integer, and the sum of all the integers (Use StringTokenizer class of java.util) import java.io.*; import java.util.*; public class TokenTest { public static void main(String args[]) { Scanner Scanner=new Scanner(System.in); System.out.println("enter sequence of integer with space b/w them and press enter"); String digit=Scanner.nextLine(); StringTokenizer Token=new StringTokenizer(digit); int i=0,dig=0,sum=0,x; while(Token.hasMoreTokens()) { String s=Token.nextToken(); dig=Integer.parseInt(s); System.out.println(digit+""); sum=sum+dig; } System.out.println(); System.out.println("sum is"+sum); } } output: E:\java Programs>javac TokenTest.java E:\java Progams>java TokenTest

Page 12: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 12 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Week 3: a). Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome. import java.io.*; class Palindrome { String st; StringBuffer str; DataInputStream dis=new DataInputStream(System.in); void getdata() throws IOException { System.out.println("enter the string"); st=dis.readLine(); str=new StringBuffer(st); } void logic() { StringBuffer st1; st1=str.reverse(); System.out.println(st1); String st2=String.valueOf(st1); if(st.equals(st2)) System.out.println("given string is palindrome"); else System.out.println("not palindrome"); } public static void main(String[] args) throws IOException { Palindrome p=new Palindrome(); p.getdata(); p.logic(); } } output: E:\java programs>javac Palindrome.java Note: Palindrome.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. E:\java programs>java Palindrome enter the string madam madam given string is palindrome

Page 13: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 13 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

b) Write a Java program for sorting a given list of names in ascending order. import java.io.*; class Sort { String st[]=new String[5]; String st1[]=new String[5]; int i; void getData() throws IOException { DataInputStream dis=new DataInputStream(System.in); System.out.println("enter 5 string values"); for(i=0;i<st.length;i++) st[i]=dis.readLine(); } void logic() { for(i=0;i<st1.length;i++) st1[i]=st[i]; for(i=0;i<st.length;i++) { if((st[i++].compareTo(st1[i]))>0) { String temp=st[i]; st[i]=st[i+1]; st[i+1]=temp; } } for(i=0;i<st.length;i++) System.out.println(st[i]); } public static void main(String[] args) throws IOException { Sort s=new Sort(); s.getData(); s.logic(); } }

Page 14: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 14 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Week 4: a). Write a Java program that reads a file name from the user, then displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes. import java.io.*; class FileMethod { public static void main(String[] args) { File f=new File("e:\\java programs","java manual.rtf"); if(f.exists()) { System.out.println("file is exist and details about file...."); System.out.println("File name:"+f.getName()); System.out.println("Absolute path:"+f.getAbsolutePath()); System.out.println(f.canRead()?"file is readable":"file is not readable"); System.out.println(f.canWrite()?"file is writable":"file is not writable"); System.out.println(f.isFile()?"f is file":"f is directory"); System.out.println("length of file "+f.length()+" Bytes"); } else System.out.println("file does not exist"); } } output: E:\java programs>javac FileMethod.java E:\java programs>java FileMethod file is exist and details about file.... File name:java manual.rtf Absolute path:e:\java programs\java manual.rtf file is readable file is writable f is file length of file 7831129 Bytes

Page 15: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 15 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

b) Write a Java program that reads a file and displays the file on the screen, with a line number before each line. import java.io.*; class file2 { public static void main(String args[])throws Exception { FileInputStream F1=new FileInputStream("Consumer.java"); int n=F1.available(); System.out.println(n); int j=1; for(int i=0;i<n;i++) { char ch=(char)F1.read(); char c='\n'; if(c==ch) { System.out.println(""+j); j++; } System.out.println(ch); } } } output: E:/java Programs>javac file2.java E/java Programs>java file2

Page 16: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 16 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

c) Write a Java program that displays the number of characters, lines and words in a text file. import java.io.*; class FileMethod2 { public static void main(String[] args) throws IOException { FileInputStream f=new FileInputStream("e:\\java programs\\hi.txt"); int size; size=f.available(); int chars=0,words=1,lines=0; for(int i=0;i<size;i++) { chars++; if(f.read()==32) words++; if(f.read()==10) lines++; } words++; System.out.println("characters with spaces"+chars+"\n words"+words+"\n lines"+lines); f.close(); } } output: E:\java programs>javac FileMethod2.java E:\java programs>java FileMethod2 characters with spaces 20 words 4 lines 1

Page 17: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 17 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Week 5: Write a Java program that:

i) Implements stack ADT. ii) Converts infix expression into Postfix form iii) Evaluates the postfix expression

Implements stack ADT: import java.io.*; import java.util.*; class stackdemo { public static void main(String[] args) { Stack st1=new Stack(); Stack st2=new Stack(); for(int i=0;i<10;i++) st1.push(i); for(int i=0;i<20;i++) st2.push(i); System.out.println("stack in mystack st1:"); for(int i=0;i<10;i++) System.out.println(st1.pop()); System.out.println("stack in mystack st2:"); for(int i=0;i<10;i++) System.out.println(st2.pop()); } }

Page 18: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 18 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Output: C:\Documents and Settings\YSCE\Desktop\java>javac stackdemo.java Note: stackdemo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. C:\Documents and Settings\YSCE\Desktop\java>java stackdemo stack in mystack st1: 9 8 7 6 5 4 3 2 1 0 stack in mystack st2: 19 18 17 16 15 14 13 12 11 10

Page 19: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 19 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

infix to postfix form: import java.io.*; public class intopost { private stack thestack; private String output=""; private String input; public intopost(String in) { input=in; int stacksize=input.length(); thestack=new stack(stacksize); } public String dotrans() { for(int j=0;j<input.length();j++) { char ch=input.charAt(j); switch(ch) { case'+': case'-': oper(ch,1); break; case'*': case'/': oper(ch,2); break; case'c': thestack.push(ch); break; case'j': paren(ch); break; default: output+=ch; break; } } while (!thestack.isEmpty()) { output +=thestack.pop(); } System.out.println(output); return output; } public void oper(char opthis,int prec1) { while(!thestack.isEmpty()) { char optop=thestack.pop();

Page 20: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 20 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

if(optop=='c') { thestack.push(optop); break; } else { int prec2; if(optop=='+'||optop=='-') prec2=1; else prec2=2; if(prec2<prec1) { thestack.push(optop); break; } else output+=optop; } } thestack.push(opthis); } public void paren(char ch) { while(!thestack.isEmpty()) { char chx=thestack.pop(); if(chx=='c') break; else output +=chx; } } public static void main(String args[])throws IOException { String input=args[0]; String output; intopost thetrans=new intopost(input); output= thetrans.dotrans(); System.out.println("postfix is"+output+"\n"); } } class stack { private int maxsize; private char[] stackarray; private int top; public stack(int m) { maxsize=m; stackarray=new char[maxsize];

Page 21: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 21 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

top=-1; } public void push(char i) { stackarray[++top]=i; } public char pop() { return stackarray[top--]; } public boolean isEmpty() { return(top==-1); } public char peek() { return stackarray[top]; } } Output: C:\Documents and Settings\YSCE\Desktop\java>javac intopost.java C:\Documents and Settings\YSCE\Desktop\java>java intopost a+b*c abc*+ postfix is abc*+

Page 22: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 22 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

week 6: a). Develop an applet that displays a simple message. import java.awt.*; import java.applet.Applet; public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("welcome to Applets",50,50); } } /*<applet code="SimpleApplet.class" height=200 width=400> </applet>*/ output: E:\java programs>javac SimpleApplet.java E:\java programs>appletviewer SimpleApplet.java

Page 23: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 23 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

b). Develop an applet that receives an integer in one text field, and computes its factorial Value and returns it in another text field, when the button named “Compute” is clicked. import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class Fact extends Applet implements ActionListener { Label l1,l2; TextField t1,t2; Button b1; public void init() { l1=new Label("enter the value"); add(l1); t1=new TextField(10); add(t1); b1=new Button("Factorial"); add(b1); b1.addActionListener(this); l2=new Label("Factorial of given no is"); add(l2); t2=new TextField(10); add(t2); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { int fact=fact(Integer.parseInt(t1.getText())); t2.setText(String.valueOf(fact)); } } int fact(int f) { int s=0; if(f==0) return 1; else return f*fact(f-1); } } /*<applet code="Fact.class" height=300 width=300> </applet>*/ output: E:\java programs>javac Fact.java

Page 24: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 24 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

E:\java programs>appletviewer Fact.java

Page 25: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 25 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Week 7: 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 result import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class Calculator extends Applet implements ActionListener { Label l1,l2; TextField t1,t2,t3; Button add1,sub,mul,div; public void init() { l1=new Label("First no"); add(l1); t1=new TextField(10); add(t1); l2=new Label("second no"); add(l2); t2=new TextField(10); add(t2); add1=new Button(" + "); add(add1); add1.addActionListener(this); sub=new Button(" - "); add(sub); sub.addActionListener(this); div=new Button(" / "); add(div); div.addActionListener(this); mul=new Button(" * "); add(mul); mul.addActionListener(this); t3=new TextField(10); add(t3); } public void actionPerformed(ActionEvent e) { if(e.getSource()==add1) { int sum=Integer.parseInt(t1.getText())+Integer.parseInt(t2.getText()); t3.setText(String.valueOf(sum)); } if(e.getSource()==sub) { int sum=Integer.parseInt(t1.getText())-Integer.parseInt(t2.getText()); t3.setText(String.valueOf(sum)); } if(e.getSource()==mul) {

Page 26: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 26 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

int sum=Integer.parseInt(t1.getText())*Integer.parseInt(t2.getText()); t3.setText(String.valueOf(sum)); } if(e.getSource()==div) { double sum=(double)(Integer.parseInt(t1.getText())/Integer.parseInt(t2.getText())); t3.setText(String.valueOf(sum)); } } } /*<applet code="Calculator.class" height=400 width=400> </applet>*/ output: E:\java programs>javac Calculator.java E:\java programs>appletviewer Calculator.java

Page 27: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 27 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Week 8: Write a Java program for handling mouse events import java.awt.*; import java.applet.*; import java.awt.event.*; public class MouseTest extends Applet implements MouseListener,MouseMotionListener { public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent e) { showStatus("mouse clicked at"+e.getX()+","+e.getY()); } public void mouseEntered(MouseEvent e) { showStatus("mouse entered at"+e.getX()+","+e.getY()); } public void mouseExited(MouseEvent e) { showStatus("mouse exited at"+e.getX()+","+e.getY()); } public void mousePressed(MouseEvent e) { showStatus("mouse pressed at"+e.getX()+","+e.getY()); } public void mouseReleased(MouseEvent e) { showStatus("mouse released at"+e.getX()+","+e.getY()); } public void mouseDragged(MouseEvent e) { showStatus("mouse dragged at"+e.getX()+","+e.getY()); } public void mouseMoved(MouseEvent e) { showStatus("mouse moved at"+e.getX()+","+e.getY()); } public void paint(Graphics g) { Font f=new Font("Helvetica",Font.BOLD,20); g.setFont(f); g.drawString("Always keep smiling !!",50,50); g.drawOval(60,60,200,200); g.fillOval(90,120,50,20); g.fillOval(190,120,50,20); g.drawLine(165,125,165,175); g.drawArc(110,130,95,95,0,-180);

Page 28: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 28 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

g.drawLine(165,175,150,160); } } /*<applet code="MouseTest.class" height=400 width=400> </applet>*/ output:E:\java programs>javac MouseTest.java E:\java programs>appletviewer MouseTest.java

Page 29: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 29 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

week 9: a).Write a Java program that creates three threads. First thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three seconds. import java.io.*; class First extends Thread { public void run() { for(;;) { System.out.println("Good Morning"); try{ Thread.sleep(1000); }catch(InterruptedException e){} } } } class Second extends Thread { public void run() { for(;;) { System.out.println("Hello"); try{ Thread.sleep(2000); }catch(InterruptedException e){} } } } class Third extends Thread { public void run() { for(;;) { System.out.println("Welcome"); try{ Thread.sleep(3000); }catch(InterruptedException e){} } } } class MThread {

Page 30: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 30 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

public static void main(String[] args) { Thread t1=new First(); Thread t2=new Second(); Thread t3=new Third(); System.out.println("press Ctrl+c to stop......"); t1.start(); t2.start(); t3.start(); } } output: E:\java programs>javac MThread.java E:\java programs>java MThread press Ctrl+c to stop...... Good Morning Hello Welcome Good Morning Good Morning Hello Good Morning Welcome Good Morning Hello Good Morning Welcome Good Morning Hello Good Morning Good Morning Hello

Page 31: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 31 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

b). Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication class Producer implements Runnable { Stock s; Thread t; Producer(Stock s) { this.s=s; t=new Thread(this,"Producer thread"); t.start(); } public void run() { while(true) { try { t.sleep(750); } catch(InterruptedException e) { } s.addStock((int)(Math.random()*100)); } } void stop() { t.stop(); } } class Consumer implements Runnable { Stock c; Thread t; Consumer(Stock c) { this.c=c; t=new Thread(this,"producer thread"); t.start(); } public void run() { while(true) { try { t.sleep(750); }catch(InterruptedException e) {

Page 32: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 32 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

} c.getStock((int)(Math.random()*100)); } } void stop() { t.stop(); } } class Stock { int goods=0; public synchronized void addStock(int i) { goods=goods+i; System.out.println("Stock added:"+i); System.out.println("present stock:"+goods); notify(); } public synchronized int getStock(int j) { while(true) { if(goods>=j) { goods=goods-j; System.out.println("stock taken away :"+j); System.out.println("present stock:"+goods); break; } else { System.out.println("stock not enough......"); System.out.println("waiting for stocks to come.."); try { wait(); }catch(InterruptedException e){} } } return goods; } public static void main(String args[]) { Stock j=new Stock(); Producer p=new Producer(j); Consumer c=new Consumer(j); try { Thread.sleep(10000); p.stop();

Page 33: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 33 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

c.stop(); p.t.join(); c.t.join(); System.out.println("thread stopped"); } catch(InterruptedException e) {} System.exit(0); } } output: E:\java programs>javac Stock.java E:\java programs>java Stock Stock added:8 present stock:8 stock not enough...... waiting for stocks to come.. Stock added:78 present stock:86 stock taken away :86 present stock:0 Stock added:95 present stock:95 stock taken away :15 present stock:80 Stock added:80 present stock:160 stock taken away :91 present stock:69 Stock added:6 present stock:75 stock taken away :18 present stock:57 Stock added:40 present stock:97 stock taken away :14 present stock:83 Stock added:63 present stock:146 stock taken away :57 present stock:89 Stock added:60 present stock:149 stock taken away :77 present stock:72 Stock added:57 present stock:129 stock taken away :72 present stock:57

Page 34: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 34 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Stock added:65 present stock:122 stock taken away :71 present stock:51 Stock added:58 present stock:109 stock taken away :79 present stock:30 Stock added:58 present stock:88 stock not enough...... waiting for stocks to come.. thread stopped

Page 35: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 35 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

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 ArithmeticException Display the exception in a message dialog box. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class div extends JFrame implements ActionListener { Container c; JButton btn; JLabel lb11,lb12,lb13; JTextField tf1,tf2,tf3; JPanel p; div() { super("Exception handler"); c=getContentPane(); c.setBackground(Color.red); btn=new JButton("Divide"); btn.addActionListener(this); tf1=new JTextField(30); tf2=new JTextField(30); tf3=new JTextField(30); lb11=new JLabel("NUM1"); lb12=new JLabel("NUM2"); lb13=new JLabel("RESULT"); p=new JPanel(); p.setLayout(new GridLayout(3,2)); p.add(lb11); p.add(tf1); p.add(lb12); p.add(tf2); p.add(lb13); p.add(tf3); c.add(new JLabel("DIVISION"),"North"); c.add(p,"Center"); c.add(btn,"South"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); } }); } public void actionPerformed(ActionEvent e) { if(e.getSource()==btn) {

Page 36: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 36 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

try { int a=Integer.parseInt(tf1.getText()); int b=Integer.parseInt(tf2.getText()); Float c=Float.valueOf(a/b); tf3.setText(String.valueOf(c)); } catch(NumberFormatException ex) { tf3.setText("........"); JOptionPane.showMessageDialog(this,"other err "+ex.getMessage()); } catch(ArithmeticException ex) { tf3.setText("........"); JOptionPane.showMessageDialog(this,ex.getMessage()); } } } public static void main(String[] args) { div b=new div(); b.setSize(300,300); b.setVisible(true); } } Output: C:\Documents and Settings\YSCE\Desktop\java>javac div.java C:\Documents and Settings\YSCE\Desktop\java>java div

Page 37: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 37 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Week 11: 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 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) Client program import java.io.*; import java.net.*; class Client { public static void main(String[] args) throws Exception { Socket s=new Socket("localhost",8080); BufferedReader br; PrintStream ps; String str; System.out.println("enter the radius to send the server"); br=new BufferedReader(new InputStreamReader(System.in)); ps=new PrintStream(s.getOutputStream()); ps.println(br.readLine()); br=new BufferedReader(new InputStreamReader(s.getInputStream())); str=br.readLine(); System.out.println("Area of circle:"+str); ps.close(); br.close(); } } Server program: import java.io.*; import java.net.*; class Server { public static void main(String[] args) { try{ ServerSocket ss=new ServerSocket(8080); System.out.println("wait for client request"); Socket s=ss.accept(); BufferedReader br; PrintStream ps; String str;

Page 38: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 38 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

br=new BufferedReader(new InputStreamReader(s.getInputStream())); str=br.readLine(); System.out.println("recieved radius"); double r=Double.parseDouble(str); double area=3.14*r*r; ps=new PrintStream(s.getOutputStream()); ps.println(String.valueOf(area)); ps.close(); br.close(); s.close(); ss.close(); } catch(Exception e) { System.out.println("exception occur at:"+e.toString()); } } } Output: Client side: C:\Documents and Settings\YSCE\Desktop\java>javac client.java C:\Documents and Settings\YSCE\Desktop\java>java Client enter the radius to send the server 10 Area of circle:314.0 Server side: C:\Documents and Settings\YSCE\Desktop\java>javac server.java C:\Documents and Settings\YSCE\Desktop\java>java Server wait for client request recieved radius

Page 39: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 39 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Week 12: a); Write a java program that simulates a traffic light. The program lets the user select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a time No light is on when the program starts. import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class TrafficSignal extends Applet { CheckboxGroup c; Checkbox c1,c2,c3; public void init() { c=new CheckboxGroup(); c1=new Checkbox("RED",c,false); c2=new Checkbox("YELLOW",c,false); c3=new Checkbox("GREEN",c,false); add(c1); add(c2); add(c3); c1.addMouseListener(new Check1()); c2.addMouseListener(new Check2()); c3.addMouseListener(new Check3()); } class Check1 extends MouseAdapter { public void mouseClicked(MouseEvent e) { setBackground(Color.red); } } class Check2 extends MouseAdapter { public void mouseClicked(MouseEvent e) { setBackground(Color.yellow); } } class Check3 extends MouseAdapter { public void mouseClicked(MouseEvent e) { setBackground(Color.green); } } } /*<applet code="TrafficSignal.class" height=300 width=300> </applet>*/

Page 40: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 40 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

output: E:\java programs>javac TrafficSignal.java E:\java programs>appletviewer TrafficSignal.java

Page 41: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 41 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

b). Write a Java program that allows the user to draw lines, rectangles and ovals import java.awt.*; import java.applet.Applet; public class DrawShapes extends Applet { public void paint(Graphics g) { g.drawLine(40,30,200,30); g.drawRect(40,60,70,40); g.fillRect(140,60,70,40); g.drawOval(240,120,70,40); g.fillOval(40,180,70,40); } } /*<applet code="DrawShapes.class" height=500 width=500> </applet>*/ output: E:\java programs>javac DrawShapes.java E:\java programs>appletviewer DrawShapes.java

Page 42: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 42 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

week 13: a). Write a java program to create an abstract class named Shape that contains an empty method named numberOfSides ( ).Provide three classes named Trapezoid, Triangle and Hexagon such that each one of the classes extends the class Shape. Each one of the classes contains only the method numberOfSides ( ) that shows the number of sides in the given geometrical figures. abstract class Shapes { abstract void numberOfSlides(); } class Trapezoid extends Shapes { void numberOfSlides() { System.out.println("no of slides for Trapezoid is 5"); } } class Triangle extends Shapes { void numberOfSlides() { System.out.println("no of slides for triangle is 3"); } } class Hexagon extends Shapes { void numberOfSlides() { System.out.println("no of slides for Hexagon in 8"); } } class Abstractclass { public static void main(String[] args) { Shapes s; s=new Trapezoid(); s.numberOfSlides(); s=new Triangle(); s.numberOfSlides(); s=new Hexagon(); s.numberOfSlides(); } }

Page 43: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 43 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

Output: E:\java programs>javac Abstractclass.java E:\java programs>java Abstractclass no of slides for Trapezoid is 5 no of slides for triangle is 3 no of slides for Hexagon in 8

Page 44: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 44 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

b) Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and the remaining lines correspond to rows in the table. The elements are _eparated by commas. Write a java program to display the table using Jtable component. import java.awt.*; import javax.swing.*; public class Table1 extends JApplet { public void init() { Container con=getContentPane(); BorderLayout b=new BorderLayout(); con.setLayout(b); final String[] colHeads={"name","rollnumber","Dept","percentage"}; final String[][] data={ {"java","0501","cse","70.05%"}, {"ajay","0341","mech","90.78%"}, {"vijaya","0401","ece","70.05%"}, {"nani","0402","ece","80.12%"}, {"lakshmi","0201","ee","80.12%"}, {"malathi","1214","cseit","50.05%"} }; JTable table1=new JTable(data,colHeads); int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane scroll=new JScrollPane(table1,v,h); con.add(scroll); } } /*<applet code="Table1.class" height=400 width=400> </applet>*/ Output: C:\Documents and Settings\YSCE\Desktop\java>javac table1.java C:\Documents and Settings\YSCE\Desktop\java>appletviewer Table1.java

Page 45: Object Oriented Programming Lab Manual

OBJECT ORIENTED PROGRAMMING LAB Page 45 of 45

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM