0% found this document useful (0 votes)
7 views46 pages

OOP Lab Exercises in Java

The document outlines a lab manual for Object Oriented Programming using Java for the JNTUH B.Tech CSE II-II Semester during 2013-2014. It includes a series of experiments with detailed instructions and sample code for various programming tasks, such as solving quadratic equations, generating Fibonacci sequences, and performing matrix multiplication. The manual serves as a guide for students to practice and implement OOP concepts through practical coding exercises.

Uploaded by

Laxmi Pandey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views46 pages

OOP Lab Exercises in Java

The document outlines a lab manual for Object Oriented Programming using Java for the JNTUH B.Tech CSE II-II Semester during 2013-2014. It includes a series of experiments with detailed instructions and sample code for various programming tasks, such as solving quadratic equations, generating Fibonacci sequences, and performing matrix multiplication. The manual serves as a guide for students to practice and implement OOP concepts through practical coding exercises.

Uploaded by

Laxmi Pandey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] || [Link] || [Link] || [Link].

net

2013-
2014

Object Oriented
Programming Lab
OOPs through Java
JNTUH [Link] CSE II-II Sem

[Link], Assistant Profess in CSE


Malla Reddy Institute of Technology (MRIT)
2013-2014

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

SNO EXP NO EXPERIMENT NAME PAGE


NO
1 a) Write a Java program that prints all real solutions to the 3
quadratic equation ax2+bx+c=0. Read in a ,b, c and use the
quadratic formula. If the discriminate b2-4ac is negative,
display a message stating that there are no real solutions.
2 b) The Fibonacci sequence is defined by the following rules: 4
Week – 1
The first two values in the sequence are 1 and 1. Every
subsequent values is the sum of the two values preceding it.
Write a java program that uses both recursive and non
recursive functions to print the nth value in the Fibonacci
sequence.
3 a) Write a program that prompts the user for an integer and 6
then prints out all prime numbers up to that integer.
4 b) Write a Java program to Multiply two given matrices. 7
Week – 2
5 c) Write a Java program that reads a line of integers and then 10
displays each integer, and the sum of all the integers( Use
String Tokenizer class of [Link])
6 a) Write a Java program that checks whether a given string is 11
a palindrome or not. Ex MADAM is a palindrome
7 b) Write a Java Progarm for sorting a given list of names in 12
Week – 3
ascending order.
8 c) Write a Java Program to make frequency count of words in 13
a given text.
9 a) Write a Java Program that reads a file name from the user, 14
then display 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.
Week - 4
10 b) Write a Java program that reads a file and displays the file 15
on the screen, with a line number before each line.
11 c) Write a Java program that displays the number of 16
characters, lines and words in a text file.
12 Write a Java program that: 17
i) Implement Stack ADT
13 Week – 5 ii) Converts Infix equation into Postfix form 20
14 ii) Evaluate the Postfix expression 23
15 a) Develop an applet that displays a simple message. 24
16 b) Develop an applet that receives an integer in one text field and 25
Week – 6
compute its factorial value in another text field, when the button
named ‘Compute” is clicked.
17 Week - 7 Write a Java program that works as a simple calculator. Use a grid 26
Layout to arrange buttons for the digits and for the +, -, *, /
operations. Add a text field to display the results.
18 Week – 8 Write a Java program for handling mouse and key events 29
19 a) Write a Java program that creates three threads. First thread 31
displays “Good Morning” every one second, the second thread
Week – 9 displays “Hello” every two seconds and the third thread displays
“Welcome” every three seconds.
20 b) Write a Java program that correctly implements producer 33

Object Oriented Programming Lab 1

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

consumer problem using the concept of inter thread


communication
21 Week – 10 Write a program that creates a user interface to perform integer divisions. 35
The user enters two numbers in the text fields, 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 Number Format Exception. If Num2 were Zero, the
program would throw an Arithmetic Exception Display the exception in a
message dialog box.
22 a) Write a java program that simulates a traffic light. The program 38
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
Week – 11 light can be on at a time. No light is on when the program starts.
23 b) Write a Java program that allows the user to draw lines, rectangle 40
and ovals.
24 a) Write a java program to create an abstract class named Shape that 41
contain 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 class
contains only the method numberOfSides() that shows the
Week – 12 number of sides in the given geometrical figures.
25 b) Suppose that a table [Link] is stored in a text file. The first line 44
in the file is the header, and the remaining lines correspond to
rows in the table. The elements are separated by commas. Write a
java program to display the table using JTable component.

Object Oriented Programming Lab 2

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week 1:

a) Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c=0.
Read in a ,b, c and use the quadratic formula. If the discriminate b2-4ac is negative, display
a message stating that there are no real solutions.

import [Link].*;
import [Link].*;
class Quad
{
public static void main(String[] args) throws Exception
{
int a,b,c,d;
float r1,r2;
[Link]("Enter a , b & c values");
DataInputStream dis=new DataInputStream([Link]);
a=[Link]([Link]());
b=[Link]([Link]());
c=[Link]([Link]());
d=(b*b)-(4*a*c);
if (d==0)
{
r1=r2=(float)(-b/(2*a));
[Link]("The roots are equal\nr1="+r1+" and r2="+r2);
}
else if(d>0)
{
r1=(float)(-b+[Link](d))/(2*a);
r2=(float)(-[Link](d))/(2*a);
[Link]("The roots are real & distinct\n r1="+r1+" and r2="+r2);
}
else if(d<0)
{
r1=(float)(-b/(2*a));
r2=(float)([Link](-d)/(2*a));
[Link]("The roots are complex &
imaginary\nr1="+r1+"+i"+r2+"\nr2="+r1+"-i"+r2);
}
}
}
Output:
D:\Lab>javac [Link]
D:\Lab>java Quad
Enter a , b & c values
321
The roots are complex & imaginary
r1=0.0+i0.47140452
r2=0.0-i0.47140452

Object Oriented Programming Lab 3

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week b)

The Fibonacci sequence is defined by the following rules: The first two values in the sequence are 1
and 1. Every subsequent values is the sum of the two values preceding it. Write a java program that
uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence.

import [Link].*;
import [Link].*;
class Fibonacci
{
int Fib(int n)
{
if(n==0)
return 0;
else if(n==1) return 1;
else
return Fib(n-1)+Fib(n-2);
}
}
class Fibrec
{
public static void main(String[] args) throws Exception
{
int n;
long r=0;
[Link]("Enter N value:");
DataInputStream dis=new DataInputStream([Link]);
n=[Link]([Link]());
Fibonacci f=new Fibonacci();
for(int i=1;i<=n; i++)
{
[Link]([Link](i)+"\t");
r=[Link](n);
}
[Link]("\nThe "+n+" the value in the Fibonacci Series : "+r);
}
}

OUTPUT:

D:\Lab>javac [Link]
D:\Lab>java Fibrec
Enter N value:
10
1 1 2 3 5 8 13 21 34 55

The 10 the value in the Fibonacci Series : 55

Object Oriented Programming Lab 4

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

import [Link].*;
import [Link].*;
class Fibonacci
{
int a=1,b=1,c;
int Fib(int no)
{
for(int i=1;i<=no-2;i++)
{
c=a+b;
[Link]("\t"+c);
a=b;
b=c;
}
return c;
}
}
class Fibnonrec
{
public static void main(String[] args) throws Exception
{
int n,r;
[Link]("Enter N value:");
DataInputStream dis=new DataInputStream([Link]);
n=[Link]([Link]());
Fibonacci f=new Fibonacci();
[Link](f.a+"\t"+f.b);
r=[Link](n);
[Link]("\nThe "+n+" the value in the Fibonacci Series : "+r);
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java Fibnonrec
Enter N value:
10
1 1 2 3 5 8 13 21 34 55
The 10 the value in the Fibonacci Series : 55

Object Oriented Programming Lab 5

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week 2:
a) Write a program that prompts the user for an integer and then prints out all prime
numbers up to that integer.
import [Link].*;
class Primenos
{
public static void main(String[] args) throws Exception
{
int n,fact;
[Link]("Enter the range of Prime No U want");
DataInputStream dis=new DataInputStream([Link]);
n=[Link]([Link]());
[Link]("Prime No's from 1 to "+n+" is");
for(int i=1;i<=n;i++)
{
fact=1;
for(int x=1;x<i;x++)
if(i%x==0)
fact++;
if(fact==2)
[Link](i+"\t");
}
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java Primenos
Enter the range of Prime No U want
100
Prime No's from 1 to 100 is
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
73 79 83 89 97

Object Oriented Programming Lab 6

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week b) Write a Java program to Multiply two given matrices.


import [Link].*;
class Matrix
{
int a[][],b[][],c[][];
int i,j,k,m,n,p,q;
DataInputStream dis=new DataInputStream([Link]);
void readA()
{
try
{
[Link]("Enter the Size of Matrix A (Rows and Columns) ");
m=[Link]([Link]());
n=[Link]([Link]());
a=new int[m][n];
[Link]("Enter the Matrix A values:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
a[i][j]=[Link]([Link]());
}
catch(Exception e){}
}
void readB()
{
try
{
[Link]("Enter the Size of Matrix B (Rows and Columns) ");
p=[Link]([Link]());
q=[Link]([Link]());
b=new int[p][q];
[Link]("Enter the Matrix A values:");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
b[i][j]=[Link]([Link]());
}catch(Exception e){}
}
void printA()
{
[Link]("Matrix A \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
[Link](a[i][j]+"\t");
}
[Link](" ");
}
}
void printB()
{
[Link]("Matrix B \n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
[Link](b[i][j]+"\t");

Object Oriented Programming Lab 7

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

}
[Link](" ");
}
}
void mulAB()
{
c=new int[m][q];
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]+=a[i][k]*b[k][j];
}
}
void printC()
{
[Link]("Matrix Multiplication is \n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
[Link](c[i][j]+"\t");
}
[Link](" ");
}
}

}
class MatrixMul
{
public static void main(String[] args) throws Exception
{
Matrix mat=new Matrix();
[Link]();
[Link]();
if(mat.n==mat.p)
{
[Link]();
[Link]();
[Link]();
[Link]();
}
else
[Link]("Matrix Multiplication is Not Possible");
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java MatrixMul
Enter the Size of Matrix A (Rows and Columns)
2
2
Enter the Matrix A values:
1 2
1 2

Object Oriented Programming Lab 8

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Enter the Size of Matrix B (Rows and Columns)


2
2
Enter the Matrix A values:
2 1
2 1
Matrix A
1 2
1 2
Matrix B
2 1
2 1
Matrix Multiplication is
6 3
6 3

D:\Lab>java MatrixMul
Enter the Size of Matrix A (Rows and Columns)
2
3
Enter the Matrix A values:
2 3 2
3 2 1
Enter the Size of Matrix B (Rows and Columns)
2
3
Enter the Matrix A values:
2 2 2
2 2 2
Matrix Multiplication is Not Possible

Object Oriented Programming Lab 9

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week c)
Write a Java program that reads a line of integers and then displays each integer, and the sum of
all the integers( Use String Tokenizer class of [Link])
import [Link].*;
import [Link].*;
class StringToken
{
public static void main(String[] args) throws Exception
{
int i=0,sum=0;
DataInputStream dis=new DataInputStream([Link]);
[Link]("Enter the Line of Integer Separated by Space");
String str=[Link]();
int n=[Link]();
int a[]=new int[n];
StringTokenizer st=new StringTokenizer(str);
while([Link]())
{
a[i]=[Link]([Link]());
[Link]("a["+i+"]= "+a[i]);
i++;
}
for(i=0;i<n;i++)
sum+=a[i];
[Link]("Sum is = "+sum);
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java StringToken
Enter the Line of Integer Separated by Space
12345
a[0]= 1
a[1]= 2
a[2]= 3
a[3]= 4
a[4]= 5
Sum is = 15

Object Oriented Programming Lab 10

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week 3:
a) Write a Java program that checks whether a given string is a palindrome or not. Ex
MADAM is a palindrome

import [Link].*;
class Palindrome
{
public static void main(String[] args) throws Exception
{
String str1, str2;
DataInputStream dis=new DataInputStream([Link]);
[Link]("Enter a String");
str1=[Link]();
StringBuffer tmp=new StringBuffer(str1);
[Link]();
str2=new String(tmp);
[Link]("The String after Reverse is "+str2);
if([Link](str2))
[Link]("The given String "+str1+" is palindrome");
else
[Link]("The given String "+str1+" is not palindrome");
}
}

OUTPUT:

D:\Lab>javac [Link]
D:\Lab>java Palindrome
Enter a String
madam
The String after Reverse is madam
The given String madam is palindrome

D:\Lab>java Palindrome
Enter a String
abcde
The String after Reverse is edcba
The given String abcde is not palindrome

Object Oriented Programming Lab 11

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

b) Write a Java Progarm for sorting a given list of names in ascending order.
import [Link].*;
class SortingStr
{
public static void main(String[] args) throws Exception
{
int n,i,j;
DataInputStream dis=new DataInputStream([Link]);
[Link]("Ente the number of Strings :");
n=[Link]([Link]());
String str[]=new String[n];
for(i=0;i<n;i++)
{
[Link]("Enter string "+(i+1)+" :");
str[i]=[Link]();
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if((str[i].compareTo(str[j]))>0)
{
String tmp=str[i];
str[i]=str[j];
str[j]=tmp;
}
}
}
[Link]("The String after Sorting : ");
for(i=0;i<n;i++)
[Link](str[i]);
}
}

OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java SortingStr
Ente the number of Strings :
5
Enter string 1 : rama
Enter string 2 : krishna
Enter string 3 : raju
Enter string 4 : abc
Enter string 5 : sai

The String after Sorting :


abc
krishna
raju
rama
sai

Object Oriented Programming Lab 12

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

c) Write a Java Program to make frequency count of words in a given text.


import [Link].*;
import [Link].*;
class Freq
{
public static void main(String[] args) throws Exception
{
DataInputStream dis=new DataInputStream([Link]);
[Link]("Enter a String :");
String s=[Link]();
StringTokenizer st=new StringTokenizer(s);
int count=1,i=0;
int size=[Link]();
String words[]=new String[size];
while([Link]())
{
words[i]=[Link]();
i++;
}
for(i=0;i<size;i++)
{
count=1;
for(int j=i+1;j<size;j++)
{
if(words[i].equals(words[j]))
{
count++;
move(words,j,size);
size--;
j--;
}
}
[Link](words[i]+" occurs "+count+" no of times");
}
}
static void move(String a[],int i,int size)
{
while(i<size)
{
if(i==size-1)
a[i]=null;
else
a[i]=a[i+1];
i++;
}
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java Freq
Enter a String :
jai bolo hanuman ki jai
jai occurs 2 no of times
bolo occurs 1 no of times
hanuman occurs 1 no of times
ki occurs 1 no of times

Object Oriented Programming Lab 13

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week 4:
a) Write a Java Program that reads a file name from the user, then display 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 [Link].*;
class FileEx
{
public static void main(String[] args)
{
DataInputStream dis=new DataInputStream([Link]);
File f=new File("D:/Lab/abc/[Link]");
[Link]("File Name = "+[Link]());
[Link]("File Path = " +[Link]());
[Link]("File parent = "+[Link]());
[Link]([Link]()?" is a File":"not a file");
[Link]([Link]()?"it is a directory":"not a directory");
[Link]([Link]()?" it is readable":"it is not readable");
[Link]([Link]()?"it is writable":"it is not writable");
[Link]("length of file is"+[Link]());
}
}

OUTPUT:

D:\Lab>javac [Link]

D:\Lab>java FileEx

File Name = [Link]


File Path = D:\Lab\abc\[Link]
File parent = D:\Lab\abc
is a File
not a directory
it is readable
it is not writable
length of file is68

Object Oriented Programming Lab 14

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week b) Write a Java program that reads a file and displays the file on the screen, with a line
number before each line.
import [Link].*;
class FileRead
{
public static void main(String[] args) throws Exception
{
File f=new File("[Link]");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String str=[Link]();
int i=1;
while((str=[Link]())!=null)
{
[Link](i++ +" "+str);
}
[Link]();
}
}

OUTPUT:

D:\Lab>javac [Link]
D:\Lab>java FileRead

1 class FileRead
2{
3 public static void main(String[] args) throws Exception
4 {
5 File f=new File("[Link]");
6 FileReader fr=new FileReader(f);
7 BufferedReader br=new BufferedReader(fr);
8 String str=[Link]();
9 int i=1;
10 while((str=[Link]())!=null)
11 {
12 [Link](i++ +" "+str);
13 }
14 [Link]();
15 }
16 }

Object Oriented Programming Lab 15

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week c) Write a Java program that displays the number of characters, lines and words in a text
file.
import [Link].*;
import [Link].*;
class FileCount
{
public static void main(String[] args) throws Exception
{
String fname;
[Link]("Enter a filename:");
DataInputStream dis=new DataInputStream([Link]);
fname=[Link]();
FileReader f=new FileReader(fname);
BufferedReader br=new BufferedReader(f);
String str;
int words=0,lines=0,chars=0;
while((str=[Link]())!=null)
{
StringTokenizer st=new StringTokenizer(str);
lines++;
words+=[Link]();
int i=0,n;
n=[Link]();
for(i=0;i<n;i++)
{
char ch=[Link](i);
if(ch!=' ')
chars++;
}
}
[Link]("the number of lines in the file are = "+lines);
[Link]("the number of words in the file are = "+words);
[Link]("the number of characters in the file are = "+chars);

}
}

OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java FileCount

Enter a filename:
[Link]
the number of lines in the file are = 34
the number of words in the file are = 85
the number of characters in the file are = 749

Object Oriented Programming Lab 16

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week 5: a) Write a Java program that:


i) Implement Stack ADT
import [Link].*;
class StackDemo
{
public static void main(String[] args) throws Exception
{
Stack st=new Stack();
DataInputStream dis=new DataInputStream([Link]);
while(true)
{
[Link]("MENU\[Link]\[Link]\[Link]\[Link]");
[Link]("Enter Ur Choice:");
int ch=[Link]([Link]());
switch(ch)
{
case 1: [Link]("Enter element to Push into Stack:");
int a=[Link]([Link]());
[Link](a);break;
case 2: [Link]();break;
case 3:[Link]();break;
case 4:[Link](0);break;
}
}
}
}
interface StackADT
{
void push(Object o);
void pop();
void display();
}

class Stack implements StackADT


{
Object o[];
int top=-1;
int size=10;
Stack()
{
o=new Object[10];
}
Stack(int size)
{
o=new Object[size];
}
public void push(Object obj)
{
if (size==[Link]-1)
[Link]("Stack is OverFlow");
else
o[++top]=obj;
}
public void pop()
{

Object Oriented Programming Lab 17

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

if(top==-1)
[Link]("Stack is empty");
else
{
[Link]("Element "+o[top]+"is deleted from stack");
top=top-1;
}
}
public void display()
{
if(top==-1)
[Link]("Stack is empty");
else
[Link]("Elements in the Stack are:");
for(int i=0;i<=top;i++)
[Link](o[i]);
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java StackDemo
MENU
[Link]
[Link]
[Link]
[Link]
Enter Ur Choice:
3
Stack is empty
MENU
[Link]
[Link]
[Link]
[Link]
Enter Ur Choice:
1
Enter element to Push into Stack:
10
MENU
[Link]
[Link]
[Link]
[Link]
Enter Ur Choice:
1
Enter element to Push into Stack:
20
MENU
[Link]
[Link]
[Link]
[Link]

Object Oriented Programming Lab 18

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Enter Ur Choice:
2
Element 20is deleted from stack
MENU
[Link]
[Link]
[Link]
[Link]
Enter Ur Choice:
2
Element 10is deleted from stack
MENU
[Link]
[Link]
[Link]
[Link]
Enter Ur Choice:
2
Stack is empty
MENU
[Link]
[Link]
[Link]
[Link]
Enter Ur Choice:
4

Object Oriented Programming Lab 19

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

ii) Converts Infix equation into Postfix form


import [Link].*;
import [Link].*;
class charstack
{
int top,size;
char stack[],ele;
charstack(int n)
{
size=n;
top=-1;
stack=new char[n];
}
void push(char x)
{
ele=x;
if(!isfull())
{
stack[++top]=ele;
}
else
[Link]("stack is full");
}
char pop()
{
if(!isempty())
{
return stack[top--];
}
else
{
[Link]("stack is empty");
return 'a';
}
}
boolean isempty()
{
if(top==-1)
return true;
else
return false;
}
boolean isfull()
{
if(top>size)
return true;
else
return false;
}
void display()
{
if(!isempty())
[Link]("="+stack[top]);
else
[Link]("stack is empty");

Object Oriented Programming Lab 20

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

}
char peek()
{
return stack[top];
}
}
class InfixToPostfix
{
charstack cs;
char pf[];
InfixToPostfix()
{
cs=new charstack(50);
pf=new char[50];
}
boolean iop(char op)
{
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='('||op==')'||op=='^'||op=='%')
return true;
else
return false;
}
int prec(char op)
{
if(op=='+'||op=='-')
return 1;
else if(op=='/'||op=='*')
return 2;
else if(op=='%'||op=='^')
return 3;
return 0;
}
void infixtop(String infix)
{
char isym;
int j=0;
char ir[]=[Link]();
for(int i=0;i<[Link];i++)
{
isym=ir[i];
if(!iop(isym))
{
pf[j]=isym;
j++;
}
else
{
if(isym=='('||[Link]())
[Link](isym);
else if(isym==')')
{
while([Link]()!='(')
{
pf[j]=[Link]();
j++;
}

Object Oriented Programming Lab 21

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

char v=[Link]();
}
else if([Link]())
[Link](isym);
else if([Link]()||[Link]()=='('||(prec([Link]())<prec(isym)))
[Link](isym);
else
{
while((![Link]())&&([Link]()!='(')&&prec([Link]())>=prec(isym))
{
pf[j]=[Link]();
j++;
}
[Link](isym);
}
}
}
while(![Link]())
{
pf[j]=[Link]();
j++;
}
}
void display1()
{
for(int i=0;i<[Link]-1;i++)
[Link](pf[i]);
}
public static void main(String args[])throws Exception
{
InfixToPostfix ob=new InfixToPostfix();
Scanner r=new Scanner([Link]);
[Link]("enter any equation:");
String s=[Link]();
[Link](s);
ob.display1();
}
}

OUTPUT:

D:\Lab>javac [Link]
D:\Lab>java InfixToPostfix
enter any equation:
a+b*c-d
abc*+d-

Object Oriented Programming Lab 22

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

iii) Evaluate the Postfix expression


import [Link].*;
import [Link].*;
class PostEval
{
public static void main(String[] args) throws Exception
{
String postfixexp;
DataInputStream dis=new DataInputStream([Link]);
[Link]("Enter the Postfix Expression to be evaluated:");
postfixexp=[Link]();
[Link]<Integer> st=new [Link]<Integer>();
int ans=0;
for(int i=0;i<[Link]();i++)
{
char ch=[Link](i);
if(ch>'0'&&ch<='9')
{
String str=(new Character(ch)).toString();
[Link]([Link](str));
}
else
{
int n2=[Link]().intValue();
int n1=[Link]().intValue();
switch(ch)
{
case '+': ans=n1+n2;break;
case '-':ans=n1-n2;break;
case '*':ans=n1*n2;break;
case '/':ans=n1/n2;break;
default: [Link]("Invalid operator");break;
}
[Link](new Integer(ans));
}
}
[Link]("Value of the Postfix expression is "+[Link]());

}
}

OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java PostEval
Enter the Postfix Expression to be evaluated:
123*+4-
Value of the Postfix expression is 3

Object Oriented Programming Lab 23

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week 6 :
a ) Develop an applet that displays a simple message.

import [Link].*;
import [Link].*;
/*<applet code="MyApplet" width=500 height=200>
</applet>*/
public class MyApplet extends Applet
{
String str="Welcome to MallaReddy Institute of Tech.";
public void init()
{
setBackground([Link]);
setForeground([Link]);
Font f=new Font("Dialog",[Link],25);
setFont(f);
}
public void paint(Graphics g)
{
[Link](str,10,100);
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>appletviewer [Link] (OR) D:\Lab>appletviewer [Link]

Object Oriented Programming Lab 24

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

b) Develop an applet that receives an integer in one text field and compute its factorial value in another
text field, when the button named ‘Compute” is clicked.
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="FactApplet" width=500 height=250> </applet>*/
public class FactApplet extends Applet implements ActionListener
{
TextField num, res;
Button b1;
public void init()
{
setLayout(null);
Label l1=new Label("Enter the Number:");
[Link](10,50,100,30);
num=new TextField();
[Link](200,50,100,30);
Label l2=new Label("The Factorial is :");
[Link](10,100,100,40);
res=new TextField();
[Link](200,100,100,40);
b1=new Button("Compute");
[Link](200,150,70,40);
add(l1);
add(l2);
add(num);
add(res);
add(b1);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
if(([Link]())==b1)
{
int n=[Link]([Link]());
int i,fact=1;
for(i=1;i<=n;i++)
fact=fact*i;
[Link](" "+fact);
}
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>appletviewer [Link]

Object Oriented Programming Lab 25

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

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 results.

import [Link].*;
import [Link].*;
class Calculator extends Frame implements ActionListener
{
TextField f;
boolean reset=false,opset=false;
String s=" ";
int n1=0,n2=0,res=0;
char op=' ';
Calculator()
{
setVisible(true);
setTitle("CALCULATOR");
setSize(600,600);
setLayout(null);
Button b[]=new Button[16];
Panel p=new Panel();
[Link](new GridLayout(4,4)) ;
[Link](200,200,200,200);
b[0]=new Button("0");
for(int i=1;i<10;i++)
{
[Link](b[i]=new Button(i+" "));
}
b[10]=new Button("+");
b[11]=new Button("-");
b[12]=new Button("*");
b[13]=new Button("/");
b[14]=new Button("=");
b[15]=new Button("C");
[Link](b[0]);
[Link](b[10]);
[Link](b[11]);
[Link](b[12]);
[Link](b[13]);
[Link](b[14]);
[Link](b[15]);
f=new TextField("0");
[Link](200,160,200,40);
add(f);
add(p);
for(int j=0;j<16;j++)
{
b[j].addActionListener(this);
}
}
public static void main(String args[])
{
new Calculator();
}
public void actionPerformed(ActionEvent e)
{
String s=" ";

Object Oriented Programming Lab 26

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

char ch=([Link]().charAt(0));
switch(ch)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (!reset)
{
if((s=[Link]()).equals("0"))
{
[Link](ch+"");
reset=false;
}
else
{
s=[Link]();
[Link](s+ch);
}
}
else
{
[Link](ch+"");
reset=false;
}
break;
case '+':
case '-':
case '*':
case '/':
if (!opset)
{
n1=[Link]([Link]());
op=ch;
opset=true;
[Link]("0");
break;
}
else
{
n2=[Link]([Link]());
if(op=='+') res=n1+n2;
if(op=='-') res=n1-n2;
if(op=='*') res=n1*n2;
if(op=='/') res=n1/n2;
[Link](res+"");
n1=res;
op=ch;
reset=true;
break;

Object Oriented Programming Lab 27

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

}
case '=':
n2=[Link]([Link]());
if(op=='+') res=n1+n2;
if(op=='-') res=n1-n2;
if(op=='*') res=n1*n2;
if(op=='/') res=n1/n2;
[Link](res+"");
reset=true;
opset=false;
break;
case 'C': n1=n2=res=0;
op=' ';
[Link]("0");
reset=false;
opset=false;
break;

}
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java Calculator

Object Oriented Programming Lab 28

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week 8 : Write a Java program for handling mouse and key events
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="MouseDemo" width=400 height=400> </applet>*/
public class MouseDemo extends Applet implements MouseListener,MouseMotionListener
{
String msg=" ";
int mx=0,my=0;
public void init()
{
setBackground([Link]);
setForeground([Link]);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me){
mx=0;my=10;
msg="mouse clicked";
repaint();
}
public void mouseEntered(MouseEvent me){
mx=0;my=10;
msg="mouse entered";
repaint();
}
public void mouseExited(MouseEvent me){
mx=0;my=10;
msg="mouse exited";
repaint();
}
public void mousePressed(MouseEvent me){
mx=[Link]();
my=[Link]();
msg="Down";
repaint();
}
public void mouseReleased(MouseEvent me){
mx=[Link]();
my=[Link]();
msg="Up";
repaint();
}
public void mouseDragged(MouseEvent me){
mx=[Link]();
my=[Link]();
msg="*";
showStatus("moving mouse at"+[Link]()+","+[Link]());
}
public void mouseMoved(MouseEvent me){
showStatus("mouse is moving");
}
public void paint(Graphics g){
[Link](msg,mx,my);
}
}

Object Oriented Programming Lab 29

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

OUTPUT:
D:\Lab>javac [Link]
D:\Lab>appletviewer [Link]

Object Oriented Programming Lab 30

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

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 hree
seconds.

import [Link].*;
class One extends Thread
{
public void run()
{
for(int i=0;i<100;i++)
{
try{
[Link](1000); }
catch(InterruptedException e){
[Link](e); }
[Link]("Good Morning");
}
}
}
class Two extends Thread
{
public void run()
{
for(int i=0;i<100;i++)
{
try{
[Link](2000); }
catch(InterruptedException e)
{
[Link](e);
}
[Link]("Hello ");
}
}
}
class Three implements Runnable
{
public void run()
{
for(int i=0;i<100;i++)
{
try{
[Link](3000); }
catch(InterruptedException e){
[Link](e); }
[Link]("Wel come");
}
}
}
class ThreadEx
{
public static void main(String[] args)
{
One t1=new One();
Two t2=new Two();

Object Oriented Programming Lab 31

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Three tt=new Three();


Thread t3=new Thread(tt);
[Link]("One");
[Link]("Two");
[Link]("Three");
[Link](t1);
[Link](t2);
[Link](t3);
Thread t=[Link]();
[Link](t);
[Link]();[Link]();[Link]();
}
}
OUTPUT:

D:\Lab>javac [Link]
D:\Lab>java ThreadEx

Thread[One,5,main]
Thread[Two,5,main]
Thread[Three,5,main]
Thread[main,5,main]
Good Morning
Good Morning
Hello
Wel come
Good Morning
Hello
Good Morning
Good Morning
Hello
Wel come
Good Morning
Good Morning
Hello
Good Morning

Object Oriented Programming Lab 32

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

c) Write a Java program that correctly implements producer consumer problem using the concept of
inter thread communication
import [Link].*;
class Thread1
{
int n;
boolean valueset=false;
synchronized int get()
{
if (!valueset)
try
{
wait();
}
catch (Exception e)
{
[Link]("Excepton occur at : "+e);
}
[Link]("get" +n);
try
{
[Link](1000);
}
catch (Exception e)
{
[Link]("Excepton occur at : "+e);
}
valueset=false;
notify();
return n;
}
synchronized int put(int n)
{
if (valueset)
try
{
wait();
}
catch (Exception e)
{
[Link]("Excepton occur at : "+e);
}
this.n=n;
valueset=true;
[Link]("put"+n);
try
{
[Link](1000);
}
catch (Exception e)
{
[Link]("Excepton occur at : "+e);
}
notify();
return n;
}

Object Oriented Programming Lab 33

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

}
class Producer implements Runnable
{
Thread1 t;
Producer(Thread1 t)
{
this.t=t;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while (true)
{
[Link](i++);
}
}
}
class Consumer implements Runnable
{
Thread1 t;
Consumer(Thread1 t)
{
this.t=t;
new Thread(this,"Consumer").start();
}
public void run()
{
int i=0;
while (true)
{
[Link]();
}
}
}
class ProducerConsumer
{
public static void main(String[] args) throws IOException
{
Thread1 t=new Thread1();
new Producer(t);
new Consumer(t);
[Link]("Press Control+c to exit");
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java ProducerConsumer
put0
Press Control+c to exit
get0
put1
get1
put2
get2
put3

Object Oriented Programming Lab 34

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week 10:
Write a program that creates a user interface to perform integer divisions. The user enters two numbers in
the text fields, 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 Number Format
Exception. If Num2 were Zero, the program would throw an Arithmetic Exception Display the exception in a
message dialog box.

import [Link].*;
import [Link].*;
class NumDiv extends Frame implements ActionListener
{
TextField num1, num2, res;
Button division;
String msg=" ";
Label l1,l2;
NumDiv()
{
l1=new Label("Enter First Number");
l2=new Label("Enter Second Number");
num1=new TextField(30);
num2=new TextField(30);
res=new TextField(100);
division=new Button("Division");
setLayout(null);
setForeground([Link]);
setFont(new Font("Ariel", [Link],15));
[Link](100,100,200,30);
[Link](100,150,200,30);
[Link](350,100,100,30);
[Link](350,150,100,30);
[Link](200,200,100,30);
[Link](100,250,300,30);
add(l1); add(num1);
add(l2); add(num2);
add(res);
add(division);
setSize(600,600);
setVisible(true);
setTitle("DIvision");
setBackground(new Color(250,160,250));
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](this);
}
public void paint(Graphics g)
{
[Link]([Link]);
[Link](new Font("Arial",[Link],30));
}

public static void main(String[] args)

Object Oriented Programming Lab 35

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

{
new NumDiv();
}
public void actionPerformed(ActionEvent e)
{
msg="";
int n1=1;int n2=1;int temp=1;
String s1=[Link]();
String s2=[Link]();
try
{
n1=[Link](s1);
n2=[Link](s2);
}
catch(NumberFormatException ex)
{
MyDialog d=new MyDialog(this, "NumberFormatException Dialog",ex);
}
if(n2==0)
{
try{ temp=n1/n2; } catch(ArithmeticException e1) { MyDialog d=new
MyDialog(this,"ArithmaticExceptionDialog",e1); }
}
else
{
msg+=n1/n2;
}
[Link](msg);
}
}
class MyDialog extends Dialog
{
MyDialog(Frame f, String s, Exception e)
{
super(f,s,false);
setVisible(true);
setSize(500,500);
setForeground([Link]);
setFont(new Font("Arial",[Link],15));
setLayout(null);
Label l=new Label([Link]());
[Link](20,100,500,30);
add(l);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}
}

Object Oriented Programming Lab 36

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java NumDiv

Object Oriented Programming Lab 37

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week 11:
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 [Link].*;
import [Link].*;
class Traffic extends Frame implements ItemListener
{
String clr="";
Traffic()
{
Checkbox c1,c2,c3;
CheckboxGroup cbg=new CheckboxGroup();
c1=new Checkbox("red",true,cbg);
c2=new Checkbox("green",true,cbg);
c3=new Checkbox("yellow",true,cbg);
setSize(500,500);
setTitle("Traffic Signal");
setVisible(true);
setLayout(new FlowLayout([Link]));
add(c1); add(c2); add(c3);
[Link](this);
[Link](this);
[Link](this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}
public static void main(String[] args)
{
new Traffic();
}
public void itemStateChanged(ItemEvent e)
{
clr=([Link]()).toString();
repaint();
}
public void paint(Graphics g)
{
[Link]("Traffic signals",200,250);
[Link](200,300,50,50);
[Link](200,400,50,50);
[Link](200,500,50,50);
[Link](180,200,100,400);
if([Link]("red"))
{
[Link]([Link]);
[Link](200,300,50,50);
}
if([Link]("green"))
{

Object Oriented Programming Lab 38

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

[Link]([Link]);
[Link](200,400,50,50);
}
if([Link]("yellow"))
{
[Link]([Link]);
[Link](200,500,50,50);
}
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java Traffic

Object Oriented Programming Lab 39

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

b) Write a Java program that allows the user to draw lines, rectangle and ovals.
import [Link].*;
import [Link].*;
import [Link].*;
class draw extends Frame
{
draw(){
setTitle("Drawing different Shapes");
setSize(500,500);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
[Link](0); } } );
}
public static void main(String[] args)
{
new draw();
}
public void paint(Graphics g)
{
[Link]([Link]);
[Link](100,80,350,80);
[Link](140,140,50,100);
[Link](200,140,70,70);
[Link](300,140,100,150,60,60);
[Link](140,340,100,100);
[Link](300,340,100,100);
[Link]([Link]);
[Link](120,500,70,50,0,-90);
[Link](180,500,100,150,10,+60);
[Link]([Link]);
int x[]={300,500,380,550,670};
int y[]={550,580,600,680,490};
[Link](x,y,5);
}
}
OUTPUT:

Object Oriented Programming Lab 40

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Week 12:
a) Write a java program to create an abstract class named Shape that contain 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 class contains only the method
numberOfSides() that shows the number of sides in the given geometrical figures.
import [Link].*;
import [Link].*;
abstract class Shape
{
abstract int numberOfSides();
}
class Trapezoid extends Shape
{
int numberOfSides()
{
return 4;
}
}
class Triangle extends Shape
{
int numberOfSides()
{
return 3;
}
}
class Hexagon extends Shape
{
int numberOfSides()
{
return 6;
}
}
class ShapeMain extends Frame implements TextListener
{
TextField f;
int n=0,nl=0;
Shape S;
ShapeMain()
{
setSize(500,500);
setVisible(true);
setTitle("Shape");
setLayout(new FlowLayout([Link]));
Label l=new Label("Enter number");
f=new TextField("0",10);
add(l); add(f);
[Link](this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
[Link](0); } } );
}
public static void main(String[] args)
{
new ShapeMain();
}
public void paint(Graphics g)

Object Oriented Programming Lab 41

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

{
int x[]={100,150,175,150,100,75};
int y[]={100,100,150,200,200,150};
[Link](x,y,n);
[Link]("Number of sides are:"+nl,300,300);
}
public void textValueChanged(TextEvent e)
{
Trapezoid t1=new Trapezoid();
Triangle t2=new Triangle();
Hexagon h=new Hexagon();
String msg=[Link]();
n=[Link](msg);
if([Link]("3"))
{
S=t2;
nl=[Link]();
}
if([Link]("4"))
{
S=t1;
nl=[Link]();
}
if([Link]("6"))
{
S=h;
nl=[Link]();
}
repaint();
}
}
OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java ShapeMain

Object Oriented Programming Lab 42

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

Object Oriented Programming Lab 43

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

b) Suppose that a table [Link] 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 separated by commas. Write a java
program to display the table using JTable component.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

class table extends JFrame


{
static int r=0,i=0,j=0,c=0;
static Object d[][];
static Object h[];
table()
{
setVisible(true);
setSize(500,500);
Label l=new Label("Malla Reddy Institue of Technology");
setTitle("TABLE DEMO");
setLayout(new FlowLayout([Link]));
JTable j=new JTable(d,h);
JScrollPane jsp=new JScrollPane(j);
add(l); add(jsp);
}
public static void main(String[] args) throws IOException
{
FileReader f=new FileReader("[Link]");
BufferedReader b=new BufferedReader(f);
String s=[Link]();
StringTokenizer g=new StringTokenizer(s,",");
c=[Link]();
h=new Object[c];
while([Link]())
{
h[i]=[Link]();
i++;
}
while((s=[Link]())!=null)
r++;
d=new Object[r][c];
BufferedReader br=new BufferedReader(new FileReader("[Link]"));
String e=[Link]();
for(i=0;i<r;i++)
{
e=[Link]();
StringTokenizer st=new StringTokenizer(e,",");
while([Link]())
{
d[i][j]=[Link]();
j++;
}
j=0;
}
new table();
}
}

Object Oriented Programming Lab 44

[Link] || [Link]
[Link] || [Link] || [Link] || [Link]

Object Oriented Programming Lab

OUTPUT:
D:\Lab>javac [Link]
D:\Lab>java table

Object Oriented Programming Lab 45

[Link] || [Link]

You might also like