0% found this document useful (0 votes)
19 views48 pages

Oops Lab Record-4 - Merged

oopps

Uploaded by

rajesh kumar
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)
19 views48 pages

Oops Lab Record-4 - Merged

oopps

Uploaded by

rajesh kumar
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
You are on page 1/ 48

JAYA SAKTHI ENGINEERING COLLEGE

(Approved By AICTE, New Delhi & Affiliated to Anna University,Chennai)


St.Mary’s Nagar, Thiruninravur (Near Avadi), Chennai – 602024

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

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: ………………….……………………………………………………

Year: II / Semester: III Branch: COMPUTER SCIENCE AND ENGINEERING

University Register No:

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

Submitted for the University Practical Examination held on ………………..

Signature of Examiners:

Internal :…………………… External:……………… ……


INDEX
S. PAGE
DATE LIST OF EXPERIMENTS SIGNATURE
NO NO.

Solve problems by using sequential search, binary search, and quadratic sorting
1.
algorithms (selection, insertion)

a. Solve problems by using Sequential Search

b. Solve problems by using Binary Search

Solve problems by using Quadratic Search


c.
(Selection Sort)

Solve problems by using Quadratic Search


d.
(Insertion Sort)

2. Develop stack and queue data structures using classes and objects.

Develop stack data structures using


a.
classes and objects

Develop queue data structures using


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

5. Solve the above problem using an interface.

Implement exception handling and creation of user


6.
defined exceptions
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
7.
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.
8. Write a program to perform file operations.

Develop applications to demonstrate the features


9.
of generics classes.
. Develop applications using JavaFX controls,
10.
layouts and menus
Develop a mini project for any application using
11.
Java concepts.
REG NO:112022104035

EX NO:
DATE:

SOLVE PROBLEMS BY USING SEQUENTIAL SEARCH, BINARY SEARCH AND


QUADRATIC SORTING ALGORITHMS (SELECTION, INSERTION)

SEQUENTIAL SEARCH

AIM:
To write a java program to solve problems by using sequential search.

ALGORITHM:

Step 1: Import the java packages.


Step 2: Create a class named as SequentialSearchExample
Step 3: Start iterating through the array.
Step 4: Compare the current element with the search key
Step 5: If the key is found, return the index (position)
Step 6: If the key is not found in the entire array, return -1
Step 7: Create an array to search
Step 8: Define the key to search
Step 9: Call the SequentialSearch method to find the key in the array
Step 10: Print the result
Step 11: Save the file as “SequentialSearchExample.java”.

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:

To write a java program to implement binary search.

ALGORITHM:

Step 1: Import the java packages.


Step 2: create the class Binary Search Example
Step 3: Initialize the left pointer to the start of the array
Step 4: Initialize the right pointer to the end of the array
Step 5: Calculate the middle index
Step 6: Check if the middle element is equal to the target then Return the index of the
target element
- If the target is smaller, search the left half
- If the target is larger, search the right half
- Return -1 to indicate that the target element was not found in the array
Step 7: print the result
Step 8: Save the file as “ BinarySearchExample.java”.

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

if ( first > last )


{
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}

OUTPUT:

Element is found at index: 2

RESULT:
Thus the java program to implement binary search has been successfully executed.
REG NO:112022104035

EX NO:
DATE:

SELECTION SORT

AIM:

To create a java program to implement the selection sort.

ALGORITHM:

Step 1: Import the java packages


Step 2: Create the class SelectionSortExample
Step 3: Get the length of the array
Step 4: Iterate through the array elements
Step 5: Assume the current index holds the minimum value
Step 6: Find the index of the minimum element in the unsorted portion of the array
Step 7: Update the index of the minimum element
Step 8: Swap the current element with the minimum element found
(This process continues until the entire array is sorted)
Step 9: Print the array after sorting
Step 10 : Save the file as “SelectionSortExample.java”

PROGRAM:

public class SelectionSortExample


{
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;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[])
REG NO:112022104035

{
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:

Before Selection Sort


9 14 3 2 43 11 58 22
After Selection Sort
2 3 9 11 14 22 43 58

RESULT:

Thus the java program to implement the selection sort has been successfully executed.
REG NO:112022104035

EX NO:
DATE:

INSERTION SORT

AIM:

To create a java program to implement the insertion sort.

ALGORITHM:

Step 1: Import the java packages.


Step 2: Create the class Insertion Sort
Step 3: Get the length of the array
Step 4: Iterate through the array from the second element to the last
Step 5:Store the current element to be inserted
Step 6:Start with the index of the element before the current one
Step 7:Compare the current element with elements in the sorted subarray and shift if
necessary
Step 8: Shift the greater element to the right
Step 9: Move to the previous index
Step 10: Place the key in its correct sorted position
(This process continues for each element in the unsorted portion of the array until the
entire array is sorted)
Step 11: Print the array after sorting
Step 12: save the file as “InsertionSortExample.java”.

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

System.out.println("Before Insertion Sort");


for(int i:arr1)
{
System.out.print(i+" ");
}
System.out.println();
insertionSort(arr1);//sorting array using insertion sort
System.out.println("After Insertion Sort");
for(int i:arr1)
{
System.out.print(i+" ");
}
}
}

OUTPUT:

Before Insertion Sort


9 14 3 2 43 11 58 22
After Insertion Sort
2 3 9 11 14 22 43 58

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:

Step 1: Import the java packages.


Step 2: Define a class named "Stack" to implement a stack.
Step 3: Declare private member variables for the stack.
Step 4: Create a constructor to initialize the stack.
Step 5: Implement the push operation to add elements to the top of the stack.
Step 6: Implement the pop operation to remove elements from the top of the stack.
Step 7: Implement a method to return the size of the stack.
Step 8: Implement a method to check if the stack is empty.
Step 9: Implement a method to check if the stack is full.
Step 10: Implement a method to display the elements of the stack.
Step 11: Define the main method to test the stack operations.
Step 12: Create an instance of the Stack class with a capacity of 5.
Step 13: Push elements onto the stack
Step 14: Print the stack.
Step 15: Pop an element from the stack.
Step 16: Print the stack again.
Step 17: Save the file as “Stack.java”.

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:

To create a java program to develop queue data structure.

ALGORITHM:

Step 1: Import the java packages.


Step 2: Create a class named "Queue"
Step 3: Define class variables:
- SIZE: An integer to represent the maximum size of the queue.
- items: An integer array of size SIZE to store the queue elements.
- front: An integer variable to represent the front pointer of the queue.
- rear: An integer variable to represent the rear pointer of the queue.
Step 4: Create a constructor for the Queue class to initialize the queue:
- Set front and rear to -1 (indicating an empty queue).
Step 5: Define a method "isFull()" to check if the queue is full:
- If front is 0 and rear is SIZE - 1, return true (queue is full).
- Otherwise, return false (queue is not full).
Step 6: Define a method "isEmpty()" to check if the queue is empty:
- If front is -1, return true (queue is empty).
- Otherwise, return false (queue is not empty).
Step 7: Define a method "enQueue(int element)" to insert elements into the queue:
- Check if the queue is full using the "isFull()" method.
- If the queue is full, print a message ("Queue is full").
- If the queue is not full:
- If front is -1, set front to 0 (marking the first element).
- Increment rear.
- Insert the element at the rear of the queue.
- Print a message indicating the element is inserted.
Step 8: Define a method "deQueue()" to delete an element from the queue:
- Check if the queue is empty using the "isEmpty()" method.
- If the queue is empty, print a message ("Queue is empty") and return -1.
- If the queue is not empty:
- Remove the element from the front of the queue.
- If front is greater than or equal to rear, the queue becomes empty, so reset front
and rear to -1.
- Otherwise, increment front.
- Return the deleted element.
Step 9: Define a method "display()" to display the elements of the queue:
- Check if the queue is empty using the "isEmpty()" method.
- If the queue is empty, print a message ("Empty Queue").
- If the queue is not empty:
REG NO:112022104035

- Display the front index of the queue.


- Display the elements of the queue from front to rear.
- Display the rear index of the queue.
Step 10: Create a "main" method to test the Queue class:
- Create an object of the Queue class.
- Perform various enQueue and deQueue operations to demonstrate the queue's
functionality.
- Display the queue's contents at different points to verify the operations.
Step 11: Save the file as “Queue.java”.

PROGRAM:

public class Queue


{
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;
Queue()
{
front = -1;
rear = -1;
}
// check if the queue is full
boolean isFull()
{
if (front == 0 && rear == SIZE - 1)
11
{
return true;
}
return false;
}
// check if the queue is empty
boolean isEmpty()
{
if (front == -1)
return true;
else
return false;
}
// insert elements to the queue
void enQueue(int element)
{
// if queue is full
if (isFull())
{
System.out.println("Queue is full");
REG NO:112022104035

}
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:

DEVELOP A JAVA APPLICATION WITH AN EMPLOYEE CLASS WITH EMP_NAME,


EMP_ID AND ADDRESS

Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant Professor,


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.

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:

Step 1: Import the java packages


Step 2: Create the Employee class with instance variables and a constructor.
Step 3: Create the Programmer class with inheritance, additional variables, and
methods.
Step 4: In the generatePaySlip method, calculate and display the pay slip details.
Step 5: Create the Main class, instantiate a Programmer object, and call
generatePaySlip.
Step 6: Save the file as “Main.java”..
Step 7: Compile and run the program.

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

class Programmer extends Employee {


private double BasicPay;
public Programmer(String emp_name, int emp_id, String address, String mail_id, String
mobile_no, double basicPay) {
super(emp_name, emp_id, address, mail_id, mobile_no);
BasicPay = basicPay;
}
public double calculateGrossSalary() {
double DA = 0.97 * BasicPay;
double HRA = 0.10 * BasicPay;
double PF = 0.12 * BasicPay;
double staffClubFunds = 0.001 * BasicPay;
return BasicPay + DA + HRA - PF - staffClubFunds;
}
public double calculateNetSalary() {
double DA = 0.97 * BasicPay;
double HRA = 0.10 * BasicPay;
double PF = 0.12 * BasicPay;
double staffClubFunds = 0.001 * BasicPay;
return BasicPay + DA + HRA - PF - staffClubFunds;
}
public void generatePaySlip() {
DecimalFormat df = new DecimalFormat("#.##");
double grossSalary = calculateGrossSalary();
double netSalary = calculateNetSalary();
System.out.println("Pay Slip for Programmer");
System.out.println("Employee Name: " + Emp_name);
System.out.println("Employee ID: " + Emp_id);
System.out.println("Basic Pay: $" + df.format(BasicPay));
System.out.println("DA (97% of Basic Pay): $" + df.format(0.97 * BasicPay));
System.out.println("HRA (10% of Basic Pay): $" + df.format(0.10 * BasicPay));
System.out.println("PF (12% of Basic Pay): $" + df.format(0.12 * BasicPay));
System.out.println("Staff Club Funds (0.1% of Basic Pay): $" + df.format(0.001 *
BasicPay));
System.out.println("Gross Salary: $" + df.format(grossSalary));
System.out.println("Net Salary: $" + df.format(netSalary));
}
}
public class Main {
public static void main(String[] args) {
Programmer programmer = new Programmer("John Doe", 1001, "123 Main St",
"[email protected]", "555-123-4567", 5000);
programmer.generatePaySlip();
}
}
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:

Step 1: Import the java packages.


Step 2: Create an abstract class called Shape.
- Declare public integer variables x and y.
- Define an abstract method named printArea.
Step 3: Create a class called Rectangle1 that extends Shape.
- Implement the printArea() method:
- Declare a float variable area.
- Calculate the area of a rectangle (x * y).
- Print the area of the rectangle.
Step 4: Create a class called Triangle that extends Shape.
- Implement the printArea() method:
- Declare a float variable area.
- Calculate the area of a triangle ((x * y) / 2.0f).
- Print the area of the triangle.
Step 5: Create a class called Circle that extends Shape.
- Implement the printArea() method:
- Declare a float variable area.
- Calculate the area of a circle ((22 * x * x) / 7.0f).
- Print the area of the circle.
Step 6: Create the main class called AreaOfShapes.
- In the main method:
- Declare an integer variable choice to store the user's choice.
- Create a Scanner object sc to read user input.
- Display a menu to the user with options to calculate the area of a
rectangle, triangle, or circle.
- Prompt the user to enter their choice.
- Use a switch statement to handle different cases:
- Case 1: Calculate the area of a rectangle:
- Create a Rectangle1 object r.
- Prompt the user to enter the length and breadth.
- Set the x and y properties of r.
REG NO:112022104035

- Call r.printArea() to calculate and display the area.


- Case 2: Calculate the area of a triangle:
- Create a Triangle object t.
- Prompt the user to enter the base and height.
- Set the x and y properties of t.
- Call t.printArea() to calculate and display the area.
- Case 3: Calculate the area of a circle:
- Create a Circle object c.
- Prompt the user to enter the radius.
- Set the x property of c.
- Call c.printArea() to calculate and display the are
- Default: Display an error message for an incorrect choice.
Step 7: Save the file as “AreaOfShapes.java”.
Step 8: Run the program using AreaOfShapes.java.

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

System.out.println("Menu \n 1.Area of Rectangle \n 2.Area of Traingle \n 3.Area of Circle


");
System.out.print("Enter your choice : ");
choice=sc.nextInt();
switch(choice) {
case 1: System.out.println("Enter length and breadth for area of rectangle : ");
Rectangle1 r = new Rectangle1();
r.x=sc.nextInt();
r.y=sc.nextInt();
r.printArea();
break;
case 2: System.out.println("Enter bredth and height for area of traingle : ");
Triangle t = new Triangle();
t.x=sc.nextInt();
t.y=sc.nextInt();
t.printArea();
break;
case 3: System.out.println("Enter radius for area of circle : ");
Circle c = new Circle();
c.x = sc.nextInt();
c.printArea();
break;
default:System.out.println("Enter correct choice");
}
}
}
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:

FINDING THE AREA OF DIFFERENT SHAPES USING AN INTERFACE.

AIM:

To create a java program to find the Area of different shapes using an interface.

ALGORITHM:

Step 1: import the java packages.


Step 2: Define the Shape interface
Step 3: Create classes for different shapes that implement the Shape interface
Step 4: Create a main class to use the shape classes
Step 5: save the file as “Main.java”.

PROGRAM:

// Step 1: Define the Shape interface


interface Shape {
double calculateArea();
}
// Step 2: Create classes for different shapes that implement the Shape interface
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double calculateArea() {
return width * height;
}
}
class Triangle implements Shape {
REG NO:112022104035

private double base;


private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double calculateArea() {
return 0.5 * base * height;
}
}
// Step 3: Create a main class to use the shape classes
public class Main {
public static void main(String[] args) {
// Create instances of different shapes
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4.0, 6.0);
Shape triangle = new Triangle(3.0, 8.0);
// Calculate and display the areas
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Rectangle Area: " + rectangle.calculateArea());
System.out.println("Triangle Area: " + triangle.calculateArea());
}
}

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:

IMPLEMENT EXCEPTION HANDLING AND CREATION OF USER DEFINED EXCEPTIONS

AIM:

To create a java program to Implement exception handling and creation of user defined
exceptions.

ALGORITHM:

Step 1: Import the java packages.


Step 2: Create a custom exception class named InvalidAgeException Constructor that takes a
custom error message as a parameter Call the constructor of the parent Exception class with
the
provided message
Step 3: Create a class that uses the custom exception InvalidAgeException
Step 4: Define a method to check the age and throw the custom exception if age is less than 18
Throw an object of the user-defined exception InvalidAgeException
Step 5: Define the main method
Step 6: Call the validate method with an age value
Step 7: Catch the custom exception InvalidAgeException
Step 8: Print the message from the InvalidAgeException object
Step 9: Continue with the rest of the code
Step 10: Save the file as “TestCustomException1.java”

PROGRAM:

// class representing custom exception


class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote");
}
REG NO:112022104035

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:

To create a java program to implement a multi-threaded application.

ALGORITHM:

Step 1: Import the java packages.


Step 2: Create the NumberGenerator class implementing Runnable.
Step 3: Initialize the random number generator, evenThread, oddThread, and count.
Step 4: Implement the run method for NumberGenerator.
- Generate random numbers and notify even or odd threads based on the number's
parity.
- Sleep for 1 second between number generation.
- Exit the program after generating 5 numbers.
Step 5: Create the EvenThread class implementing Runnable.
- Initialize it with the NumberGenerator instance.
- Implement the run method.
- Continuously check for interruptions.
- When interrupted, calculate and print the square of a random number.
Step 6: Create the OddThread class implementing Runnable.
- Initialize it with the NumberGenerator instance.
- Implement the run method.
- Continuously check for interruptions.
- When interrupted, calculate and print the cube of a random number.
Step 7: Create the Main class.
- Initialize NumberGenerator, evenThread, and oddThread.
- Start evenThread and oddThread.
- Start generatorThread to generate random numbers and notify threads.
Step 8: Save the file as “Main.java”
REG NO:112022104035

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:

WRITE A PROGRAM TO PERFORM FILE OPERATIONS

AIM:

To write a java program to perform file operations.

ALGORITHM:

Step 1: Import the java packages


Step 2: Create a new file.
Step 3: Write data to the file.
Step 4: Read and display data from the file.
Step 5: Delete the file.
Step 6: Save the file as “ FileOperationsDemo.java”.

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

// Method to write data to a file


private static void writeToFile(String fileName, String data) {
try (FileOutputStream fos = new FileOutputStream(fileName)) {
byte[] bytes = data.getBytes();
fos.write(bytes);
System.out.println("Data written to the file.");
} catch (IOException e) {
System.err.println("An error occurred while writing to the file: " + e.getMessage());
}
}
// Method to read data from a file
private static String readFromFile(String fileName) {
StringBuilder content = new StringBuilder();
try (FileInputStream fis = new FileInputStream(fileName)) {
int byteRead;
while ((byteRead = fis.read()) != -1) {
content.append((char) byteRead);
}
} catch (IOException e) {
System.err.println("An error occurred while reading from the file: " + e.getMessage());
}
return content.toString();
}
// Method to delete a file
private static void deleteFile(String fileName) {
File file = new File(fileName);
if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
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:

DEVELOP APPLICATIONS TO DEMONSTRATE THE FEATURES OF GENERICS CLASSES

AIM:

To write a java program to develop applications to demonstrate the features of generics


classes.

ALGORITHM:

Step 1: Import the java packages.


Step 2: Create a new Java class called Main
Step 3: Inside the Main class, define the main method
Step 4: Inside the main method, create an instance of the DemoClass class
Step 5: Call the genericsMethod method of the DemoClass instance with a String
argument
Step 6: Call the genericsMethod method of the DemoClass instance with an Integer
argument.
Step 7: Create a new Java class called DemoClass
Step 8: Inside the DemoClass class, define the genericsMethod
Step 9: Inside the genericsMethod method, print "Generics Method:" and the data passed
as an argument
Step 10: Save the file as “Main.java”.

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:

DEVELOP APPLICATIONS USING JAVAFX CONTROLS, LAYOUTS AND MENUS

AIM:

To write a java program to Develop applications using JavaFX controls, layouts and
menus.

ALGORITHM:

Step 1: Import the JavaFX packages.


Step 2: Create a main class that extends Application.
Step 3: Implement the 'start' method:
a. Create a primary stage (main window).
b. Define the layout (e.g., VBox, HBox) to organize UI elements.
c. Create JavaFX controls (buttons, labels, etc.) and customize their appearance.
d. Set event handlers for user interactions (e.g., button clicks).
e. Create menus and menu items using MenuBar, Menu, and MenuItem.
f. Define actions for menu items (e.g., exit the application).
g. Add all UI elements (controls, menus) to the layout.
h. Create a scene with the layout and set the stage's title.
i. Set the scene for the primary stage and show it.
Step 4: Implement event handlers and actions for user interactions
Step 5: Customize the appearance and behavior of UI elements as needed.
Step 6: Test the application to ensure it functions correctly.
Step 7: Compile and run the JavaFX application.

PROGRAM:

// Java program to create a menu bar and add


// menu to it and also add menuitems to menu
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.scene.control.Alert.AlertType;
import java.time.LocalDate;
public class MenuBar_1 extends Application {
REG NO:112022104035

// launch the application


public void start(Stage s)
{
// set title for the stage
s.setTitle("creating MenuBar");

// 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");

// add menu items to menu


m.getItems().add(m1);
m.getItems().add(m2);
m.getItems().add(m3);

// create a menubar
MenuBar mb = new MenuBar();

// add menu to menubar


mb.getMenus().add(m);

// create a VBox
VBox vb = new VBox(mb);

// create a scene
Scene sc = new Scene(vb, 500, 300);

// set the scene


s.setScene(sc);

s.show();
}

public static void main(String args[])


{
// launch the application
launch(args);
}
}
REG NO:112022104035

OUTPUT:

RESULT:

Thus the java to Develop applications using JavaFX controls, layouts and menus
has been successfully executed.
REG NO:112022104035

EX NO:
DATE:

DEVELOP A MINI PROJECT FOR ANY APPLICATION USING JAVA CONCEPTS

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

System.out.print("Enter your choice: ");


choice = scanner.nextInt();
switch (choice) {
case 1:
house.displayTenants();
break;
case 2:
int totalRent = house.calculateTotalRent();
System.out.println("Total Rent Amount: $" + totalRent);
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
} while (choice != 3);
scanner.close();
}
}

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

House Rent Management System


1. Display Tenants
2. Calculate Total Rent
3. Exit
Enter your choice: 2

Total Rent Amount: 2450

House Rent Management System


1. Display Tenants
2. Calculate Total Rent
3. Exit
Enter your choice: 3
Exiting...

RESULT:
Thus the java to develop a mini project for house rent management system has been
successfully executed.

You might also like