0% found this document useful (0 votes)
22 views36 pages

Java OOP Lab Manual for CSE Students

The document is a lab manual for the Object Oriented Programming through Java course at Vaageswari College of Engineering. It includes a syllabus with a list of experiments that cover various Java programming concepts such as creating a simple calculator, developing applets, handling exceptions, and implementing multi-threading. Each experiment provides a brief description and sample code to guide students in their practical learning.

Uploaded by

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

Java OOP Lab Manual for CSE Students

The document is a lab manual for the Object Oriented Programming through Java course at Vaageswari College of Engineering. It includes a syllabus with a list of experiments that cover various Java programming concepts such as creating a simple calculator, developing applets, handling exceptions, and implementing multi-threading. Each experiment provides a brief description and sample code to guide students in their practical learning.

Uploaded by

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

VAAGESWARI COLLEGE OF ENGINEERING

THIMMAPUR, KARIMNAGAR

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB


(II YEAR CSE/ I SEMESTER)

PREPARED BY

[Link], ASSOCIATE PROFESSOR,

Department of Computer Science and Engineering,

Vaageswari College Of Engineering

OBJECT ORIENTED PROGRAMMING THROUGH JAVA


LAB MANUAL
SYLLABUS

List Of Experiments

1. Use Eclipse or Net bean platform and acquaint yourself with the various menus. Create a
test project, add a test class, and run it. See how you can use auto suggestions, auto fill.
Try code formatter and code refactoring like renaming variables, methods, and classes.
Try debug step by step with a small program of about 10 to 15 lines which contains at
least one if else condition and a for loop.
2. 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. Handle any possible exceptions like divided by zero.
3. A) Develop an applet in Java that displays a simple message.
B) Develop an applet in Java 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.
4. Write a Java 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 Num
2 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 Number Format Exception. If Num2
were Zero, the program would throw an Arithmetic Exception. Display the exception in a
message dialog box.
5. Write a Java program that implements a multi-thread application that has three threads.
First thread generates a random integer every 1 second and if the value is even, the
second thread computes the square of the number and prints. If the value is odd, the third
thread will print the value of the cube of the number.
6. Write a Java program for the following:
Create a doubly linked list of elements.
Delete a given element from the above list.
Display the contents of the list after deletion.
7. Write a Java program that simulates a traffic light. The program lets the user select one of
three lights: red, yellow, or green with radio buttons. On selecting a button, an
appropriate message with “Stop” or “Ready” or “Go” should appear above the buttons in
the selected color. Initially, there is no message shown.
8. Write a Java program to create an abstract class named Shape that contains two integers
and an empty method named print Area (). Provide three classes named Rectangle,
Triangle, and Circle such that each one of the classes extends the class Shape. Each one
of the classes contains only the method print Area () that prints the area of the given
shape.
9. Suppose that a table named [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 Labels in Grid
Layout.
10. Write a Java program that handles all mouse events and shows the event name at the
center of the window when a mouse event is fired (Use Adapter classes).
11. Write a Java program that loads names and phone numbers from a text file where the data
organized as one line per record and each field in a record are separated by a tab (\t). It
takes a name or phone number as input and prints the corresponding other value from
the hash table (hint: use hash tables).
12. Write a Java program that correctly implements the producer – consumer problem using
the concept of inter thread communication.
13. Write a Java program to list all the files in a directory including the files present in all its
subdirectories.
EXPERIMENT-1

Use eclipse or Netbean platform and acquaint with the various menus, create a test
project, add a test class and run it see how you can use auto suggestions, auto fill. Try
code formatter and code refactoring like renaming variables, methods and classes. Try
debug step by step with a smallprogramofabout 10 to 15 lineswhich containsat least one
ifelse condition and a for loop.

Sample_Program.java

//Importing packages
import [Link];
import [Link];
// Creating Class
class Sample_Program {
// main method
public static void main(String args[]) {
int i,count=0,n;
// creating scanner object
Scanner sc=new Scanner([Link]);
// get input number from user
[Link]("Enter Any Number : ");
n=[Link]();
// logic to check prime or not
for(i=1;i<=n;i++) {
if(n%i==0) {
count++;
}
}
if(count==2)
[Link](n+" is prime");
else
[Link](n+" is not prime");

}
}

OUTPUT:
EXPERIMENT-2

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. Handle any
possible exceptions like divided by zero.

Source code :

/* Program to create a Simple Calculator */


import [Link].*;
import [Link].*;
public class MyCalculator extends Frame implements ActionListener {
double num1,num2,result;
Label lbl1,lbl2,lbl3;
TextField tf1,tf2,tf3;
Button btn1,btn2,btn3,btn4;
char op;
MyCalculator() {
lbl1=new Label("Number 1: ");
[Link](50,100,100,30);

tf1=new TextField();
[Link](160,100,100,30);

lbl2=new Label("Number 2: ");


[Link](50,170,100,30);

tf2=new TextField();
[Link](160,170,100,30);

btn1=new Button("+");
[Link](50,250,40,40);

btn2=new Button("-");
[Link](120,250,40,40);

btn3=new Button("*");
[Link](190,250,40,40);

btn4=new Button("/");
[Link](260,250,40,40);

lbl3=new Label("Result : ");


[Link](50,320,100,30);

tf3=new TextField();
[Link](160,320,100,30);

[Link](this);
[Link](this);
[Link](this);
[Link](this);

add(lbl1); add(lbl2); add(lbl3);


add(tf1); add(tf2); add(tf3);
add(btn1); add(btn2); add(btn3); add(btn4);

setSize(400,500);
setLayout(null);
setTitle("Calculator");
setVisible(true);

public void actionPerformed(ActionEvent ae) {

num1 = [Link]([Link]());
num2 = [Link]([Link]());

if([Link]() == btn1)
{
result = num1 + num2;
[Link]([Link](result));
}
if([Link]() == btn2)
{
result = num1 - num2;
[Link]([Link](result));
}
if([Link]() == btn3)
{
result = num1 * num2;
[Link]([Link](result));
}
if([Link]() == btn4)
{
result = num1 / num2;
[Link]([Link](result));
}
}

public static void main(String args[]) {


MyCalculator calc=new MyCalculator();
}
}
OUTPUT:
EXPERIMENT-3

Develop an applet in Java that displays a simple message.

Aim: a) Develop an applet in Java that displays a simple message.

Source Code:

/* Develop a applet to display the simple message */

import [Link].*;

import [Link].*;

public class First Applet extends Applet

Public void paint(Graphics g)

[Link]([Link]);

Font font = new Font("Arial", [Link], 16);

[Link](font);

[Link]("This is My First Applet",60,110);

OUTPUT :
Develop an applet in Java 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.
/** Develop applet to find factorial of the given number */
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="FactorialApplet" width=500 height=250>
</applet>*/
public class FactorialApplet extends Applet implements ActionListener {
Label L1,L2;
TextField T1,T2;
Button B1;
public void init() {
L1=new Label("Enter any Number : ");
add(L1);
T1=new TextField(10);
add(T1);
L2=new Label("Factorial of Num : ");
add(L2);
T2=new TextField(10);
add(T2);
B1=new Button("Compute");
add(B1);
[Link](this);
}
public void actionPerformed(ActionEvent e) {
if([Link]()==B1)
{
int value=[Link]([Link]());
int fact=factorial(value);
[Link]([Link](fact));
}
}
int factorial(int n) {
if(n==0)
return 1;
else
return n*factorial(n-1);
}
}
OUTPUT:
EXPERIMENT-4

Write a Java 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 Num 2 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 Number Format Exception. If Num2 were Zero, the
program would throw an Arithmetic Exception. Display the exception in a message dialog
box.

/* Develop an java program to perform division */


import [Link].*;
import [Link].*;
import [Link].*;
public class DivisionApp extends Frame implements ActionListener {
Label L1,L2,L3;
TextField T1,T2,T3;
Button B1;
DivisionApp() {
L1=new Label("First Number :");
[Link](50,100,100,30);
add(L1);

T1=new TextField(10);
[Link](160,100,100,30);
add(T1);

L2=new Label("Second Number :");


[Link](50,150,100,30);
add(L2);

T2=new TextField(10);
[Link](160,150,100,30);
add(T2);

B1=new Button("Divide");
[Link](100,200,100,30);
add(B1);
[Link](this);

L3=new Label("Result");
[Link](50,250,100,30);
add(L3);

T3=new TextField();
[Link](160,250,100,30);
add(T3);
setSize(400,500);
setLayout(null);
setTitle("Division APP");
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if([Link]()==B1) {
try {
double value1=[Link]([Link]());
double value2=[Link]([Link]());
double result=value1 % value2;
[Link]([Link](result));
}
catch(NumberFormatException nfe) {
[Link](this,"Not a number");
}
catch(ArithmeticException ae) {
[Link](this,"Divided by Zero");
}
}
}
public static void main(String args[]) {
DivisionApp div=new DivisionApp();
}
}

OUTPUT :
EXPERIMENT-5

Write a Java program that implements a multi-thread application that has three threads.
First thread generates random integer every 1 second and if the value is even, second
thread computes the square of the number and prints. If the value is odd, the third thread
will print the value of cube of the number.

Source code:

import [Link].*;
// class for Even Number
class EvenNum implements Runnable {
public int a;
public EvenNum(int a) {
this.a = a;
}
public void run() {
[Link]("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);
}
} // class for Odd Number
class OddNum implements Runnable {
public int a;
public OddNum(int a) {
this.a = a;
}
public void run() {
[Link]("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);
}
}
// class to generate random number
class RandomNumGenerator extends Thread {
public void run() {
int n = 0;
Random rand = new Random();
try {
for (int i = 0; i < 10; i++) {
n = [Link](20);
[Link]("Generated Number is " + n);
// check if random number is even or odd
if (n % 2 == 0) {
Thread thread1 = new Thread(new EvenNum(n));
[Link]();
}
else {
Thread thread2 = new Thread(new OddNum(n));
[Link]();
}
// thread wait for 1 second
[Link](1000);
[Link]("------------------------------------");
}
}
catch (Exception ex) {
[Link]([Link]());
}
}
}
// Driver class
public class MultiThreadRandOddEven {
public static void main(String[] args) {
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}

OUTPUT :
EXPERIMENT-6

Write a program for the following:i) Create a doubly linked list of elements.
ii) Delete a given element from the above [Link])Display the contents of the list after
deletion.

Source Code:
[Link]

import [Link].*;
public class DoublyLinkListDemo {
public static void main(String[] args) {
int i,ch,element,position;
LinkedList<Integer> dblList = new LinkedList<Integer>();
[Link]("[Link] element at begining");
[Link]("[Link] element at end");
[Link]("[Link] element at position");
[Link]("[Link] a given element");
[Link]("[Link] elements in the list");
[Link]("[Link]");
Scanner sc=new Scanner([Link]);
do {
[Link]("Choose your choice(1 - 6) :");
ch=[Link]();
switch(ch) {
case 1: // To read element form the user
[Link]("Enter an element to insert at begining : ");
element=[Link]();
// to add element to doubly linked list at begining
[Link](element);
[Link]("Successfully Inserted");
break;
case 2: // To read element form the user
[Link]("Enter an element to insert at end : ");
element=[Link]();
// to add element to doubly linked list at end
[Link](element);
[Link]("Successfully Inserted");
break;
case 3: // To read position form the user
[Link]("Enter position to insert element : ");
position=[Link]();
// checks if the position is lessthan or equal to list size.
if(position<=[Link]()) {
// To read element
[Link]("Enter element : ");
element=[Link]();
// to add element to doubly linked list at given position
[Link](position,element);
[Link]("Successfully Inserted");
}
else {
[Link]("Enter the size between 0 to"+[Link]());
}
break;
case 4: // To read element form the user to remove
[Link]("Enter element to remove : ");
Integer ele_rm;
ele_rm=[Link]();
if ([Link](ele_rm)){
[Link](ele_rm);
[Link]("Successfully Deleted");
Iterator itr=[Link]();
[Link]("Elements after deleting :"+ele_rm);
while([Link]()) {
[Link]([Link]()+"<->");
}
[Link]("NULL");
}
else {
[Link]("Element not found");
}
break;

case 5: // To Display elements in the list


Iterator itr=[Link]();
[Link]("Elements in the list :");
while([Link]()) {
[Link]([Link]()+"<->");
}
[Link]("NULL");
break;

case 6: [Link]("Program terminated");


break;
default:[Link]("Invalid choice");
}
}
while(ch!=6);
}
}
OUTPUT:

EXPERIMENT-7
Write a Java program that simulates a traffic light. The program lets the user selects one of
three lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate
message with Stop, Ready, or Go should appear above the buttons in the selected color.
Initially, there is no message shown

Source Code:
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
class TrafficLights extends JFrame implements ActionListener {
JLabel lbl1, lbl2;
JRadioButton rl,gl,ol;
ButtonGroup bg;
TrafficLights() {
Font fontL = new Font("Verdana", [Link], 70);
lbl1 = new JLabel();
[Link](170,30,300,200);
[Link](fontL);
add(lbl1);

Font fontR = new Font("Verdana", [Link], 16);


lbl2 = new JLabel("Select Lights");
[Link](20,250,130,50);
[Link](fontR);
add(lbl2);

rl = new JRadioButton("Red Light");


[Link](160,250,120,50);
[Link]([Link]);
[Link](fontR);
add(rl);
[Link](this);

ol = new JRadioButton("Orange Light");


[Link](300,250,150,50);
[Link]([Link]);
[Link](fontR);
add(ol);
[Link](this);

gl = new JRadioButton("Green Light");


[Link](460,250,140,50);
[Link]([Link]);
[Link](fontR);
add(gl);
[Link](this);
bg = new ButtonGroup();
[Link](rl);[Link](ol);[Link](gl);
setTitle("Traffic Light Simulator");
setSize(650,400);
setLayout(null);
setVisible(true);
}
// To read selected item
public void actionPerformed(ActionEvent ae) {
if([Link]() == rl)
{
[Link]("STOP");
[Link]([Link]);
}
if([Link]() == ol)
{
[Link]("READY");
[Link]([Link]);
}
if([Link]() == gl)
{
[Link]("GO");
[Link]([Link]);
}
}
// main method
public static void main(String[] args) {
new TrafficLights();
}
}

OUTPUT :
EXPERIMENT-8

Write a Java program to create an abstract class named Shape that contains two integers
and an empty method named print Area (). Provide three classes named Rectangle,
Triangle, and Circle such that each one of the classes extends the class Shape. Each one of
the classes contains only the method print Area () that prints the area of the given shape.

Source Code:

[Link]

import [Link].*;
abstract class Shape {
public int x,y;
public abstract void printArea();
}
class Rectangle1 extends Shape {
public void printArea() {
float area;
area= x * y;
[Link]("Area of Rectangle is " +area);
}
}
class Triangle extends Shape {
public void printArea() {
float area;
area= (x * y) / 2.0f;
[Link]("Area of Triangle is " + area);
}
}
class Circle extends Shape {
public void printArea() {
float area;
area=(22 * x * x) / 7.0f;
[Link]("Area of Circle is " + area);
}
}
public class AreaOfShapes {
public static void main(String[] args) {
int choice;
Scanner sc=new Scanner([Link]);
[Link]("Menu \n [Link] of Rectangle \n [Link] of Traingle \n [Link] of Circle
");
[Link]("Enter your choice : ");
choice=[Link]();
switch(choice) {
case 1: [Link]("Enter length and breadth for area of rectangle : ");
Rectangle1 r = new Rectangle1();
r.x=[Link]();
r.y=[Link]();
[Link]();
break;
case 2: [Link]("Enter bredth and height for area of traingle : ");
Triangle t = new Triangle();
t.x=[Link]();
t.y=[Link]();
[Link]();
break;
case 3: [Link]("Enter radius for area of circle : ");
Circle c = new Circle();
c.x = [Link]();
[Link]();
break;
default:[Link]("Enter correct choice");
}
}
}

OUTPUT :
EXPERIMENT-9

Suppose that a table named [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 Labels in Grid
Layout.

Source Code:
[Link]

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Text_To_Table extends JFrame
{
public void convertTexttotable()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
GridLayout g = new GridLayout(0, 4);
setLayout(g);
try
{
FileInputStream fis = new FileInputStream("./[Link]");
Scanner sc = new Scanner(fis);
String[] arrayList;
String str;
while ([Link]())
{
str = [Link]();
arrayList = [Link](",");
for (String i : arrayList)
{
add(new Label(i));
}
}
}
catch (Exception ex) {
[Link]();
}
setVisible(true);
setTitle("Display Data in Table");
}
}
public class TableText
{
public static void main(String[] args)
{
Text_To_Table tt = new Text_To_Table();
[Link]();
}
}

[Link]

NAME,NUMBER,MARKS,RESULT
NAVEEN,501,544,PASS
RAMESH,503,344,PASS
DURGA,521,344,PASS
ASHOK,532,344,PASS
MADHU,543,344,PASS

OUTPUT :
EXPERIMENT-10

Write a java program that handles all mouse events and shows the event name at the center
of the window when a mouse event is fired (Use Adapter classes).

Source Code:

[Link]

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class MouseEventPerformer extends JFrame implements MouseListener
{
JLabel l1;
public MouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout([Link]));
l1 = new JLabel();
Font f = new Font("Verdana", [Link], 20);
[Link](f);
[Link]([Link]);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
[Link]("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
[Link]("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
[Link]("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
[Link]("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
[Link]("Mouse Clicked");
}
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
}

OUTPUT :
EXPERIMENT-11

Program that loads names and phone numbers from a text file where the data is organized
as one line per record and each filed in a record are separated by a tab (\t). It takes a name
or phone number as input and prints the corresponding other value from the hash table
(hint: use hash tables).

Source Code:
[Link]
import [Link].*;
import [Link].*;
public class Contacts
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("[Link]");
Scanner sc=new Scanner(fin).useDelimiter("\t");
Hashtable<String,String> ht=new Hashtable<String,String> ();
String[] strary;
String record,name;
[Link]("Phonebook");
[Link]("***********");
[Link]("Name \tNumber");
[Link]("*****\t******");
while([Link]())
{
String[] ary;
record=[Link]();
strary=[Link]("\t");
[Link](strary[0],strary[1]);
[Link](strary[0]+" \t "+strary[1]);
}
[Link]("--------------------------");
Scanner s=new Scanner([Link]);
[Link]("Type the name as given in the phonebook : ");
name=[Link]();
name=[Link]();
if([Link](name))
{
[Link]("phone no is "+[Link](name));
}
else
{
[Link]("Name is not matched");
}
}
catch(Exception e)
{
[Link](e);
}
}
}

OUTPUT:

[Link]

madhu 8801123456
ravi 9885123456
suresh 9666123456
sona 7878123456
kiran 6767123456
EXPERIMENT-12

Write a Java program that correctly implements the producer – consumer problem using
the concept of inter thread communication

Source Code:

[Link]

// create a class
class Items
{
int count = 1000;
synchronized void consume(int cnt)
{
[Link]("Items :"+[Link]);
[Link]("Consumer : Going to consume "+cnt);
if ([Link] < cnt)
{
[Link]("Low : waiting for produce..");
try
{
[Link](10000);
wait();
}
catch (InterruptedException e)
{}
}
[Link] = [Link] - cnt;
[Link]("consume competed");
[Link]("Current :"+[Link]);

synchronized void produce(int cnt)


{
[Link]("Producer : Going to produce "+cnt);
[Link] = [Link] + cnt;
[Link]("Current :"+[Link]);
[Link]("produce Completed");
notify();
}
}
// creating a Thread1
class Consumer extends Thread
{
Items pt;
Consumer(Items pt)
{
[Link] = pt;
}
public void run()
{
[Link](1500);
}
}
// creating a Thread2
class Producer extends Thread
{
Items pt;
Producer(Items pt)
{
[Link] = pt;
}
public void run()
{
[Link](800);
}

}
// main class
class ProducerConsumer
{
public static void main(String[] args)
{
Items obj = new Items();
Consumer t1 = new Consumer(obj);
Producer t2 = new Producer(obj);
[Link]();
[Link]();
}
}

OUTPUT:
EXPERIMENT-13

Write a Java program to list all the files in a directory including the files present in all its
subdirectories.

Source Code:
[Link]
import [Link].*;
public class ListOfFilesInDir {
public static void listOfFiles(File dirPath){
File fileList[] = [Link]();
for(File file : fileList) {
if([Link]()) {
[Link]([Link]());
} else {
[Link]("-----------------------------");
[Link]("Files in Directory :"+[Link]());
[Link]("-----------------------------");
listOfFiles(file);
}
}
}
public static void main(String args[]) throws IOException {
File file = new File("C:/Labs");
listOfFiles(file);
}
}

OUTPUT :

You might also like