Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
DEPARTMENT OF
COMPUTER SCIENCE ENGINEERING
&
INFORMATION TECHNOLOGY
PREPARED BY:
L. CHANDRA SEKHAR
Asst. Professor.(Dept of CSE)
OBJECT ORIENTED PROGRAMMING LAB Page 2 of 45
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)
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.
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:
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;
}
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");
}
}
}
import java.io.*;
class Matrics
{
output:
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
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:
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]);
}
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:
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
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:
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());
}
}
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();
Output:
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:
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:
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)
{
}
}
/*<applet code="Calculator.class" height=400 width=400>
</applet>*/
output:
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);
}
/*<applet code="MouseTest.class" height=400 width=400>
</applet>*/
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 MThread
{
output:
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();
output:
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)
{
}
}
public static void main(String[] args)
{
div b=new div();
b.setSize(300,300);
b.setVisible(true);
}
}
Output:
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
{
}
}
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;
Output:
Client side:
Server side:
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;
output:
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:
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.
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: