SlideShare a Scribd company logo
1 of 32
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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

More Related Content

What's hot (20)

Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
ASP.NET
ASP.NETASP.NET
ASP.NET
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
All experiment of java
All experiment of javaAll experiment of java
All experiment of java
 
Java practical
Java practicalJava practical
Java practical
 
CORE JAVA-2
CORE JAVA-2CORE JAVA-2
CORE JAVA-2
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Java codes
Java codesJava codes
Java codes
 
Java lab 2
Java lab 2Java lab 2
Java lab 2
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
Taking User Input in Java
Taking User Input in JavaTaking User Input in Java
Taking User Input in Java
 
ECET 370 Achievement Education -- www.ecet370.com
ECET 370 Achievement Education -- www.ecet370.comECET 370 Achievement Education -- www.ecet370.com
ECET 370 Achievement Education -- www.ecet370.com
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Core java
Core javaCore java
Core java
 
ECET 370 Redefined Education--ecet370.com
ECET 370 Redefined Education--ecet370.comECET 370 Redefined Education--ecet370.com
ECET 370 Redefined Education--ecet370.com
 
ECET 370 Education Planning--ecet370.com
 ECET 370 Education Planning--ecet370.com ECET 370 Education Planning--ecet370.com
ECET 370 Education Planning--ecet370.com
 
01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB
 
ECET 370 Inspiring Innovation--ecet370.com
ECET 370 Inspiring Innovation--ecet370.comECET 370 Inspiring Innovation--ecet370.com
ECET 370 Inspiring Innovation--ecet370.com
 

Viewers also liked

Mat 045 test 4 review
Mat 045 test 4 reviewMat 045 test 4 review
Mat 045 test 4 reviewMae Guerra
 
Building Risk Management into Enterprise Architecture
Building Risk Management into Enterprise ArchitectureBuilding Risk Management into Enterprise Architecture
Building Risk Management into Enterprise Architectureiasaglobal
 
BBVA Innovation Edge. Gamificación (español)
BBVA Innovation Edge. Gamificación (español)BBVA Innovation Edge. Gamificación (español)
BBVA Innovation Edge. Gamificación (español)Hugo Najera
 
Loyalty with the self
Loyalty with the selfLoyalty with the self
Loyalty with the selfPrateek Jain
 
Splitting up your web app
Splitting up your web appSplitting up your web app
Splitting up your web appAlex Payne
 
Why Scala for Web 2.0?
Why Scala for Web 2.0?Why Scala for Web 2.0?
Why Scala for Web 2.0?Alex Payne
 
Scala eXchange opening
Scala eXchange openingScala eXchange opening
Scala eXchange openingMartin Odersky
 
Functional programming
Functional programmingFunctional programming
Functional programmingPrateek Jain
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako, Vasil Remeniuk
 
In memory grids IMDG
In memory grids IMDGIn memory grids IMDG
In memory grids IMDGPrateek Jain
 
Cr concepts the best resource for gmat cr from ivy-gmat (sandeep gupta)
Cr concepts   the best resource for gmat cr from ivy-gmat (sandeep gupta)Cr concepts   the best resource for gmat cr from ivy-gmat (sandeep gupta)
Cr concepts the best resource for gmat cr from ivy-gmat (sandeep gupta)mamunapece
 
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011Matt Raible
 

Viewers also liked (20)

Forthnet Απρίλιος 2013
Forthnet Απρίλιος 2013Forthnet Απρίλιος 2013
Forthnet Απρίλιος 2013
 
Mat 045 test 4 review
Mat 045 test 4 reviewMat 045 test 4 review
Mat 045 test 4 review
 
Building Risk Management into Enterprise Architecture
Building Risk Management into Enterprise ArchitectureBuilding Risk Management into Enterprise Architecture
Building Risk Management into Enterprise Architecture
 
BBVA Innovation Edge. Gamificación (español)
BBVA Innovation Edge. Gamificación (español)BBVA Innovation Edge. Gamificación (español)
BBVA Innovation Edge. Gamificación (español)
 
My project
My projectMy project
My project
 
No sql
No sqlNo sql
No sql
 
Flatmap
FlatmapFlatmap
Flatmap
 
Loyalty with the self
Loyalty with the selfLoyalty with the self
Loyalty with the self
 
Splitting up your web app
Splitting up your web appSplitting up your web app
Splitting up your web app
 
Scea prateek
Scea prateekScea prateek
Scea prateek
 
Why Scala for Web 2.0?
Why Scala for Web 2.0?Why Scala for Web 2.0?
Why Scala for Web 2.0?
 
Scala eXchange opening
Scala eXchange openingScala eXchange opening
Scala eXchange opening
 
Java Class Loading
Java Class LoadingJava Class Loading
Java Class Loading
 
Java Classloaders
Java ClassloadersJava Classloaders
Java Classloaders
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
In memory grids IMDG
In memory grids IMDGIn memory grids IMDG
In memory grids IMDG
 
Cr concepts the best resource for gmat cr from ivy-gmat (sandeep gupta)
Cr concepts   the best resource for gmat cr from ivy-gmat (sandeep gupta)Cr concepts   the best resource for gmat cr from ivy-gmat (sandeep gupta)
Cr concepts the best resource for gmat cr from ivy-gmat (sandeep gupta)
 
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
 
Manhattan Elite Prep GMAT Prep Tips: The Dos and Don'ts of Math Problems
Manhattan Elite Prep GMAT Prep Tips: The Dos and Don'ts of Math Problems Manhattan Elite Prep GMAT Prep Tips: The Dos and Don'ts of Math Problems
Manhattan Elite Prep GMAT Prep Tips: The Dos and Don'ts of Math Problems
 

Similar to Object oriented programming la bmanual jntu

Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab FileKandarp Tiwari
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
• GUI design using drag and drop feature of IDE(Net beans), • File IO
•	GUI design using drag and drop feature of IDE(Net beans), •	File IO•	GUI design using drag and drop feature of IDE(Net beans), •	File IO
• GUI design using drag and drop feature of IDE(Net beans), • File IOSyedShahroseSohail
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdfamitbhachne
 
Turbinando o compilador do Java 8
Turbinando o compilador do Java 8Turbinando o compilador do Java 8
Turbinando o compilador do Java 8Marcelo de Castro
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdfanupamfootwear
 
JAVA Q2- Write a program that reads strings from the user and writes t.docx
JAVA Q2- Write a program that reads strings from the user and writes t.docxJAVA Q2- Write a program that reads strings from the user and writes t.docx
JAVA Q2- Write a program that reads strings from the user and writes t.docxmichael1810
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)mehul patel
 

Similar to Object oriented programming la bmanual jntu (20)

Java practical
Java practicalJava practical
Java practical
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab File
 
54240326 (1)
54240326 (1)54240326 (1)
54240326 (1)
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
 
Java ppt
Java pptJava ppt
Java ppt
 
Java final lab
Java final labJava final lab
Java final lab
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
• GUI design using drag and drop feature of IDE(Net beans), • File IO
•	GUI design using drag and drop feature of IDE(Net beans), •	File IO•	GUI design using drag and drop feature of IDE(Net beans), •	File IO
• GUI design using drag and drop feature of IDE(Net beans), • File IO
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
Turbinando o compilador do Java 8
Turbinando o compilador do Java 8Turbinando o compilador do Java 8
Turbinando o compilador do Java 8
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
JAVA Q2- Write a program that reads strings from the user and writes t.docx
JAVA Q2- Write a program that reads strings from the user and writes t.docxJAVA Q2- Write a program that reads strings from the user and writes t.docx
JAVA Q2- Write a program that reads strings from the user and writes t.docx
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Introduction to java programming part 2
Introduction to java programming  part 2Introduction to java programming  part 2
Introduction to java programming part 2
 
Java Week4(C) Notepad
Java Week4(C)   NotepadJava Week4(C)   Notepad
Java Week4(C) Notepad
 

Object oriented programming la bmanual jntu

  • 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