0% found this document useful (0 votes)
3 views

oops batch2

Uploaded by

ece apce
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

oops batch2

Uploaded by

ece apce
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

1.

Solve problem by using sequential search algorithms (Selection,


insertion)

Program:

public class SortUsingSelectionAndInsertion {


public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {


int[] selectionSortArr = {64, 25, 12, 22, 11};
int[] insertionSortArr = {64, 25, 12, 22, 11};
System.out.println("Original array for Selection Sort:");
printArray(selectionSortArr);
selectionSort(selectionSortArr);
System.out.println("Sorted array using Selection Sort:");
printArray(selectionSortArr);
System.out.println("\nOriginal array for Insertion Sort:");
printArray(insertionSortArr);
insertionSort(insertionSortArr);
System.out.println("Sorted array using Insertion Sort:");
printArray(insertionSortArr);
}
}

Output:

Original array for Selection Sort:


64 25 12 22 11
Sorted array using Selection Sort:
11 12 22 25 64

Original array for Insertion Sort:


64 25 12 22 11
Sorted array using Insertion Sort:
11 12 22 25 64
2. Solve problem by using binary search sorting algorithms (Selection,
insertion)

Program:

public class SortAndBinarySearch {


public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
public static int binarySearch(int[] arr, int key) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] < key) left = mid + 1;
else right = mid - 1;
}
return -1;
}

public static void printArray(int[] arr) {


for (int num : arr) System.out.print(num + " ");
System.out.println();
}
public static void main(String[] args) {
int[] arr1 = {64, 25, 12, 22, 11};
int[] arr2 = {64, 25, 12, 22, 11};
selectionSort(arr1);
System.out.println("Selection Sort Result: ");
printArray(arr1);
insertionSort(arr2);
System.out.println("Insertion Sort Result: ");
printArray(arr2);
int key = 22;
System.out.println("Binary Search in Selection Sorted array: " + binarySearch(arr1, key));
System.out.println("Binary Search in Insertion Sorted array: " + binarySearch(arr2, key));
}
}

Output:

Selection Sort Result:


11 12 22 25 64
Insertion Sort Result:
11 12 22 25 64
Binary Search in Selection Sorted array: 2
Binary Search in Insertion Sorted array: 2
3. Develop a java application with an employee class with members for
generate pay Slip using inheritance.

Program:

class Employee {
String name;
int employeeId;
public Employee(String name, int employeeId) {
this.name = name;
this.employeeId = employeeId;
}
public void generatePaySlip() {
System.out.println("Employee Name: " + name);
System.out.println("Employee ID: " + employeeId);
System.out.println("Base Salary: Not Defined");
System.out.println("Bonus: Not Defined");
}
}
class FullTimeEmployee extends Employee {
double baseSalary;
double bonus;
public FullTimeEmployee(String name, int employeeId, double baseSalary, double bonus) {
super(name, employeeId); // Call parent constructor
this.baseSalary = baseSalary;
this.bonus = bonus;
}
public void generatePaySlip() {
super.generatePaySlip();
System.out.println("Base Salary: $" + baseSalary);
System.out.println("Bonus: $" + bonus);
double totalSalary = baseSalary + bonus;
System.out.println("Total Salary: $" + totalSalary);
}
}

public class PaySlipApp {


public static void main(String[] args) {
FullTimeEmployee emp = new FullTimeEmployee("John Doe", 101, 5000.0, 500.0);
System.out.println("Pay Slip for Full Time Employee:");
emp.generatePaySlip();
}
}
Output:

Pay Slip for Full Time Employee:


Employee Name: John Doe
Employee ID: 101
Base Salary: $5000.0
Bonus: $500.0
Total Salary: $5500.0
4. Write a java program to create abstract class for calculating area of
different shape.

Program:

abstract class Shape {


abstract double calculateArea();
}
class Circle extends Shape {
double radius;
public Circle(double radius) {
this.radius = radius;
}
double calculateArea() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
double calculateArea() {
return length * width;
}
}
class Triangle extends Shape {
double base, height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
double calculateArea() {
return 0.5 * base * height;
}
}
public class ShapeAreaCalculator {
public static void main(String[] args) {
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4.0, 6.0);
Shape triangle = new Triangle(3.0, 7.0);
System.out.println("Area of Circle: " + circle.calculateArea());
System.out.println("Area of Rectangle: " + rectangle.calculateArea());
System.out.println("Area of Triangle: " + triangle.calculateArea());
}
}

Output:

Area of Circle: 78.53981633974483


Area of Rectangle: 24.0
Area of Triangle: 10.5
5. Write a java program to create interface for calculating area of different
shape.

Program:
interface Shape {
double calculateArea();
}
class Circle implements Shape {
double radius;
public Circle(double radius) {
this.radius = radius;
}
public double calculateArea() {
return Math.PI * radius * radius;
}
}
class Rectangle implements Shape {
double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double calculateArea() {
return length * width;
}
}
class Triangle implements Shape {
double base, height;

public Triangle(double base, double height) {


this.base = base;
this.height = height;
}
public double calculateArea() {
return 0.5 * base * height;
}
}
public class ShapeAreaCalculator {
public static void main(String[] args) {
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4.0, 6.0);
Shape triangle = new Triangle(3.0, 7.0);
System.out.println("Area of Circle: " + circle.calculateArea());
System.out.println("Area of Rectangle: " + rectangle.calculateArea());
System.out.println("Area of Triangle: " + triangle.calculateArea());
}
}
Output:

Area of Circle: 78.53981633974483


Area of Rectangle: 24.0
Area of Triangle: 10.5
6.Write a java program for implementing user defined exceptions handling.
Program:
class AgeNotValidException extends Exception {

public AgeNotValidException(String message) {

super(message);

public class UserDefinedExceptionExample {

public static void validateAge(int age) throws AgeNotValidException {

if (age < 18) {

throw new AgeNotValidException("Age is less than 18, access denied.");

} else {

System.out.println("Age is valid. Access granted.");

public static void main(String[] args) {

try {

validateAge(16);

} catch (AgeNotValidException e) {

System.out.println("Exception caught: " + e.getMessage());

try {

validateAge(25);

} catch (AgeNotValidException e) {

System.out.println("Exception caught: " + e.getMessage());

}
Output:
Exception caught: Age is less than 18, access denied.

Age is valid. Access granted.


7. Write a java program for implementing generic class.Write a java program
for implementing multi-threaded application.

Program:
class MyThread1 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
class MyThread2 implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 2: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class MultiThreadExample {
public static void main(String[] args) {
MyThread1 thread1 = new MyThread1();
thread1.start();
MyThread2 myRunnable = new MyThread2();
Thread thread2 = new Thread(myRunnable);
thread2.start(); // Starting Thread 2
}
}

Output:
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4
Thread 1: 5
Thread 2: 5
8. Write a java program for implementing generic class.
Program:
class Box<T> {

private T value;

public Box(T value) {

this.value = value;

public T getValue() {

return value;

public void setValue(T value) {

this.value = value;

public class GenericClassExample {

public static void main(String[] args) {

Box<Integer> intBox = new Box<>(10);

System.out.println("Integer value in box: " + intBox.getValue());

Box<String> strBox = new Box<>("Hello, Generics!");

System.out.println("String value in box: " + strBox.getValue());

Box<Double> dblBox = new Box<>(3.14);

System.out.println("Double value in box: " + dblBox.getValue());

Output:
Integer value in box: 10

String value in box: Hello, Generics!

Double value in box: 3.14


9. Develop queue data structures using classes and objects.
Program:
class Queue {

private int maxSize;

private int front;

private int rear;

private int[] queueArray;

public Queue(int size) {

maxSize = size;

queueArray = new int[maxSize];

front = 0;

rear = -1;

public boolean isFull() {

return rear == maxSize - 1;

public boolean isEmpty() {

return front > rear;

public void enqueue(int value) {

if (isFull()) {

System.out.println("Queue is full, cannot add " + value);

} else {

queueArray[++rear] = value;

System.out.println("Enqueued: " + value);

public int dequeue() {

if (isEmpty()) {

System.out.println("Queue is empty, cannot dequeue");

return -1;
} else {

int value = queueArray[front++];

System.out.println("Dequeued: " + value);

return value;

public int peek() {

if (isEmpty()) {

System.out.println("Queue is empty");

return -1;

} else {

return queueArray[front];

public void displayQueue() {

if (isEmpty()) {

System.out.println("Queue is empty");

} else {

System.out.print("Queue elements: ");

for (int i = front; i <= rear; i++) {

System.out.print(queueArray[i] + " ");

System.out.println();

public class QueueExample {

public static void main(String[] args) {

Queue queue = new Queue(5);

queue.enqueue(10);

queue.enqueue(20);
queue.enqueue(30);

queue.enqueue(40);

queue.enqueue(50);

queue.displayQueue();

queue.enqueue(60);

queue.dequeue();

queue.dequeue();

queue.displayQueue();

System.out.println("Front element is: " + queue.peek());

queue.dequeue();

queue.dequeue();

queue.dequeue();

queue.displayQueue();

Output:
Enqueued: 10

Enqueued: 20

Enqueued: 30

Enqueued: 40

Enqueued: 50

Queue elements: 10 20 30 40 50

Queue is full, cannot add 60

Dequeued: 10

Dequeued: 20

Queue elements: 30 40 50

Front element is: 30

Dequeued: 30

Dequeued: 40

Dequeued: 50

Queue is empty
10. Write a program to Check Prime Number using Interface.
Program:
interface PrimeCheck {

boolean isPrime(int number);

class PrimeNumber implements PrimeCheck {

@Override

public boolean isPrime(int number) {

if (number <= 1) {

return false;

for (int i = 2; i <= Math.sqrt(number); i++) {

if (number % i == 0) {

return false;

return true;

public class PrimeCheckExample {

public static void main(String[] args) {

PrimeCheck primeChecker = new PrimeNumber();

int num1 = 29;

int num2 = 15;

if (primeChecker.isPrime(num1)) {

System.out.println(num1 + " is a prime number.");

} else {

System.out.println(num1 + " is not a prime number.");

}
if (primeChecker.isPrime(num2)) {

System.out.println(num2 + " is a prime number.");

} else {

System.out.println(num2 + " is not a prime number.");

Output:
29 is a prime number.

15 is not a prime number.


11. Write a Java program to find the sum value of two given type of elements
using a generic class.
Program:
class Sum<T extends Number> {
private T num1, num2;
public Sum(T num1, T num2) {
this.num1 = num1;
this.num2 = num2;
}
public double getSum() {
return num1.doubleValue() + num2.doubleValue();
}
}
public class GenericSumExample {
public static void main(String[] args) {
Sum<Integer> intSum = new Sum<>(10, 20);
System.out.println("Sum of Integers: " + intSum.getSum());
Sum<Double> doubleSum = new Sum<>(10.5, 20.5);
System.out.println("Sum of Doubles: " + doubleSum.getSum());
}
}

Output:
Sum of Integers: 30.0

Sum of Doubles: 31.0


12. Create a Java Application to calculate GPA for 5 subjects using the
marks of the subject and credits of the subject and implement a user
defined exception for subject mark, credits, subject name, and subject
code.

Program:

class InvalidSubjectNameException extends Exception {


public InvalidSubjectNameException(String message) {
super(message);
}
}
class InvalidSubjectCodeException extends Exception {
public InvalidSubjectCodeException(String message) {
super(message);
}
}
class InvalidMarksException extends Exception {
public InvalidMarksException(String message) {
super(message);
}
}
class InvalidCreditsException extends Exception {
public InvalidCreditsException(String message) {
super(message);
}
}
class Subject {
String subjectName;
String subjectCode;
double marks;
int credits;
public Subject(String subjectName, String subjectCode, double marks, int credits) throws
InvalidSubjectNameException, InvalidSubjectCodeException, InvalidMarksException,
InvalidCreditsException {
if (subjectName == null || subjectName.isEmpty()) {
throw new InvalidSubjectNameException("Subject Name cannot be empty");
}
if (!subjectCode.matches("^[A-Za-z]{2}\\d{3}$")) {
throw new InvalidSubjectCodeException("Invalid Subject Code. Format should be like
AB123");
}
if (marks < 0 || marks > 100) {
throw new InvalidMarksException("Marks should be between 0 and 100");
}
if (credits <= 0) {
throw new InvalidCreditsException("Credits should be greater than 0");
}

this.subjectName = subjectName;
this.subjectCode = subjectCode;
this.marks = marks;
this.credits = credits;
}
public double weightedMarks() {
return marks * credits;
}
}
public class GPACalculator {
public static void main(String[] args) {
double totalMarks = 0;
int totalCredits = 0;
Subject[] subjects = new Subject[5];
try {
subjects[0] = new Subject("Mathematics", "MA101", 85, 4);
subjects[1] = new Subject("Physics", "PH102", 90, 3);
subjects[2] = new Subject("Chemistry", "CH103", 75, 4);
subjects[3] = new Subject("Biology", "BI104", 80, 3);
subjects[4] = new Subject("Computer Science", "CS105", 88, 5);
for (Subject subject : subjects) {
totalMarks += subject.weightedMarks();
totalCredits += subject.credits;
}
double GPA = totalMarks / totalCredits;
System.out.println("Your GPA is: " + GPA);
} catch(InvalidSubjectNameException| InvalidSubjectCodeException |
InvalidMarksException | InvalidCreditsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Output:
Your GPA is: 83.68421052631578

Your GPA is: 83.68


13. Write Java programs to implementing Arithmetic exception and
implementing Array IndexOutOfBound exception.

Program:

public class CombinedExceptionExample {


public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
int[] arr = {1, 2, 3, 4, 5}; {
int result = num1 / num2;
System.out.println("Division Result: " + result);
System.out.println("Accessing element at index 5: " + arr[5]);
} catch (ArithmeticException e) {
System.out.println("Error: ArithmeticException caught - Cannot divide by zero.");
System.out.println("Exception Message: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: ArrayIndexOutOfBoundsException caught - Invalid index
accessed.");
System.out.println("Exception Message: " + e.getMessage());
}
System.out.println("Program continues after exception handling.");
}
}
Output:

Error: ArithmeticException caught - Cannot divide by zero.


Exception Message: / by zero
Error: ArrayIndexOutOfBoundsException caught - Invalid index accessed.
Exception Message: Index 5 out of bounds for length 5
Program continues after exception handling.

You might also like