Oops Lab Record-4 - Merged
Oops Lab Record-4 - Merged
CS3381/
Object Oriented Programming Laboratory
NAME :________________________________________
REGISTER NO :________________________________________
YEAR : ________________________________________
SEMESTER :_________________________________________
JAYA SAKTHI ENGINEERING COLLEGE
(Approved By AICTE, New Delhi & Affiliated to Anna University,Chennai)
St.Mary’s Nagar, Thiruninravur (Near Avadi), Chennai – 602024
BONAFIDE CERTIFICATE
Name: ………………….……………………………………………………
Certified that this is the bonafide record of work done by the above student in the
CS3381/OBJECT ORIENTED PROGRAMMING LABORATORY during the
academic year 2023-2024.
_____________________________ _____________________
Signature of Head of the Department Signature of Lab In charge
Signature of Examiners:
Solve problems by using sequential search, binary search, and quadratic sorting
1.
algorithms (selection, insertion)
2. Develop stack and queue data structures using classes and objects.
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,
3. Associate Professor and Professor from 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.
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 Rectangle,
4.
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.
EX NO:
DATE:
SEQUENTIAL SEARCH
AIM:
To write a java program to solve problems by using sequential search.
ALGORITHM:
PROGRAM:
public class SequentialSearchExample
{
public static int SequentialSearch(int[] arr, int key)
{
for(int i=0;i<arr.length;i++)
{
if(arr[i] == key)
{
return i;
}
}
return -1;
}
public static void main(String a[])
{
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+SequentialSearch(a1, key));
}
}
REG NO:112022104035
OUTPUT:
50 is found at index: 3
RESULT:
Thus the java program to solve problems by using sequential search has been successfully
executed.
REG NO:112022104035
EX NO:
DATE:
BINARY SEARCH
AIM:
ALGORITHM:
PROGRAM:
class BinarySearchExample
{
public static void binarySearch(int arr[], int first, int last, int key)
{
int mid = (first + last)/2;
while( first <= last )
{
if ( arr[mid] < key )
{
first = mid + 1;
}
else if ( arr[mid] == key )
{
System.out.println("Element is found at index: " + mid);
break;
}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}
REG NO:112022104035
OUTPUT:
RESULT:
Thus the java program to implement binary search has been successfully executed.
REG NO:112022104035
EX NO:
DATE:
SELECTION SORT
AIM:
ALGORITHM:
PROGRAM:
{
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1)
{
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);//sorting array using selection sort
System.out.println("After Selection Sort");
for(int i:arr1)
{
System.out.print(i+" ");
}
}
}
OUTPUT:
RESULT:
Thus the java program to implement the selection sort has been successfully executed.
REG NO:112022104035
EX NO:
DATE:
INSERTION SORT
AIM:
ALGORITHM:
PROGRAM:
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 a[]){
int[] arr1 = {9,14,3,2,43,11,58,22};
REG NO:112022104035
OUTPUT:
RESULT:
Thus the java program to implement the insertion sort has been successfully executed.
REG NO:112022104035
EX NO:
DATE:
DEVELOP STACK AND QUEUE DATA STRUCTURES USING CLASSES AND OBJECTS
STACK
AIM:
To create a java program to develop stack data structure.
ALGORITHM:
PROGRAM:
// Stack implementation in Java
class Stack
{
// store elements of stack
private int arr[];
// represent top of stack
private int top;
// total capacity of the stack
private int capacity;
// Creating a stack
Stack(int size)
{
// initialize the array
// initialize the stack variables
arr = new int[size];
capacity = size;
top = -1;
REG NO:112022104035
}
// push elements to the top of stack
public void push(int x)
{
if (isFull())
{
System.out.println("Stack OverFlow");
// terminates the program
System.exit(1);
}
// insert element on top of stack
System.out.println("Inserting " + x);
arr[++top] = x;
}
// pop elements from top of stack
public int pop()
{
// if stack is empty
// no element to pop
if (isEmpty())
{
System.out.println("STACK EMPTY");
// terminates the program
System.exit(1);
}
// pop element from top of stack
return arr[top--];
}
// return size of the stack
public int getSize()
{
return top + 1;
}
// check if the stack is empty
public Boolean isEmpty()
{
return top == -1;
}
// check if the stack is full
public Boolean isFull()
{
return top == capacity - 1;
}
// display elements of stack
public void printStack()
{
for (int i = 0; i <= top; i++)
REG NO:112022104035
{
System.out.print(arr[i] + ", ");
}
}
public static void main(String[] args)
{
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
// remove element from stack
stack.pop();
System.out.println("\nAfter popping out:");
stack.printStack();
}
}
OUTPUT:
Inserting 1
Inserting 2
Inserting 3
Stack: 1, 2, 3,
After popping out:1, 2,
RESULT:
Thus the java program to develop stack data structure has been successfully executed.
REG NO:112022104035
EX NO:
DATE:
QUEUE
AIM:
ALGORITHM:
PROGRAM:
}
else
{
if (front == -1)
{
// mark front denote first element of queue
front = 0;
}
rear++;
// insert element at the rear
items[rear] = element;
System.out.println("Insert " + element);
}
}
// delete element from the queue
int deQueue()
{
int element;
// if queue is empty
if (isEmpty())
{
System.out.println("Queue is empty");
return (-1);
}
else
{
// remove element from the front of queue
element = items[front];
// if the queue has only one element
if (front >= rear)
{
front = -1;
rear = -1;
}
else
{
// mark next element as the front
front++;
}
System.out.println( element + " Deleted");
return (element);
}
}
// display element of the queue
void display()
{
int i;
REG NO:112022104035
if (isEmpty())
{
System.out.println("Empty Queue");
}
else
{
// display the front of the queue
System.out.println("\nFront index-> " + front);
// display element of the queue
System.out.println("Items -> ");
for (i = front; i <= rear; i++)
System.out.print(items[i] + " ");
// display the rear of the queue
System.out.println("\nRear index-> " + rear);
}
}
public static void main(String[] args)
{
// create an object of Queue class
Queue q = new Queue();
// try to delete element from the queue
// currently queue is empty
// so deletion is not possible
q.deQueue();
// insert elements to the queue
for(int i = 1; i < 6; i ++)
{
q.enQueue(i);
}
// 6th element can't be added to queue because queue is full
q.enQueue(6);
q.display();
// deQueue removes element entered first i.e. 1
q.deQueue();
// Now we have just 4 elements
q.display();
}
}
REG NO:112022104035
OUTPUT:
Queue is empty
Insert 1
Insert 2
Insert 3
Insert 4
Insert 5
Queue is full
Front index-> 0
Items ->
12345
Rear index-> 4
1 Deleted
Front index-> 1
Items ->
2345
Rear index-> 4
RESULT:
Thus the java program to develop queue data structure has been successfully executed.
REG NO:112022104035
EX NO:
DATE:
AIM:
To write a java program to develop a java application with an Employee class with
Emp_name, Emp_id, Address, Mail_id, Mobile_no as members.
ALGORITHM:
PROGRAM:
import java.text.DecimalFormat;
class Employee {
protected String Emp_name;
protected int Emp_id;
protected String Address;
protected String Mail_id;
protected String Mobile_no;
public Employee(String emp_name, int emp_id, String address, String mail_id, String
mobile_no) {
Emp_name = emp_name;
Emp_id = emp_id;
Address = address;
Mail_id = mail_id;
Mobile_no = mobile_no;
}
}
REG NO:112022104035
OUTPUT:
D:\First>javac Main.java
D:\First>java Main
Pay Slip for Programmer
Employee Name: John Doe
Employee ID: 1001
Basic Pay: $5000
DA (97% of Basic Pay): $4850
HRA (10% of Basic Pay): $500
PF (12% of Basic Pay): $600
Staff Club Funds (0.1% of Basic Pay): $5
Gross Salary: $9745
Net Salary: $9745
RESULT:
Thus the java program to develop a java application with an Employee class with
Emp_name, Emp_id, Address, Mail_id, Mobile_no as members has been successfully
executed.
REG NO:112022104035
EX NO:
DATE:
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
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.
AIM:
To write a java program to find the area of different shapes by using abstract class.
ALGORITHM:
PROGRAM:
import java.util.*;
abstract class Shape {
public int x,y;
public abstract void printArea();
}
class Rectangle1 extends Shape {
public void printArea() {
float area;
area= x * y;
System.out.println("Area of Rectangle is " +area);
}
}
class Triangle extends Shape {
public void printArea() {
float area;
area= (x * y) / 2.0f;
System.out.println("Area of Triangle is " + area);
}
}
class Circle extends Shape {
public void printArea() {
float area;
area=(22 * x * x) / 7.0f;
System.out.println("Area of Circle is " + area);
}
}
public class AreaOfShapes {
public static void main(String[] args) {
int choice;
Scanner sc=new Scanner(System.in);
REG NO:112022104035
OUTPUT:
D:\First>javac AreaOfShapes.java
D:\First>java AreaOfShapes
Menu
1.Area of Rectangle
2.Area of Traingle
3.Area of Circle
Enter your choice : 1
Enter length and breadth for area of rectangle :
12
54
Area of Rectangle is 648.0
D:\First>java AreaOfShapes
Menu
1.Area of Rectangle
2.Area of Traingle
3.Area of Circle
Enter your choice : 2
Enter bredth and height for area of traingle :
32
34
Area of Triangle is 544.0
D:\First>java AreaOfShapes
Menu
1.Area of Rectangle
2.Area of Traingle
3.Area of Circle
Enter your choice : 3
Enter radius for area of circle :
32
Area of Circle is 3218.2856
RESULT:
Thus the java program to find the area of different shapes by using abstract class has
been successfully executed.
REG NO:112022104035
EX NO:
DATE:
AIM:
To create a java program to find the Area of different shapes using an interface.
ALGORITHM:
PROGRAM:
OUTPUT:
D:\First>javac Main.java
D:\First>java Main
Circle Area: 78.53981633974483
Rectangle Area: 24.0
Triangle Area: 12.0.
RESULT:
Thus the java program to find the Area of different shapes using an interface has been
successfully executed.
REG NO:112022104035
EX NO:
DATE:
AIM:
To create a java program to Implement exception handling and creation of user defined
exceptions.
ALGORITHM:
PROGRAM:
else {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
// printing the message from InvalidAgeException object
System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code...");
}
}
OUTPUT:
D:\First>javac TestCustomException1.java
D:\First>java TestCustomException1
Caught the exception
Exception occured: InvalidAgeException: age is not valid to vote
rest of the code…
RESULT:
Thus the java program to Implement exception handling and creation of user
defined exceptions has been successfully executed.
REG NO:112022104035
EX NO:
DATE:
Write a java program that implements a multi-threaded 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.
AIM:
ALGORITHM:
PROGRAM:
import java.util.Random;
class NumberGenerator implements Runnable {
private Random random = new Random();
private Thread evenThread;
private Thread oddThread;
private int count = 0; // Counter to track the number of generated numbers
public NumberGenerator(Thread evenThread, Thread oddThread) {
this.evenThread = evenThread;
this.oddThread = oddThread;
}
public int getRandomNumber() {
return random.nextInt(100);
}
@Override
public void run() {
while (count < 5) { // Break after generating 5 random numbers
int number = getRandomNumber(); // Generate a random integer between 0 and 99
System.out.println("Generated number: " + number);
if (number % 2 == 0) {
evenThread.interrupt(); // Notify the even thread
}
else {
oddThread.interrupt(); // Notify the odd thread
}
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
// After generating 5 random numbers, exit the program
System.exit(0);
}
}
// ... Rest of the code remains the same ...
class EvenThread implements Runnable {
private NumberGenerator numberGenerator;
public EvenThread(NumberGenerator numberGenerator) {
this.numberGenerator = numberGenerator;
}
@Override
public void run() {
REG NO:112022104035
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000); // Sleep for 1 second
numberGenerator.getRandomNumber(); // Generate a random number to trigger the
interruption
} catch (InterruptedException e) {
int number = numberGenerator.getRandomNumber();
System.out.println("Square of " + number + " is " + (number * number));
}
}
}
}
class OddThread implements Runnable {
private NumberGenerator numberGenerator;
public OddThread(NumberGenerator numberGenerator) {
this.numberGenerator = numberGenerator;
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000); // Sleep for 1 second
numberGenerator.getRandomNumber(); // Generate a random number to trigger the
interruption
} catch (InterruptedException e) {
int number = numberGenerator.getRandomNumber();
System.out.println("Cube of " + number + " is " + (number * number * number));
}
}
}
}
public class Main {
public static void main(String[] args) {
NumberGenerator numberGenerator = new NumberGenerator(null, null);
Thread evenThread = new Thread(new EvenThread(numberGenerator));
Thread oddThread = new Thread(new OddThread(numberGenerator));
numberGenerator = new NumberGenerator(evenThread, oddThread);
evenThread.start();
oddThread.start();
Thread generatorThread = new Thread(numberGenerator);
generatorThread.start();
}
}
REG NO:112022104035
OUTPUT:
D:\First>javac Main.java
D:\First>java Main
Generated number: 87
Cube of 48 is 110592
Generated number: 70
Square of 68 is 4624
Generated number: 30
Square of 20 is 400
Generated number: 20
Square of 94 is 8836
Generated number: 67
Cube of 99 is 970299
RESULT:
Thus the java program to implement a multi-threaded application has been successfully
executed.
REG NO:112022104035
EX NO:
DATE:
AIM:
ALGORITHM:
PROGRAM:
import java.io.*;
public class FileOperationsDemo {
public static void main(String[] args) {
String fileName = "example.txt";
// Create a new file
createFile(fileName);
// Write data to the file
writeToFile(fileName, "Hello, World!");
// Read and display data from the file
String fileContents = readFromFile(fileName);
System.out.println("File Contents: " + fileContents);
// Delete the file
deleteFile(fileName);
}
// Method to create a new file
private static void createFile(String fileName) {
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.err.println("An error occurred while creating the file: " + e.getMessage());
}
}
REG NO:112022104035
OUTPUT:
D:\First>javac FileOperationsDemo.java
D:\First>java FileOperationsDemo
File created: example.txt
Data written to the file.
File Contents: Hello, World!
File deleted: example.txt
RESULT:
Thus the java program to perform file operations has been successfully executed.
REG NO:112022104035
EX NO:
DATE:
AIM:
ALGORITHM:
PROGRAM:
class Main {
public static void main(String[] args) {
// initialize the class with Integer data
DemoClass demo = new DemoClass();
// generics method working with String
demo.<String>genericsMethod("Java Programming");
// generics method working with integer
demo.<Integer>genericsMethod(25);
}
}
class DemoClass {
// creae a generics method
public <T> void genericsMethod(T data) {
System.out.println("Generics Method:");
System.out.println("Data Passed: " + data);
}
}
REG NO:112022104035
OUTPUT:
D:\First>javac Main.java
D:\First>java Main
Generics Method:
Data Passed: Java Programming
Generics Method:
Data Passed: 25
RESULT:
Thus the java to Develop applications to demonstrate the features of generics classes has
been successfully executed.
REG NO:112022104035
EX NO:
DATE:
AIM:
To write a java program to Develop applications using JavaFX controls, layouts and
menus.
ALGORITHM:
PROGRAM:
// create a menu
Menu m = new Menu("Menu");
// create menuitems
MenuItem m1 = new MenuItem("menu item 1");
MenuItem m2 = new MenuItem("menu item 2");
MenuItem m3 = new MenuItem("menu item 3");
// create a menubar
MenuBar mb = new MenuBar();
// create a VBox
VBox vb = new VBox(mb);
// create a scene
Scene sc = new Scene(vb, 500, 300);
s.show();
}
OUTPUT:
RESULT:
Thus the java to Develop applications using JavaFX controls, layouts and menus
has been successfully executed.
REG NO:112022104035
EX NO:
DATE:
AIM:
To write a java program to develop a mini project for any application using java concepts.
ALGORITHM:
Step1: Create Tenant Class:
- Define a class `Tenant` with attributes:
- `name` (String) - To store the tenant's name.
- `rentAmount` (int) - To store the rent amount.
Step 2: Create House Class
- Define a class `House` with attributes:
- `tenants` (ArrayList of Tenant objects) - To maintain a list of tenants.
Step 3: Add Tenant to House
- Provide a method in the `House` class to add a new tenant:
- Accept tenant details (name and rent amount) and add a new `Tenant` object to the
`tenants` list.
Step 4: Display Tenants
- Implement a method in the `House` class to display all the tenants and their rent amounts.
Step 5:Calculate Total Rent
- Implement a method in the `House` class to calculate the total rent by summing up the rent
amounts of all tenants.
Step 6: Main Program Execution
- In the `main` method:
- Create a `Scanner` object to read user input.
- Create a `House` object.
- Add some initial tenants to the house.
Step 7: Menu-driven Interface
- Use a loop to display a menu and prompt the user for choices.
- Choices include:
- Display Tenants: Show tenant information (name and rent amount).
- Calculate Total Rent: Sum up all rent amounts for tenants in the house.
- Exit: Terminate the program.
Step 8: Handle User Input
- Based on the user's choice, perform the corresponding action:
- Display tenants' information if the user selects the display option.
- Calculate and display the total rent amount if the user selects the rent calculation option.
- Exit the loop and terminate the program if the user chooses the exit option.
Step 9: Cleanup
- Close the `Scanner` object at the end of program execution.
REG NO:112022104035
PROGRAM:
import java.util.ArrayList;
import java.util.Scanner;
class Tenant {
private String name;
private int rentAmount;
public Tenant(String name, int rentAmount) {
this.name = name;
this.rentAmount = rentAmount;
}
public String getName() {
return name;
}
public int getRentAmount() {
return rentAmount;
}
}
class House {
private ArrayList<Tenant> tenants;
public House() {
tenants = new ArrayList<>();
}
public void addTenant(Tenant tenant)
{
tenants.add(tenant);
}
public void displayTenants() {
REG NO:112022104035
System.out.println("Tenants:");
for (Tenant tenant : tenants) {
System.out.println("Name: " + tenant.getName() + ", Rent Amount: $" +
tenant.getRentAmount());
}
}
public int calculateTotalRent() {
int totalRent = 0;
for (Tenant tenant : tenants) {
totalRent += tenant.getRentAmount();
}
return totalRent;
}
}
public class HouseRentManagement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
House house = new House
// Adding tenants and their rent
house.addTenant(new Tenant("John", 800));
house.addTenant(new Tenant("Alice", 750));
house.addTenant(new Tenant("Bob", 900));
int choice;
do {
System.out.println("\nHouse Rent Management System");
System.out.println("1. Display Tenants");
System.out.println("2. Calculate Total Rent");
System.out.println("3. Exit");
REG NO:112022104035
OUTPUT:
House Rent Management System
1. Display Tenants
2. Calculate Total Rent
3. Exit
Enter your choice: 1
REG NO:112022104035
Tenants:
Name: John, Rent Amount: 800
Name: Alice, Rent Amount: 750
Name: Bob, Rent Amount: 900
RESULT:
Thus the java to develop a mini project for house rent management system has been
successfully executed.