This document contains a lab manual for an Object Oriented Programming class through Java. It provides examples of Java programs to solve problems related to various topics in OOP including quadratic equations, Fibonacci sequences, prime numbers, matrix multiplication, file handling, stacks, infix to postfix conversion, and postfix expression evaluation. The programs are organized into weekly labs covering topics such as classes and objects, arrays, strings, file I/O, and data structures.
1. OOP Through JAVA Department of Computer Science and Engineering
Department
Of
Computer Science & Engineering
Object Oriented Programming Through JAVA
Lab manual
BALAJI INSTITUTE OF
TECHNOLOGY AND SCIENCE
Department of computer science & engineering
In-charge HOD Principal
Prepared by: Approved &
Reviewed by:
Issued by: w.e.f Date:
Balaji Institute of Technology and Science 1
2. OOP Through JAVA Department of Computer Science and Engineering
BALAJI INSTITUTE OF TECHNOLOGY AND
SCIENCE
Laknepally(V), Narsampet, Warangal
DEPARTMENT OF COMPUTER SCIENCE &
ENGINEERING
Lab Manual for the Academic Year 2011-12
(In accordance with JNTU syllabus)
SUBJECT : OOPs Through JAVA LAB
STREAM : CSE
H.O.D
Balaji Institute of Technology and Science 2
3. OOP Through JAVA Department of Computer Science and Engineering
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");
}
}
}
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]);
Balaji Institute of Technology and Science 3
4. OOP Through JAVA Department of Computer Science and Engineering
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.
import java.lang.*;
import java.io.*;
class prime
{
public static void main(String args[])
{i
nt n=Integer.parseInt(args[0]);
for(int r=0;r<n;r++)
{i
nt t=0;
for(int i=1;i<r;i++)
{i
f (r%i==0)
{ t++;
}}i
f(t<2)
{
System.out.print(r);
System.out.print(" ");
}}}} b) Write a Java program to multiply two given matrices.
import java.lang.*;
Balaji Institute of Technology and Science 4
5. OOP Through JAVA Department of Computer Science and Engineering
import java.io.*;
class arraymul
{
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());
}}}i
nt 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]);
}
Balaji Institute of Technology and Science 5
6. OOP Through JAVA Department of Computer Science and Engineering
}} 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 integer, 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
{
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++)
{i
nt 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 not.
class Palindrome
{
public static void main(String args[])
{
Balaji Institute of Technology and Science 6
7. OOP Through JAVA Department of Computer Science and Engineering
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)
{
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");
for(int i=0;i<n;i++)
{
x[i]=br.readLine();
}
String s=new String();
for(int i=0;i<n;i++)
{
Balaji Institute of Technology and Science 7
8. OOP Through JAVA Department of Computer Science and Engineering
for(int j=0;j<n;j++)
{i
f(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
{
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
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 FileDemo
{
public static void main(String args[])
Balaji Institute of Technology and Science 8
9. OOP Through JAVA Department of Computer Science and Engineering
{
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());
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,
with 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++;
System.out.println(c+t);
}
fr.close();
}
}
Balaji Institute of Technology and Science 9
10. OOP Through JAVA Department of Computer Science and Engineering
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);
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];
Balaji Institute of Technology and Science 10
11. OOP Through JAVA Department of Computer Science and Engineering
int tos;
stack()
{ tos=-1;
}
void push(int item)
{i
f(tos==9)
System.out.println("stack is full");
else
stack[++tos]=item;
}i
nt pop()
{i
f(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());
}}
ii) Converts infix expression into Postfix form .
import java.io.*;
Balaji Institute of Technology and Science 11
12. OOP Through JAVA Department of Computer Science and Engineering
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;
}i
nt pre(char ch)
{
switch(ch)
{
case '-':return 1;
case '+':return 1;
case '*':return 2;
case '/':return 2;
}
return 0;
}
boolean operator(char ch)
{i
f(ch=='/'||ch=='*'||ch=='+'||ch=='-')
return true;
else
return false;
}
boolean isAlpha(char ch)
{i
f(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;
Balaji Institute of Technology and Science 12
13. OOP Through JAVA Department of Computer Science and Engineering
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))
{i
f(stack1[top]==0||(pre(ch)>pre
(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
{
Balaji Institute of Technology and Science 13
14. OOP Through JAVA Department of Computer Science and Engineering
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)
{i
f(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");
Balaji Institute of Technology and Science 14
15. OOP Through JAVA Department of Computer Science and Engineering
return(0);
}
else
{
num=stk[T];
T--;
}
return(num);
} float ExpEval(char sfix[],float data[])
{i
nt j=0;
float op1,op2,fs;
char ch;
while(sfix[j]!='0')
{
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);
}}
Balaji Institute of Technology and Science 15
16. OOP Through JAVA Department of Computer Science and Engineering
class EvalPostFix
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')
{i
f(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));
}}
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);
}}
Balaji Institute of Technology and Science 16
17. OOP Through JAVA Department of Computer Science and Engineering
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.
//<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()
{
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)
{i
nt 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);
Balaji Institute of Technology and Science 17
18. OOP Through JAVA Department of Computer Science and Engineering
}}}
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.
//<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();
p2=new JPanel();
p1.setBackground(Color.gray);
p2.setBackground(Color.gray);
setBackground(Color.lightGray);
l1=new JLabel("Enter the First number :");
p1.add(l1);
t1=new JTextField(10);
p1.add(t1);
l2=new JLabel("Enter the Second number :");
p1.add(l2);
t2=new JTextField(10);
p1.add(t2);
l3=new JLabel("Result");
p1.add(l3);
t3=new JTextField(10);
p1.add(t3);
b1=new JButton("ADD");
p2.add(b1);
b1.addActionListener(this);
b2=new JButton("SUB");
p2.add(b2);
b2.addActionListener(this);
b3=new JButton("MUL");
p2.add(b3);
b3.addActionListener(this);
Balaji Institute of Technology and Science 18
19. OOP Through JAVA Department of Computer Science and Engineering
b4=new JButton("DIVISION");
p2.add(b4);
b4.addActionListener(this);
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.CENTER);
t1.setBackground(Color.yellow);
t2.setBackground(Color.yellow);
t3.setBackground(Color.yellow);
}
public void actionPerformed(ActionEvent ae)
{ try
{i
f (ae.getSource()==b1)
{i
nt x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int sum=x+y;
t3.setText(" "+sum);
}i
f (ae.getSource()==b2)
{i
nt x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int sub=x-y;
t3.setText(" "+sub);
}i
f (ae.getSource()==b3)
{i
nt x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int mul=x*y;
t3.setText(" "+mul);
}i
f (ae.getSource()==b4)
{i
nt 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);
}
Balaji Institute of Technology and Science 19
20. OOP Through JAVA Department of Computer Science and Engineering
}}
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,MouseMotionListener
{
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;
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();
Balaji Institute of Technology and Science 20
21. OOP Through JAVA Department of Computer Science and Engineering
}
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();
}
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 Morning” every one second,
the second thread displays “Hello” every two seconds and the third thread
displays “Welcome” every three
seconds.
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(10);
System.out.println("good morning");
}
}
catch(Exception e)
{ }
}
Balaji Institute of Technology and Science 21
22. OOP Through JAVA Department of Computer Science and Engineering
}
class B extends Thread
{
synchronized public void run()
{
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);
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();
}
Balaji Institute of Technology and Science 22
23. OOP Through JAVA Department of Computer Science and Engineering
}
b) Write a Java program that correctly implements producer consumer
problem using the concept of inter
thread communication.
class Q
{
boolean valueSet=false;
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
("n Exception in put:"+e);
}
this.n=n;
valueSet=true;
System.out.println("nput:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Balaji Institute of Technology and Science 23
24. OOP Through JAVA Department of Computer Science and Engineering
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)
{
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
Balaji Institute of Technology and Science 24
25. OOP Through JAVA Department of Computer Science and Engineering
NumberFormatException. If Num2 were Zero, the program would throw an
ArithmeticException Display the
exception in a message dialog box.
import java.awt.*;
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);
}
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
{
Balaji Institute of Technology and Science 25
26. OOP Through JAVA Department of Computer Science and Engineering
System.out.println(" ");
}
catch(Exception e)
{
System.out.println("ArithematicException"+e);
}
msg="Arithemetic";
repaint();
}
else if((num1<0)||(num2<0))
{
try
{
System.out.println("");
}
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 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).
server.java
import java.net.*;
Balaji Institute of Technology and Science 26
27. OOP Through JAVA Department of Computer Science and Engineering
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;
String result;
rad=Double.parseDouble(br.readLine());
System.out.println("From Client : "+rad);
area=Math.PI*rad*rad;
result="Area is "+area;
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(result);
br.close();
ps.close();
s.close();
ss.close();
}
}
Client.java
import java.net.*;
import java.io.*;
public class client
{
public static void main(String args[]) throws Exception
{
Socket s=new Socket("localhost",2000);
BufferedReader br=new
BufferedReader(new InputStreamReader(System.in));
String rad;
System.out.println("Enter radius of the circle ");
rad=br.readLine();
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(rad);
BufferedReader fs=new
BufferedReader(new InputStreamReader
(s.getInputStream()));
String result=fs.readLine();
System.out.println("From Server : "+result);
br.close();
Balaji Institute of Technology and Science 27
28. OOP Through JAVA Department of Computer Science and Engineering
fs.close();
ps.close();
s.close();
}
}
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 javax.swing.*;
class TrafficLight extends JFrame implements ActionListener
{
String msg=" " ;
private JLabel label;
private JTextField display;
private JRadioButton r1,r2,r3;
private ButtonGroup bg;
private Container c;
public TrafficLight()
{
setLayout(new FlowLayout());
c=getContentPane();
label=new JLabel(" Traffic Light");
display =new JTextField(10);
r1=new JRadioButton("RED");
r2=new JRadioButton("GREEN");
r3=new JRadioButton("YELLOW");
bg=new ButtonGroup();
c.add(label);
c.add(r1);
c.add(r2);
c.add(r3);
c.add(display);
bg.add(r1);
bg.add(r2);
bg.add(r3);
r1.addActionListener(this);
r2.addActionListener(this);
r3.addActionListener(this);
setSize(400,400);
setVisible(true);
c.setBackground(Color.pink);
Balaji Institute of Technology and Science 28
29. OOP Through JAVA Department of Computer Science and Engineering
}
public void actionPerformed(ActionEvent ie)
{
msg=ie.getActionCommand();
if (msg.equals("RED"))
{
c.setBackground(Color.RED);
display.setText(msg+ " :TURN ON");
}
else if (msg.equals("GREEN"))
{
c.setBackground(Color.GREEN);
display.setText(msg+ " :TURN ON");
}
else if (msg.equals("YELLOW"))
{
c.setBackground(Color.YELLOW);
display.setText(msg+ " :TURN ON");
}}
public static void main(String args[])
{
TrafficLight light=new TrafficLight();
light.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
b) Write a Java program that allows the user to draw lines, rectangles and
ovals.
//<applet code="LinesRectsOvals.class" height="250" width="400"> </applet>
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class LinesRectsOvals extends JApplet
{
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.red);
g.drawLine(5,30,350,30);
g.setColor(Color.blue);
g.drawRect(5,40,90,55);
g.fillRect(100,40,90,55);
g.setColor(Color.cyan);
g.fillRoundRect(195,40,90,55,50,50);
g.drawRoundRect(290,40,90,55,20,20);
g.setColor(Color.yellow);
Balaji Institute of Technology and Science 29
30. OOP Through JAVA Department of Computer Science and Engineering
g.draw3DRect(5,100,90,55,true);
g.fill3DRect(100,100,90,55,false);
g.setColor(Color.magenta);
g.drawOval(195,100,90,55);
g.fillOval(290,100,90,55);
}}
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.
import javax.swing.*;
abstract class Shape
{
public abstract void numberOfSides();
}
class Trapezoid extends Shape
{
public void numberOfSides()
{
JOptionPane.showMessageDialog(null,"TRAPEZOID -- Number of sides in trapezoid is 4
(Of which two
are parallel and with no angles)");
}
}
class Triangle extends Shape
{
public void numberOfSides()
{
JOptionPane.showMessageDialog(null,"TRIANGLE -- Number of sides in Triangle is 3 ");
}
}
class Hexagon extends Shape
{
public void numberOfSides()
{
JOptionPane.showMessageDialog(null,"HEXAGON -- Number of sides in Hexagon is 6 ");
}
}
class ShapeDemo
{
Balaji Institute of Technology and Science 30
31. OOP Through JAVA Department of Computer Science and Engineering
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null,"Some of the Geometrical figures are as follows
" );
Trapezoid t=new Trapezoid();
Triangle tg=new Triangle();
Hexagon h=new Hexagon();
t.numberOfSides();
tg.numberOfSides();
h.numberOfSides();
}
}
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
43eparated by commas. Write a java
program to display the table using Jtable component.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class Table1 extends JFrame
{i
nt i=0;
int j=0,k=0;
Object data[][]=new Object[5][4];
Object list[][]=new Object[5][4];
JButton save;
JTable table1;
FileInputStream fis;
DataInputStream dis;
public Table1()
{
String d= " ";
Container con=getContentPane();
con.setLayout(new BorderLayout());
final String[] colHeads={"Name","Roll Number","Department","Percentage"};
try
{
String s=JOptionPane.showInputDialog("Enter the File name present in the
current directory");
FileInputStream fis=new FileInputStream(s);
DataInputStream dis = new DataInputStream(fis);
while ((d=dis.readLine())!=null)
{
Balaji Institute of Technology and Science 31
32. OOP Through JAVA Department of Computer Science and Engineering
StringTokenizer st1=new StringTokenizer(d,",");
while (st1.hasMoreTokens())
{ for (j=0;j<4;j++)
{
data[i][j]=st1.nextToken();
System.out.println(data[i][j]);
}i
++;
}
System.out.println("______________");
}}
catch (Exception e)
{
System.out.println("Eception raised" +e.toString());
} 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,BorderLayout.CENTER);
}
public static void main(String args[])
{
Table1 t=new Table1();
t.setBackground(Color.green);
t.setTitle("Display Data");
t.setSize(500,300);
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
Balaji Institute of Technology and Science 32