CS3381 - Object Oriented Programming Laboratory
CS3381 - Object Oriented Programming Laboratory
NAME :
REGISTER NO. :
BRANCH :
ANNA UNIVERSITY
1
UNIVERSITY COLLEGE OF ENGINEERING – DINDIGUL
DINDIGUL – 62422
BONAFIDE CERTIFICATE
This is to certify that is a bonafide record of work done by
Mr./Ms.________________________________________
in _____________________________________________
laboratory during the academic year 2022-2023
University Registration no.:
INDEX
EXPT NAME OF THE EXPERIMENT PAGE DATE OF SIGNATURE
2
NO. NO. COMPLETIO
N
1 Solve problems by using sequential search, binary search, 4
and quadratic sorting algorithms (selection, insertion)
2 Develop stack and queue data structures using classes 12
and objects
3 Develop a java application with an Employee class with
Emp_name, Emp_id, Address, Mail_id, Mobile_no as
members. Inherit the classes, Programmer, Assistant
Professor, Associate Professor and Professor from 19
employee class. Add Basic Pay (BP) as the member of all
the inherited classes with 97% of BP as DA, 10 % of BP as
HRA, 12% of BP as PF, 0.1% of BP for staff club funds.
Generate pay slips for the employees with their gross and
net salary.
4 Write a Java Program to create an abstract class named
Shape that contains two integers and an empty method
named printArea(). Provide three classes named 25
Rectangle, Triangle and Circle such that each one of the
classes extends the class Shape. Each one of the classes
contains only the method printArea( ) that prints the area
of the given shape.
5 Solve the above problem using an interface 27
3
AIM:
To write a java program to solve problem for sequential search method.
ALGORITHM:
SOURCE CODE:
4
RESULT:
Thus the program to solve the problem for “sequential search” was
executed successfully and the output was verified.
EXPT NO.: 01(b)
BINARY SEARCH
DATE :
5
AIM:
To write a java program to solve the problem for binary search method.
ALGORITHM:
1. Start the program.
2. Compare x with the middle element.
3. If x matches with middle element, we return the mid index.
4. Else If x is greater than the mid element, then x can only lie in the right
half subarray after the mid element. So we recur for right half.
5. Else (x is smaller) recur for the left half.
6. Stop the program.
SOURCE CODE:
class BinarySearch
{
int binarySearch(int arr[], int l, int r, int x)
{
if (r>=l)
{
int mid = l + (r-l)/2;
if (arr[mid]==x)
return mid;
if (arr[mid]>x)
return binarySearch(arr, l,mid - 1, x);
return binarySearch(arr, mid + 1,r, x);
}
return -1;
}
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, 0, n - 1, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index "+ result);
}
6
}
RESULT:
Thus the program to solve the problem for “sequential search” was
executed successfully and the output was verified.
7
EXPT NO.: 01(c)
INSERTION SORT
DATE :
AIM:
To write a java program to solve the problem for insertion sort method.
ALGORITHM:
1. Start the program.
2. Iterate from arr[1] to arr[N] over the array.
3. Compare the current element (key) to its predecessor.
4. If the key element is smaller than its predecessor, compare it to the
elements before. Move the greater elements one position up to make
space for the swapped element.
5. Stop.
SOURCE CODE:
public class InsertionSortExample
{
public static void insertionSort(int array[])
{
int n = array.length;
for (int j = 1; j < n; j++)
{
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) )
{
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}
public static void main(String args[])
{
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Insertion Sort");
for(int i:arr1)
{
8
System.out.print(i+" ");
}
System.out.println();
insertionSort(arr1);
System.out.println("After Insertion Sort");
for(int i:arr1)
{
System.out.print(i+" ");
}
}
RESULT:
Thus the program to solve the problem for “insertion sort” was executed
successfully and the output was verified.
9
EXPT NO.: 01(d)
SELECTION SORT
DATE :
AIM:
To write a java program to solve the problem for selection sort method.
ALGORITHM:
1. Start the program.
2. Initialize minimum value(min_idx) to location 0.
3. Traverse the array to find the minimum element in the array.
4. While traversing if any element smaller than min_idx is found then
swap both the values.
5. Then, increment min_idx to point to the next element.
6. Repeat until the array is sorted.
7. Stop.
SOURCE CODE:
public class Selection
{
public static void selectionSort(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[index])
{
index = j;
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];arr[i] = smallerNumber;
}
}
public static void main(String args[])
{
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
10
for(int i:arr1)
{
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);
System.out.println("After Selection Sort");
for(int i:arr1)
{
System.out.print(i+" ");
}
}
}
RESULT:
Thus the program to solve the problem for “insertion sort” was executed
successfully and the output was verified.
11
EXPT NO.: 02(a)
STACK IN JAVA
DATE :
AIM:
To write a java program for solving the stack and the stack operation
involved in it.
ALGORITHM:
1. Creating a stack :
Step 1 - Include all the header files which are used in the program and define
a constant 'SIZE' with specific value.
Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
Step 5 - In main method, display menu with list of operations and make
suitable function calls to perform operation selected by the user on the stack.
Step 3 - If it is NOT FULL, then increment top value by one (top++) and set
stack[top] to value (stack[top] = value).
Step 3 - If it is NOT EMPTY, then delete stack[top] and decrement top value
by one (top--).
12
4. Displaying values of the stack:
Step 3 - If it is NOT EMPTY, then define a variable 'i' and initialize with top.
Display stack[i] value and decrement i value by one (i--).
SOURCE CODE:
import java.util.*;
public class StackPushPopExample
{
public static void main(String args[])
{
Stack <Integer> stk = new Stack<>();
System.out.println("stack: " + stk);
pushelmnt(stk, 20);
pushelmnt(stk, 13);
pushelmnt(stk, 89);
pushelmnt(stk, 90);
pushelmnt(stk, 11);
pushelmnt(stk, 45);
pushelmnt(stk, 18);
popelmnt(stk);
popelmnt(stk);
try
{
popelmnt(stk);
}
catch (EmptyStackException e)
{
System.out.println("empty stack");
}
}
static void pushelmnt(Stack stk, int x)
{
stk.push(new Integer(x));
System.out.println("push -> " + x);
System.out.println("stack: " + stk);
13
}
static void popelmnt(Stack stk)
{
System.out.print("pop -> ");
Integer x = (Integer) stk.pop();
System.out.println(x);
System.out.println("stack: " + stk);
}
}
RESULT:
Thus the program for “stack and its operation” was executed successfully
and the output was verified.
14
EXPT NO.: 02(b)
QUEUE IN JAVA
DATE :
AIM:
To write a java program for Queue and its queue operation involved in it.
ALGORITHM:
Step 1 - Include all the header files which are used in the program and define
a constant 'SIZE' with specific value.
Step 2 - Declare all the user defined functions which are used in queue
implementation.
Step 3 - Create a one dimensional array with above defined SIZE (int
queue[SIZE])
Step 4 - Define two integer variables 'front' and 'rear' and initialize both
with '-1'. (int front = -1, rear = -1)
Step 3 - If it is NOT FULL, then increment rear value by one (rear++) and
set queue[rear] = value.
15
Step 3 - If it is NOT EMPTY, then increment the front value by one (front ++).
Then display queue[front] as deleted element. Then check whether
both front and rear are equal (front == rear), if it TRUE, then set
both front and rear to '-1' (front = rear = -1).
Step 3 - If it is NOT EMPTY, then define an integer variable 'i' and set
'i = front+1'.
Step 4 - Display 'queue[i]' value and increment 'i' value by one (i++). Repeat the
same until 'i' value reaches to rear (i <= rear)
SOURCE CODE:
public class Queue
{
private static int front, rear, capacity;
private static int queue[];
Queue(int size)
{
front = rear = 0;
capacity = size;
queue = new int[capacity];
}
else
{
queue[rear] = item;
rear++;
}
return;
16
}
static void queueDequeue()
{
if (front == rear)
{
System.out.printf("\nQueue is empty\n");
return;
}
else
{
for (int i = 0; i < rear - 1; i++)
{
queue[i] = queue[i + 1];
}
if (rear < capacity)
queue[rear] = 0;
rear--;
}
return;
}
static void queueDisplay()
{
int i;
if (front == rear)
{
System.out.printf("Queue is Empty\n");
return;
}
for (i = front; i < rear; i++)
{
System.out.printf(" %d , ", queue[i]);
}
return;
}
static void queueFront()
{
if (front == rear)
{
System.out.printf("Queue is Empty\n");
return;
}
System.out.printf("\nFront Element of the queue: %d",
queue[front]);
return;
17
}
}
RESULT:
Thus the java program for “working in queue and its operation” was
executed successfully and the output was verified.
EXPT NO.: 03
GENERATING EMPLOYEE PAYROLL
18
DATE :
DETAILS.
AIM:
To develop a java application for generating pay slips of employees with
their gross and net salary.
ALGORITHM:
1. The package keyword is used to create a package in java.
2. Create a class Employee inside a package name employee.
3. Class Employee contains Emp_name, Emp_id, Address, Mail_id, Mobile_no as
members.
4. By using Constructor initialize the instance variable of Employee class and display
method is used to print employee details.
5. Create classes Programmer, AssistantProfessor, AssociateProfessor and Professor
that extends Employee class and define necessary constructor for sub classes.
6. Each sub classes has its own instance variable like bPay and des.
7. Override the paySlip method in each sub classes to calculate the gross and net
salary
8. By using super () method subclasses initialize the super class constructor.
9. Import employee package and create the object for Empolyee class.
10. Create different Employee object to add ArrayList<> classes.
11.DisplayEmployee method is used to display all employee playSlip details
SOURCE CODE:
package employee;
public class Employee
{
private String name;
private String id;
private String address;
private String mailId;
19
private String mobileNo;
public Employee(String name, String id, String address, String mailId, String
mobileNo)
{
this.name= name;
this.id= id;
this.address= address;
this.mailId= mailId;
this.mobileNo= mobileNo;
}
public void display()
{
System.out.println("Emp_Name : "+ name + "\t" + "Emp_id : "+ id);
System.out.println("Address : " + address);
System.out.println("Mail_id : "+ mailId + "\t" + "Mobile_no : " + mobileNo);
}
public void paySlip()
{
}
}
package employee;
public class Programmer extends Employee
{
private float bPay;
private String des;
public Programmer(String name, String id, String address, String mailId, String
mobileNo,
float bPay, String des)
{
super(name, id, address, mailId, mobileNo);
this.bPay= bPay;
this.des= des;
}
public void paySlip()
{
float da=bPay*97/100;
float hra=bPay*10/100;
double grossSalary=bPay + da + hra;
float pf=bPay*12/100;
double scf=bPay*0.1/100;
double netSalary=grossSalary - pf - scf;
System.out.println("------------ Employees Pay Slips ------------");
super.display();
System.out.println("Designation: "+des);
20
System.out.println("Basic_Pay: "+bPay);
System.out.println("Gross Salary : "+ grossSalary + "\t" + "Net Salary : " + netSalary);
System.out.println("------------ End of the Statements -----------");
}
}
package employee;
public class AssistantProfessor extends Employee
{
private float bPay;
private String des;
public AssistantProfessor(String name, String id, String address, String mailId, String
mobileNo, float bPay, String des)
{
super(name, id, address, mailId, mobileNo);
this.bPay= bPay;
this.des= des;
}
public void paySlip()
{
float da=bPay*97/100;
float hra=bPay*10/100;
double grossSalary=bPay + da + hra;
float pf=bPay*12/100;
double scf=bPay*0.1/100;
double netSalary=grossSalary - pf - scf;
System.out.println("------------ Employees Pay Slips ------------");
super.display();
System.out.println("Designation: "+des);
System.out.println("Basic_Pay: "+bPay);
System.out.println("Gross Salary : "+ grossSalary + "\t" + "Net Salary : " + netSalary);
System.out.println("------------ End of the Statements -----------");
}
}
package employee;
public class AssociateProfessor extends Employee
{
private float bPay;
private String des;
public AssociateProfessor(String name, String id, String address, String mailId, String
mobileNo, float bPay, String des)
{
21
super(name, id, address, mailId, mobileNo);
this.bPay= bPay;
this.des= des;
}
public void paySlip()
{
float da=bPay*97/100;
float hra=bPay*10/100;
double grossSalary=bPay + da + hra;
float pf=bPay*12/100;
double scf=bPay*0.1/100;
double netSalary=grossSalary - pf - scf;
System.out.println("------------ Employees Pay Slips ------------");
super.display();
System.out.println("Designation: "+des);
System.out.println("Basic_Pay: "+bPay);
System.out.println("Gross Salary : "+ grossSalary + "\t" + "Net Salary : " + netSalary);
System.out.println("------------ End of the Statements -----------");
}
}
package employee;
public class Professor extends Employee
{
private float bPay;
private String des;
public Professor(String name, String id, String address, String mailId, String mobileNo,
float
bPay, String des)
{
super(name, id, address, mailId, mobileNo);
this.bPay= bPay;
this.des= des;
}
public void paySlip()
{
float da=bPay*97/100;
float hra=bPay*10/100;
double grossSalary=bPay + da + hra;
float pf=bPay*12/100;
double scf=bPay*0.1/100;
double netSalary=grossSalary - pf - scf;
System.out.println("------------ Employees Pay Slips ------------");
22
super.display();
System.out.println("Designation: "+des);
System.out.println("Basic_Pay: "+bPay);
System.out.println("Gross Salary : "+ grossSalary + "\t" + "Net Salary : " + netSalary);
System.out.println("------------ End of the Statements -----------");
}
}
import employee.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Emp
{
Employee e;
ArrayList<Employee> obj= new ArrayList<>();
Scanner get= new Scanner(System.in);
public void addEmployee()
{
System.out.println("Enter the Emp_Name:");
String name = get.next();
System.out.println("Enter the Emp_id:");
String id = get.next();
System.out.println("Enter the Address:");
String address = get.next();
System.out.println("Enter the Mail_id:");
String mailId = get.next();
System.out.println("Enter the Mobile_no:");
String mobileNo = get.next();
System.out.println("Enter the Designation:");
String des = get.next();
System.out.println("Enter the Basic_Pay:");
float bPay = get.nextFloat();
if(des.equalsIgnoreCase("Programmer"))
{
e= new Programmer(name, id, address, mailId, mobileNo, bPay, des);
obj.add(e);
}
else if(des.equalsIgnoreCase("AssistantProfessor"))
{
e= new AssistantProfessor(name, id, address, mailId, mobileNo, bPay, des);
obj.add(e);
}
23
else if(des.equalsIgnoreCase("AssociateProfessor"))
{
e= new AssociateProfessor(name, id, address, mailId, mobileNo, bPay, des);
obj.add(e);
}
else if(des.equalsIgnoreCase("Professor"))
{
e= new Professor(name, id, address, mailId, mobileNo, bPay, des);
obj.add(e);
}
}
public void displayEmployee()
{
for(Employee e:obj)
{
e.paySlip();
}
}
public static void main(String args[]) throws IOException
{
Emp x= new Emp();
String check;
do
{
x.addEmployee();
System.out.println("Do you wnat continue press 'y'");
check=x.get.next();
}
while(check.equalsIgnoreCase("y"));
x.displayEmployee();
}
}
RESULT:
Thus the program for “generating employee payroll details” was executed
successfully and the output was verified.
24
AIM:
To write a java program for printing the area of the given three shapes
using abstract class involved in it.
ALGORITHM:
1. Start the program.
2. Create an abstract class named shape that contains two integers and
an empty method named printarea().
3. Provide three classes named rectangle, triangle and circle such that each
one of the classes extends the class Shape.
4. Each of the inherited class from shape class should provide the
implementation for the method printarea().
5. Get the input and calculate the area of rectangle,circle and triangle .
6. In the shapeclass , create the objects for the three inherited classes and
invoke the methods and display the area values of the different shapes.
7. Stop.
SOURCE CODE:
import java.util.*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
25
class Triangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstractDDemo
{
RESULT:
Thus the program for “printing the area of the given three shapes using
abstract class” was executed successfully and the output was verified
EXPT NO.: 05
INTERFACE.
DATE :
26
AIM:
To solve the above problem using an interface.
ALGORITHM:
1. Start the program.
2. Interface are used to implement abstraction.
3. It is used to achieve total abstraction.
4. Interface are declared by specifying a keyword “interface”.
5. Stop the program.
SOURCE CODE:
import java.util.Scanner.*;
interface Shape
{
void input();
void area();
}
27
int p, b;
double ar;
public void input()
{
super.input();
p=6;
b=4;
}
public void area()
{
super.area();
ar = p*b;
System.out.println("Area of rectangle:"+ar);
}
}
RESULT:
Thus the above problem using an interface done successfully and the
output was verified.
28
EXPT NO.: 06
EXCEPTION HANDLING
DATE :
AIM:
To write a Java program to implement user defined exception handling.
ALGORITHM:
1. Start the program.
2. Create a class NegativeAmtException which extends Exception class.
3. Create a constructor which receives the string as argument.
4. Get the Amount as input from the user.
5. If the amount is negative, the exception will be generated.
6. Using the exception handling mechanism , the thrown exception is handled by the
catch construct.
7. After the exception is handled , the string “invalid amount “ will be displayed.
8. If the amount is greater than 0, the message “Amount Deposited “will be displayed
9. Stop.
PROGRAM:
public class JavaExceptionExample
{
public static void main(String args[])
{
try
{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
29
System.out.println("rest of the code...");
}
}
RESULT:
Thus the Implement exception handling and creation of user defined
exceptions was executed successfully.
30
EXPT NO.: 07
MULTI-THREADED
DATE :
AIM:
To Write a java program that implements a multi-thread application that has three
threads.
ALGORITHM:
1. Start the program
2. Design the first thread that generates a random integer for every 1 second .
3. If the first thread value is even, design the second thread as the square of the number and then
print it.
4. If the first thread value is odd, then third thread will print the value of cube of the number.
SOURCE CODE:
import java.util.*;
class Square extends Thread
{
int num;
Square(int n)
{
num=n;
}
public void run()
{
System.out.println("Square of the number is "+num*num);
}
}
31
num=n;
}
public void run()
{
System.out.println("Cube of the number is "+num*num*num);
}
}
class RandomDemo extends Thread
{
public void run()
{
Random ra=new Random();
for(int i=0;i<10;i++)
{
int num=ra.nextInt(1000);
System.out.println("\nGenerated Random number is "+num);
if(num%2==0)
{
System.out.println("\nInvoking the Square Thread...");
Square s=new Square(num);
s.start();
}
else
{
System.out.println("\nInvoking the Cube Thread...");
Cube c=new Cube(num);
c.start();
}
try
{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
}
}
}
public static void main(String []ar)
{
RandomDemo rd=new RandomDemo();
rd.start();
}
}
32
RESULT:
Thus the java program that implements a multi-thread application that
has three threads was successfully and the output was verified.
33
EXPT NO.: 08
READ AND WRITE OPERATIONS
DATE :
AIM:
To write a program to perform file operation.
ALGORITHM:
1. Start the program.
2. To write data into the file.
3. To read the data from the file.
4. To write a character into the file.
5. Open new file or existing file
6. Stop the program.
SOURCE CODE:
import java.io.*;
import java.util.*;
class filedem
{
public static void main(String[] args)
{
String filename;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the file name ");
filename = sc.nextLine();
File f1=new File(filename);
System.out.println("*****************");
System.out.println("FILE INFORMATION");
System.out.println("*****************");
System.out.println("NAME OF THE FILE "+f1.getName());
System.out.println("PATH OF THE FILE "+f1.getPath());
System.out.println("PARENT"+f1.getParent());
if(f1.exists())
System.out.println("THE FILE EXISTS ");
34
else
System.out.println("THE FILE DOES NOT ExISTS ");
if(f1.canRead())
System.out.println("THE FILE CAN BE READ ");
else
System.out.println("THE FILE CANNOT BE READ ");
if(f1.canWrite())
System.out.println("WRITE OPERATION IS PERMITTED");
else
System.out.println("WRITE OPERATION IS NOT PERMITTED");
if(f1.isDirectory())
System.out.println("IT IS A DIRECTORY ");
else
System.out.println("NOT A DIRECTORY");
if(f1.isFile())
System.out.println("IT IS A FILE ");
else
System.out.println("NOT A FILE");
System.out.println("File last modified "+ f1.lastModified());
System.out.println("LENGTH OF THE FILE "+f1.length());
System.out.println("FILE DELETED "+f1.delete());
}
}
RESULT:
Thus the program to perform file operation was executed successfully and the
output was verified.
35
EXPT NO.: 09
GENERICS CLASSES.
DATE :
AIM:
To Develop applications to demonstrate the features of generics classes.
ALGORITHM:
SOURCE CODE:
36
RESULT:
Thus the develop applications to demonstrate the features of generics
classes was executed successfully and the output was verified.
37
EXPT NO.: 10
JAVAFX.
DATE :
AIM:
To develop applications using JavaFX controls, layouts and menus.
ALGORITHM:
1. Start the program.
2. To write the program.
3. Using the java FX controls.
4. To run the program.
5. Stop the program.
SOURCE CODE:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MenuExample extends Application
{
public void start(Stage stage)
{
//Creating a menu
Menu fileMenu = new Menu("File");
//Creating menu Items
MenuItem item1 = new MenuItem("Add Files");
MenuItem item2 = new MenuItem("Start Converting");
MenuItem item3 = new MenuItem("Stop Converting");
MenuItem item4 = new MenuItem("Remove File");
MenuItem item5 = new MenuItem("Exit");
//Adding all the menu items to the menu
38
fileMenu.getItems().addAll(item1, item2, item3, item4, item5);
//Creating a menu bar and adding menu to it.
MenuBar menuBar = new MenuBar(fileMenu);
menuBar.setTranslateX(200);
menuBar.setTranslateY(20);
//Setting the stage
Group root = new Group(menuBar);
Scene scene = new Scene(root, 595, 200, Color.BEIGE);
stage.setTitle("Menu Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[])
{
launch(args);
}
}
RESULT:
Thus the Develop applications using JavaFX controls, layouts and menus
was executed successfully and the output was verified.
39