Oops Manual
Oops Manual
ENGINEERING
LAB MANUAL
CS3381-OBJECT ORIENTED PROGRAMMING LABORATORY
LABORATORY
PREPARED BY
VERIFIED BY
APPROVED BY
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Name :
Register Number :
Subject Name :
Subject Code :
Batch :
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Date: Internal:
External:
INDEX
06 Illustration of multi-threading
Windows 10
Java SE 12
Ex No: 1 PROGRAM TO SEQUENTIAL SEARCH, BINARY SEARCH,
AND QUADRATIC SORTING ALGORITHMS
Date:
AIM:
To develop a Java application to Sequential search, Binary search and quadratic sorting algorithms.
ALGORITHM:
STEP 1: Start
STEP 2.1: First, we have to traverse the array elements using a for loop.
STEP 2.2: In each iteration of for loop, compare the search element with the current array element,
STEP 2.2.1: If the element matches, then return the index of the corresponding array element
STEP 2.2.2: If the element does not match, then move to the next element.
STEP 2.2.3: If thereis no match or the search element is not present in the given array, return -1
STEP 4.3: Replace the value at location Min with a different value. Step 4.4: Increase Min to pointto
the next element
STEP 5.2: Compare the current element (key) to one that came before it.
STEP 5.3: If the data at the current index is less than the data at the previous index, you will
compare it to the element before it
STEP 5.4: You will shift bigger elements to the next index to make space for swapped elements, and
then you will iterate the same steps again to sort the complete array.
STEP 7: Stop
PROGRAM:
Sequential Search:
class Sequential_Search
{
// Function for search
public static int search(int arr[], int x)
{
int n = arr.length;
// Traverse array arr[]
for (int i = 0; i < n; i++)
{
// If element found then
// return that index
if (arr[i] == x)
return i;
}
return -1;
}
// Driver Code
public static void main(String args[])
{
// Given arr[]
int arr[] = { 2, 3, 4, 10, 40 };
// Element to search
int x = 10;
// Function Call
int result = search(arr, x);
if (result == -1)
System.out.print("Element is not present in array");
else
System.out.print("Element is present" + " at index " + result);
}
}
Binary Search:
class BinarySearch {
// Function that returns index of
// x if it is present in arr[l, r]
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l) / 2;
// If the element is present
// at the middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than
// mid, then it can only be
// present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l,mid - 1, x);
// Else the element can only be
// present in right subarray
return binarySearch(arr, mid + 1,r, x);
}
// Reach here when element is
// not present in array
return -1;
}
// Driver Code
public static void main(String args[])
{
// Create object of this class
BinarySearch ob = new BinarySearch();
// Given array arr[]
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
// Function Call
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);
}
}
Selection Sort:
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Prints the array
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver code to test above
public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
Insertion Sort
OUTPUT:
Sequential Search
Element is present at index 4
Binary Search
Element is present at index 4
Selection Sort
Sorted Array 11 12 22 25 64
Insertion Sort
5 6 11 12 13
RESULT
AIM:
To develop a stack and queue data structures using classes and objects.
ALGORITHM:
STEP 1: Push inserts an item at the top of the stack (i.e., above its current top element).
STEP 2: Pop removes the object at the top of the stack and returns that object from the
function. The stack size will be decremented by one.
STEP 3: IsEmpty tests if the stack is empty or not.
STEP 4: IsFull tests if the stack is full or not.
STEP 5: Peek returns the object at the top of the stack without removing it from the stack
ormodifying the stack in any way.
STEP 6: Size returns the total number of elements present in the stack.
PROGRAM:
Stack Implementation
class Stack
{
private int arr[];
private int top;
private int capacity;
// Constructor to initialize the stack
Stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}
// Utility function to add an element `x` to the stack
public void push(int x)
{
if (isFull())
{
System.out.println("Overflow\nProgram Terminated\n");
System.exit(-1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}
// Utility function to pop a top element from the stack
public int pop()
{
// check for stack underflow
if (isEmpty())
{
System.out.println("Underflow\nProgram Terminated");
System.exit(-1);
}
System.out.println("Removing " + peek());
OUTPUT
Inserting 1
Inserting 2
Removing 2
Removing 1
Inserting 3
Removing 3
Queue Implementation
import java.util.LinkedList;
import java.util.Queue;
class Main
{
public static void main(String[] args)
{
Queue<String> queue = new LinkedList<String>();
queue.add("A"); // Insert `A` into the queue
queue.add("B"); // Insert `B` into the queue
queue.add("C"); // Insert `C` into the queue
queue.add("D"); // Insert `D` into the queue
// Prints the front of the queue (`A`)
System.out.println("The front element is " + queue.peek());
queue.remove(); // removing the front element (`A`)
queue.remove(); // removing the front element (`B`)
// Prints the front of the queue (`C`)
System.out.println("The front element is " + queue.peek());
// Returns the total number of elements present in the queue
System.out.println("The queue size is " + queue.size());
// check if the queue is empty
if (queue.isEmpty())
{
System.out.println("The queue is empty");
}
else
{
System.out.println("The queue is not empty");
}
}
}
OUTPUT
The front element is A
The front element is C
The queue size is 2
The queue is not empty
RESULT
AIM
To develop a java application to generate pay slip for different category of employees using the
concept of inheritance.
EXPLANATION
Develop a java application with 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 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 fund.
Generate pay slips for the employees with their gross and net salary
ALGORITHM
PROGRAM
package employee;
import java.io.IOException;
import java.util.Scanner;
class Emp
{
String ename,Address,email;
int eid;
int mobile;
void getEmployeedetails()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the Emp_id. :");
eid=in.nextInt();
System.out.println("Enter the Employee Name:");
ename=in.next();
System.out.println("Enter the Employee Address:");
Address=in.next();
System.out.println("Enter the Employee Email id :");
email=in.next();
System.out.println("Enter the Mobile No:");
mobile=in.nextInt();
}
void pay_calulation(double BasicPay)
{
double DA,HRA,PF,Sfund,Gross_Salary,Netsalary;
DA=BasicPay*0.97;
HRA=BasicPay*0.10;
PF=BasicPay*0.12;
Sfund=BasicPay*0.1;
Gross_Salary=BasicPay+DA+HRA;
Netsalary=Gross_Salary-(PF+Sfund);
System.out.println("Gross salary of the Employee"+Gross_Salary);
System.out.println("Net salary of the Employee: "+Netsalary);
}
void display()
{
System.out.println("Emp_id:"+eid);
System.out.println("Employee Name:"+ename);
System.out.println("Employee Address:"+Address);
System.out.println("Employee Email id :"+email);
System.out.println("Employee Mobile No:"+mobile);
}
}
class Programmer extends Emp
{
double BasicPay;
void Programmerdetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the Programmer:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
class AssistantProfessor extends Emp
{
void APDetails()
{
double BasicPay;
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the AssistantProfessor:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
class AssociateProfessor extends Emp
{
double BasicPay;
void ASPDetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the AssociateProfessor:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
class Professor extends Emp
{
double BasicPay;
void profDetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the Professor:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
public class Employee
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Choose the type Employee");
System.out.println("1.Programmer ,2.Assistant Professor,3.Associate Professor ,4.Professor: ");
int ch=in.nextInt();
switch(ch)
{
case 1: System.out.println("PROGRAMMER DETAILS");
Programmer p=new Programmer();
p.Programmerdetails();
break;
case 2: System.out.println("Assistant Professor DETAILS");
AssistantProfessor ap=new AssistantProfessor();
ap.APDetails();
break;
case 3: System.out.println("Associate Professor DETAILS");
AssociateProfessor asp=new AssociateProfessor();
asp.ASPDetails();
break;
case 4: System.out.println("Professor DETAILS");
Professor pf=new Professor();
pf.profDetails();
break;
}
}
}
OUTPUT
RESULT
AIM
To write a java program to calculate the area of rectangle, circle and triangle using the concept
of abstract class.
EXPLANATION
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.
ALGORITHM
STEP 1: Create an abstract class with the name shape
STEP 1.1: Let sides of shape be Side1 and Side2, create variables Side1, Side2
STEP 1.2: Define an empty method PrintArea()
STEP 2: Create three classes with names Rectangle, Triangle and Circle
STEP 2.1: Extend the Shape class in each of these classes
STEP 2.2: Develop the implementation of Area in each class appropriately
STEP 2.3: For Eg: PrintArea() of Circle would be 3.14*Side1*Side1 ; here Side1 is
considered ascircle’s radius
STEP 3: Write a class with main method
STEP 4: Create instance of all three classes
STEP 5: Calculate the Area for each shape
STEP 6: Display the area
PROGRAM
RESULT
AIM
ALGORITHM
PROGRAM
package example1;
class MyException extends Exception
{
String str1;
MyException(String str2)
{
str1=str2;
}
public String toString()
{
return ("MyException Occurred: "+str1);
}
}
public class Example1
{
public static void main(String[] args)
{
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp)
{
System.out.println("Catch Block");
System.out.println(exp);
}
}
}
OUTPUT:
RESULT
AIM
EXPLANATION
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, 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.
ALGORITHM
PROGRAM
package mtherad;
import java.util.*;
class even implements Runnable
{
public int x;
public even(int x)
{this.x=x;
}
@Override
public void run()
{
System.out.println("Thread Name:Even Thread and square is: " + x * x);
}
}
class odd implements Runnable
{
public int x;
public odd(int x){
this.x=x;
}
@Override
public void run()
{
System.out.println("Thread Name:Odd Thread and cube is :"+ x * x * x);
}
}
class A extends Thread{
public String tname;
public Random r;
public Thread t1,t2;
public A(String s){
tname=s;
}
@Override
public void run()
{
int num=0;
r=new Random();
try {
for(int i=0;i<50;i++){
num=r.nextInt(100);
System.out.println("main thread and generated number is"+num);
if(num%2==0)
{
t1=new Thread(new even(num));
t1.start();
}else{
t2=new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println(" ");
}
}
catch(InterruptedException ex)
{
System.out.println(ex.getMessage());
}
}
}
public class Mtherad
{
public static void main(String[] args)
{
A a=new A("one");
a.start();
}
}
OUTPUT:
RESULT
AIM
To write a java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length of the
file in bytes.
EXPLANATION
Write a Java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length of the
file in bytes.
ALGORITHM
STEP 1: Create a text file with some contents
STEP 1.1: Let the name of file be ‘Example.txt’
STEP 1.2: Enter some content and save in the same folder as java program
STEP 2: Create a class with main method
STEP 2.1: Create a file object
STEP 2.2: Print all the attributes of the file objects
PROGRAM
package Filedemo;
import java.util.Scanner;
import java.io.File;
public class Filedemo {
public static void main(String[] args)
{
String filename;
Scanner s=new Scanner(System.in);
System.out.println("Enter the file name ");
filename=s.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 ");
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());
}
}
OUTPUT
RESULT
AIM
ALGORITHM
PROGRAM
OUTPUT
AGNI
3128
RESULT
Date:
AIM
ALGORITHM
PROGRAM
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Label_Test extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
OUTPUT
Menu
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenuExample extends Application {
public static void main(String[] args)
{
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception
{
// TODO Auto-generated method stub
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene);
primaryStage.show();
}
}
OUTPUT
RESULT
AIM
To develop a mini project for Ping Pong game application using JavaFX controls, layouts.
ALGORITHM
PROGRAM
import java.util.Random;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Ex11 extends Application
{
//variable
private static final int width = 800;
private static final int height = 600;
private static final int PLAYER_HEIGHT = 100;
private static final int PLAYER_WIDTH = 15;
private static final double BALL_R = 15;
private int ballYSpeed = 1;
private int ballXSpeed = 1;
private double playerOneYPos = height / 2;
private double playerTwoYPos = height / 2;
private double ballXPos = width / 2;
private double ballYPos = height / 2;
private int scoreP1 = 0;
private int scoreP2 = 0;
private boolean gameStarted;
private int playerOneXPos = 0;
private double playerTwoXPos = width - PLAYER_WIDTH;
public void start(Stage stage) throws Exception
{
stage.setTitle("P O N G");
//background size
Canvas canvas = new Canvas(width, height);
GraphicsContext gc = canvas.getGraphicsContext2D();
//JavaFX Timeline = free form animation defined by KeyFrames and their duration
Timeline tl = new Timeline(new KeyFrame(Duration.millis(10), e -> run(gc)));
//number of cycles in animation INDEFINITE = repeat indefinitely
tl.setCycleCount(Timeline.INDEFINITE);
//mouse control (move and click)
canvas.setOnMouseMoved(e -> playerOneYPos = e.getY());
canvas.setOnMouseClicked(e -> gameStarted = true);
stage.setScene(new Scene(new StackPane(canvas)));
stage.show();
tl.play();
}
private void run(GraphicsContext gc)
{
//set graphics
//set background color
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, width, height);
//set text
gc.setFill(Color.BLACK);
gc.setFont(Font.font(25));
if(gameStarted) {
//set ball movement
ballXPos+=ballXSpeed;
ballYPos+=ballYSpeed;
//simple computer opponent who is following the ball
if(ballXPos < width - width / 4)
{
playerTwoYPos = ballYPos - PLAYER_HEIGHT / 2;
} else
{
playerTwoYPos = ballYPos > playerTwoYPos + PLAYER_HEIGHT / 2 ?playerTwoYPos += 1:
playerTwoYPos - 1;
}
//draw the ball
gc.fillOval(ballXPos, ballYPos, BALL_R, BALL_R);
} else
{
//set the start text
gc.setStroke(Color.BLACK);
gc.setTextAlign(TextAlignment.CENTER);
gc.strokeText("Click", width / 2, height / 2);
//reset the ball start position
ballXPos = width / 2;
ballYPos = height / 2;
//reset the ball speed and the direction
ballXSpeed = new Random().nextInt(2) == 0 ? 1: -1;
ballYSpeed = new Random().nextInt(2) == 0 ? 1: -1;
}
//makes sure the ball stays in the canvas
if(ballYPos > height || ballYPos < 0) ballYSpeed *=-1;
//if you miss the ball, computer gets a point
if(ballXPos < playerOneXPos - PLAYER_WIDTH)
{
scoreP2++;
gameStarted = false;
}
//if the computer misses the ball, you get a point
if(ballXPos > playerTwoXPos + PLAYER_WIDTH)
{
scoreP1++;
gameStarted = false;
}
//increase the speed after the ball hits the player
if( ((ballXPos + BALL_R > playerTwoXPos) && ballYPos >= playerTwoYPos && ballYPos <=
playerTwoYPos + PLAYER_HEIGHT) ||
((ballXPos < playerOneXPos + PLAYER_WIDTH) && ballYPos >= playerOneYPos &&
ballYPos <= playerOneYPos + PLAYER_HEIGHT))
{
ballYSpeed += 1 * Math.signum(ballYSpeed);
ballXSpeed += 1 * Math.signum(ballXSpeed);
ballXSpeed *= -1;
ballYSpeed *= -1;
}
//draw score
gc.fillText(scoreP1 + "\t\t\t\t\t\t\t\t" + scoreP2, width / 2, 100);
//draw player 1 & 2
gc.fillRect(playerTwoXPos, playerTwoYPos, PLAYER_WIDTH, PLAYER_HEIGHT);
gc.fillRect(playerOneXPos, playerOneYPos, PLAYER_WIDTH, PLAYER_HEIGHT);
}
// start the application
public static void main(String[] args) {
launch(args);
}
}
OUTPUT
RESULT
Thus, the mini project using Java concepts was developed and executed successfully.
1.1Linear search
It is used to search a key element from multiple elements.
1.2Binary search
A search algorithm that finds the position of a target value within a sorted
array. Binary search compares the target value to the middle element of
the array.
Steps
Divide the search space into two halves by finding the middle index
“mid”.
Compare the middle element of the search space with the key.
If the key is found at middle element, the process is terminated.
If the key is not found at middle element, choose which half will be used as
the next search space.
o If the key is smaller than the middle element, then the left side is
used for next search.
o If the key is larger than the middle element, then the right side is
used for next search.
This process is continued until the key is found or the total search space is
exhausted.
1.3Selection Sort
In selection sort, the smallest value
among the unsorted elements of the array is
selected in every pass and inserted to its appropriate
position into the array.
1.4Insertion Sort
Initial:
Current element is 23
The first element in the array is assumed to be sorted.
The sorted part until 0th index is : [23]
First Pass:
Compare 1 with 23 (current element with the sorted part).
Since 1 is smaller, insert 1 before 23 .
The sorted part until 1st index is: [1, 23]
Second Pass:
Compare 10 with 1 and 23 (current element with the sorted part).
Since 10 is greater than 1 and smaller than 23 ,
insert 10 between 1 and 23 .
The sorted part until 2nd index is: [1, 10, 23]
Third Pass:
Compare 5 with 1 , 10 , and 23 (current element with the sorted part).
Since 5 is greater than 1 and smaller than 10 , insert 5 between 1 and 10
The sorted part until 3rd index is : [1, 5, 10, 23]
Fourth Pass:
Compare 2 with 1, 5, 10 , and 23 (current element with the sorted part).
Since 2 is greater than 1 and smaller than 5 insert 2 between 1 and 5 .
The sorted part until 4th index is: [1, 2, 5, 10, 23]
Final Array:
The sorted array is: [1, 2, 5, 10, 23]
To implement a queue
Create an array ar of size n and take two variables front and rear which
are initialized as 0 and -1 respectively
Rear is the index up to which the elements are stored in the array
including the rear index itself. We mainly add an item by incrementing
it.
Front is the index of the first element of the array. We mainly remove
the element at this index in Dequeue operation.