0% found this document useful (0 votes)
31 views109 pages

OOP Problem Statement 2024-25 Sem 2

The document outlines several Java programming tasks, including the implementation of a CaesarCipher class for encryption and decryption, a URLFinder class for validating URLs, and matrix operations such as transposing, calculating determinants, and finding inverses. It also includes methods for generating Pascal's Triangle and Number Triangle, operations on ArrayLists like removing prime numbers, traversing, and adding elements at specific indices. Lastly, it covers finding the largest and smallest elements in an array, reversing an array, and merging two sorted arrays.

Uploaded by

amitdada2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views109 pages

OOP Problem Statement 2024-25 Sem 2

The document outlines several Java programming tasks, including the implementation of a CaesarCipher class for encryption and decryption, a URLFinder class for validating URLs, and matrix operations such as transposing, calculating determinants, and finding inverses. It also includes methods for generating Pascal's Triangle and Number Triangle, operations on ArrayLists like removing prime numbers, traversing, and adding elements at specific indices. Lastly, it covers finding the largest and smallest elements in an array, reversing an array, and merging two sorted arrays.

Uploaded by

amitdada2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 109

OOP Problem Statement

1) Create the CaesarCipher class with the following parts:

● Private fields for the alphabet and shiftedAlphabet


● Write a constructor CaesarCipher that has one int parameter key. This
method should initialize all the private fields of the class.
● Write an encrypt method that has one String parameter named input. This
method returns a String that is the input encrypted using shiftedAlphabet.
● Write a decrypt method that has one String parameter named input. This
method returns a String that is the encrypted String decrypted using the key
associated with this CaesarCipher object. One way to do this is to create
another private field mainKey, which is initialized to be the value of key. Then
you can create a CaesarCipher object within decrypt: CaesarCipher cc = new
CaesarCipher(26 - mainKey); and call cc.encrypt(input).
● Create the TestCaesarCipher class with the following parts:
Create a CaesarCipher object with key 18, encrypt the String read in using the
Scanner class object, print the encrypted String, and decrypt the encrypted
String using the decrypt method.

soln:

// CaesarCipher.java

class CaesarCipher {

private String alphabet;

private String shiftedAlphabet;

private int mainKey;

// Constructor that takes a key and initializes fields

public CaesarCipher(int key) {

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

shiftedAlphabet = alphabet.substring(key) + alphabet.substring(0, key);

mainKey = key;
}

// Method to encrypt a message

public String encrypt(String input) {

StringBuilder encrypted = new StringBuilder();

for (char ch : input.toCharArray()) {

// Convert lowercase to uppercase for consistency

char upperCh = Character.toUpperCase(ch);

int idx = alphabet.indexOf(upperCh);

if (idx != -1) {

char newChar = shiftedAlphabet.charAt(idx);

// Preserve original case

encrypted.append(Character.isLowerCase(ch) ?
Character.toLowerCase(newChar) : newChar);

} else {

// Non-letter characters remain unchanged

encrypted.append(ch);

return encrypted.toString();

// Method to decrypt an encrypted message


public String decrypt(String input) {

CaesarCipher cc = new CaesarCipher(26 - mainKey);

return cc.encrypt(input);

// TestCaesarCipher.java

public class TestCaesarCipher {

public static void main(String[] args) {

// Hardcoded input

String message = "Hello, World!";

int key = 18;

// Create CaesarCipher object

CaesarCipher cipher = new CaesarCipher(key);

// Encrypt the message

String encrypted = cipher.encrypt(message);

System.out.println("Encrypted message: " + encrypted);

// Decrypt the message

String decrypted = cipher.decrypt(encrypted);

System.out.println("Decrypted message: " + decrypted);

}
}

2) Create the URLFinder class with the following parts:


· Private fields for the url

· Write a constructor URLFinder that has one int parameter url. This method
should initialize all the private fields of the class.

● Write an urlChecker method that has one String parameter named inputUrl.
This method returns a Boolean “true” for valid url.
● Create the TestURLFinder class with the following parts:
● create a URLFinder object with String read in using the Scanner class

// URLFinder.java
class URLFinder {
private String url;

// Constructor to initialize the URL


public URLFinder(String url) {
this.url = url;
}

// Method to check if the input URL is valid


public boolean urlChecker(String inputUrl) {
return inputUrl.startsWith("http://") || inputUrl.startsWith("https://");
}
}

// TestURLFinder.java
public class TestURLFinder {
public static void main(String[] args) {
// Hardcoded URL
String testUrl = "https://example.com";

// Create URLFinder object


URLFinder finder = new URLFinder(testUrl);

// Check if URL is valid


boolean isValid = finder.urlChecker(testUrl);

// Output result
if (isValid) {
System.out.println("Valid URL: " + testUrl);
} else {
System.out.println("Invalid URL: " + testUrl);
}
}
}

3) Perform the following operations on given matrix

1 2 3
4 5 6
M = 7 8 9

1. Transpose
2. Determinant
3. Inverse

public class MatrixOperations {

// Transpose function

public static int[][] transpose(int[][] matrix) {

int[][] transposed = new int[3][3];

for (int i = 0; i < 3; i++)

for (int j = 0; j < 3; j++)

transposed[i][j] = matrix[j][i];

return transposed;

}
// Determinant function (3x3)

public static int determinant(int[][] m) {

return m[0][0]*(m[1][1]*m[2][2] - m[1][2]*m[2][1])

- m[0][1]*(m[1][0]*m[2][2] - m[1][2]*m[2][0])

+ m[0][2]*(m[1][0]*m[2][1] - m[1][1]*m[2][0]);

// Inverse function (if determinant != 0)

public static double[][] inverse(int[][] m) {

int det = determinant(m);

if (det == 0) {

return null; // Non-invertible

double[][] inv = new double[3][3];

// Cofactor matrix and then adjugate and divide by determinant

inv[0][0] = (m[1][1]*m[2][2] - m[1][2]*m[2][1]) / (double)det;

inv[0][1] = -(m[0][1]*m[2][2] - m[0][2]*m[2][1]) / (double)det;

inv[0][2] = (m[0][1]*m[1][2] - m[0][2]*m[1][1]) / (double)det;


inv[1][0] = -(m[1][0]*m[2][2] - m[1][2]*m[2][0]) / (double)det;

inv[1][1] = (m[0][0]*m[2][2] - m[0][2]*m[2][0]) / (double)det;

inv[1][2] = -(m[0][0]*m[1][2] - m[0][2]*m[1][0]) / (double)det;

inv[2][0] = (m[1][0]*m[2][1] - m[1][1]*m[2][0]) / (double)det;

inv[2][1] = -(m[0][0]*m[2][1] - m[0][1]*m[2][0]) / (double)det;

inv[2][2] = (m[0][0]*m[1][1] - m[0][1]*m[1][0]) / (double)det;

return inv;

// Print 2D int matrix

public static void printMatrix(int[][] matrix) {

for (int[] row : matrix) {

for (int val : row)

System.out.print(val + "\t");

System.out.println();

}
// Print 2D double matrix

public static void printMatrix(double[][] matrix) {

for (double[] row : matrix) {

for (double val : row)

System.out.printf("%.2f\t", val);

System.out.println();

public static void main(String[] args) {

int[][] M = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

System.out.println("Original Matrix:");

printMatrix(M);
System.out.println("\nTranspose:");

int[][] transposed = transpose(M);

printMatrix(transposed);

System.out.println("\nDeterminant:");

int det = determinant(M);

System.out.println(det);

System.out.println("\nInverse:");

double[][] inv = inverse(M);

if (inv == null) {

System.out.println("Matrix is not invertible (determinant is 0).");

} else {

printMatrix(inv);

}
4) A) Write a Program to Print the Pascal’s and Number Triangle in Java

public class PascalsTriangle {

public static void main(String[] args) {

int N = 6; // You can change this value

for (int i = 0; i < N; i++) {

// Print leading spaces

for (int s = 0; s < N - i; s++) {

System.out.print(" ");

int number = 1;

for (int j = 0; j <= i; j++) {

System.out.print(number + " ");

// Formula: nCr = nCr-1 * (n - r + 1) / r

number = number * (i - j) / (j + 1);


}

System.out.println();

4) B) Write a Java program to print the number triangle

public class NumberTriangle {


public static void main(String[] args) {
int rows = 6; // You can change this

for (int i = 1; i <= rows; i++) {


// Print leading spaces
for (int s = 0; s < rows - i; s++) {
System.out.print(" ");
}

for (int j = 1; j <= i; j++) {


System.out.print(i + " ");
}
System.out.println();
}
}
}
in same pg:

public class TrianglePatterns {

// Method for Pascal's Triangle


public static void printPascalsTriangle(int N) {
System.out.println("Pascal's Triangle:");
for (int i = 0; i < N; i++) {
// Print spaces for alignment
for (int s = 0; s < N - i; s++) {
System.out.print(" ");
}

int number = 1;
for (int j = 0; j <= i; j++) {
System.out.print(number + " ");
number = number * (i - j) / (j + 1);
}
System.out.println();
}
System.out.println(); // for spacing
}

// Method for Number Triangle


public static void printNumberTriangle(int N) {
System.out.println("Number Triangle:");
for (int i = 1; i <= N; i++) {
// Print spaces for alignment
for (int s = 0; s < N - i; s++) {
System.out.print(" ");
}

for (int j = 1; j <= i; j++) {


System.out.print(i + " ");
}
System.out.println();
}
}

// Main method
public static void main(String[] args) {
int N = 6; // You can change N for different sizes
printPascalsTriangle(N);
printNumberTriangle(N);
}
}

5)

A. An ArrayList consists of 1-25 numbers. Write a Java program to remove


prime numbers from an ArrayList using an iterator.

B. Write a Java program to

a. Create and traverse (or iterate) an ArrayList using a for-loop,


iterator, and advance for-loop.

b. Check if the element(value) exists in the ArrayList?

C. Add element at the particular index of the ArrayList?

import java.util.*;

public class ArrayListOperations {

// Utility method to check if a number is prime

public static boolean isPrime(int num) {

if (num <= 1) return false;

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

if (num % i == 0)

return false;

return true;

}
// A. Remove prime numbers from an ArrayList using iterator

public static void removePrimes() {

ArrayList<Integer> numbers = new ArrayList<>();

for (int i = 1; i <= 25; i++) {

numbers.add(i);

System.out.println("\nOriginal List: " + numbers);

Iterator<Integer> iterator = numbers.iterator();

while (iterator.hasNext()) {

int num = iterator.next();

if (isPrime(num)) {

iterator.remove();

System.out.println("After removing prime numbers: " + numbers);

// B. Traverse ArrayList using for-loop and search for a value

public static void traverseAndSearch() {

ArrayList<String> fruits = new ArrayList<>(Arrays.asList("Apple", "Banana",


"Mango", "Orange"));
System.out.println("\nTraversing using for-loop:");

for (int i = 0; i < fruits.size(); i++) {

System.out.println(fruits.get(i));

Scanner sc = new Scanner(System.in);

System.out.print("\nEnter a fruit name to search: ");

String search = sc.nextLine();

boolean found = false;

for (int i = 0; i < fruits.size(); i++) {

if (fruits.get(i).equalsIgnoreCase(search)) {

found = true;

break;

if (found) {

System.out.println(search + " is present in the list.");

} else {

System.out.println(search + " is NOT present in the list.");

}
// C. Add element at a particular index

public static void addAtIndex() {

ArrayList<String> animals = new ArrayList<>(Arrays.asList("Cat", "Dog",


"Elephant"));

System.out.println("\nOriginal List: " + animals);

Scanner sc = new Scanner(System.in);

System.out.print("Enter element to add: ");

String element = sc.nextLine();

System.out.print("Enter index to insert at (0 to " + animals.size() + "): ");

int index = sc.nextInt();

if (index >= 0 && index <= animals.size()) {

animals.add(index, element);

System.out.println("Updated List: " + animals);

} else {

System.out.println("Invalid index.");

// Main menu

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


int choice;

do {

System.out.println("\n====== ArrayList Operations Menu ======");

System.out.println("1. Remove Prime Numbers (1 to 25)");

System.out.println("2. Traverse and Search in ArrayList (for-loop only)");

System.out.println("3. Add Element at a Particular Index");

System.out.println("0. Exit");

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

choice = sc.nextInt();

sc.nextLine(); // clear buffer

switch (choice) {

case 1:

removePrimes();

break;

case 2:

traverseAndSearch();

break;

case 3:

addAtIndex();

break;

case 0:

System.out.println("Exiting program.");
break;

default:

System.out.println("Invalid choice! Try again.");

} while (choice != 0);

6)

 Write a Java program to find the largest and smallest elements in an array of
integers.

● Implement a function to reverse an array in place.


● Given two arrays, write a method to merge them into a single sorted array.

import java.util.*;

public class ArrayTasks {

// 1. Find the largest and smallest elements

public static void findMinMax(int[] arr) {

if (arr.length == 0) {

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

return;

int min = arr[0];


int max = arr[0];

for (int i = 1; i < arr.length; i++) {

if (arr[i] < min)

min = arr[i];

if (arr[i] > max)

max = arr[i];

System.out.println("Smallest element: " + min);

System.out.println("Largest element: " + max);

// 2. Reverse an array in place

public static void reverseArray(int[] arr) {

int left = 0, right = arr.length - 1;

while (left < right) {

int temp = arr[left];

arr[left] = arr[right];

arr[right] = temp;

left++;

right--;

}
}

// 3. Merge two arrays and return a sorted array

public static int[] mergeAndSort(int[] arr1, int[] arr2) {

int[] merged = new int[arr1.length + arr2.length];

for (int i = 0; i < arr1.length; i++)

merged[i] = arr1[i];

for (int i = 0; i < arr2.length; i++)

merged[arr1.length + i] = arr2[i];

Arrays.sort(merged);

return merged;

// Utility method to print array

public static void printArray(String label, int[] arr) {

System.out.print(label);

for (int num : arr)

System.out.print(num + " ");


System.out.println();

// Main method

public static void main(String[] args) {

// Hardcoded array for min/max and reverse

int[] originalArray = {34, 12, 56, 7, 89, 23, 3};

System.out.println("Original array: " + Arrays.toString(originalArray));

// Task 1: Find min and max

findMinMax(originalArray);

// Task 2: Reverse the array

reverseArray(originalArray);

printArray("Reversed array: ", originalArray);

// Task 3: Merge and sort two arrays

int[] arr1 = {5, 8, 1, 10};

int[] arr2 = {2, 7, 3, 9};

printArray("\nArray 1: ", arr1);

printArray("Array 2: ", arr2);


int[] merged = mergeAndSort(arr1, arr2);

printArray("Merged and sorted array: ", merged);

7)
● Write a program to check if a given string is a palindrome.
● Implement a function to count the occurrences of a specific character in a
string.
● Write a program to remove all whitespace from a string.

public class StringTasks {

// 1. Check if a string is a palindrome

public static boolean isPalindrome(String str) {

str = str.toLowerCase(); // ignore case

int left = 0;

int right = str.length() - 1;


while (left < right) {

if (str.charAt(left) != str.charAt(right))

return false;

left++;

right--;

return true;

// 2. Count occurrences of a specific character

public static int countChar(String str, char target) {

int count = 0;
for (char ch : str.toCharArray()) {

if (ch == target)

count++;

return count;

// 3. Remove all whitespace from a string

public static String removeWhitespace(String str) {

return str.replaceAll("\\s+", "");

}
// Main method

public static void main(String[] args) {

// Task 1: Palindrome check

String word = "Madam";

System.out.println("Original word: " + word);

if (isPalindrome(word))

System.out.println("Result: It is a palindrome.");

else

System.out.println("Result: It is NOT a palindrome.");

// Task 2: Count character occurrences

String sentence = "Java is a versatile language.";


char targetChar = 'a';

int count = countChar(sentence.toLowerCase(),


Character.toLowerCase(targetChar));

System.out.println("\nSentence: " + sentence);

System.out.println("Character to count: '" + targetChar + "'");

System.out.println("Occurrences: " + count);

// Task 3: Remove all whitespaces

String messyString = " Hello World \t This is Java! ";

String cleanString = removeWhitespace(messyString);

System.out.println("\nOriginal string with spaces: \"" + messyString + "\"");

System.out.println("String without whitespace: \"" + cleanString + "\"");

}
}

8) Design a class BankAccount with methods for deposit, withdraw, and check
balance. Implement exception handling for insufficient funds during withdrawal.

9) Write a program to read data from a text file using IO Stream class and display
the number of characters and words on the console.

import java.io.*;

public class FileReaderExample {

public static void main(String[] args) {

// File path to be specified

String filePath = "sample.txt"; // Replace with the correct file path

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {

String line;

int charCount = 0;

int wordCount = 0;
// Reading file line by line

while ((line = reader.readLine()) != null) {

charCount += line.length(); // Count characters

String[] words = line.split("\\s+"); // Split line into words based on spaces

wordCount += words.length; // Count words

// Display the result

System.out.println("Number of characters: " + charCount);

System.out.println("Number of words: " + wordCount);

} catch (IOException e) {

System.out.println("Error reading file: " + e.getMessage());

10)
A. Write a program to find the greatest common divisor (GCD) of two numbers.
B. Write a program to convert a decimal number to binary.

public class MathTasks {

// A. Find the GCD of two numbers using Euclidean algorithm

public static int findGCD(int a, int b) {

while (b != 0) {

int temp = b;

b = a % b;

a = temp;

return a;

// B. Convert a decimal number to binary

public static String decimalToBinary(int num) {

if (num == 0) return "0";

StringBuilder binary = new StringBuilder();

while (num > 0) {

binary.insert(0, num % 2);

num = num / 2;
}

return binary.toString();

// Main method

public static void main(String[] args) {

// Task A: GCD

int num1 = 36;

int num2 = 60;

int gcd = findGCD(num1, num2);

System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);

// Task B: Decimal to Binary

int decimalNumber = 25;

String binary = decimalToBinary(decimalNumber);

System.out.println("Binary of " + decimalNumber + " is: " + binary);

11) Create the CarAssembly class which implements Runnable interface with the
following parts:

● Private fields for the componentName(String) and timeToPrepare(int)


● Write a constructor CarAssembly that has two parameters componentName
and timeToPrepare . This method should initialize all the private fields of the
class.
● Write an run method that has sleep method which takes timeToPrepare
parameter. The sleep method is invoveked between two print statements
componentName is preparing & componentName is ready.
● Components names and their preparation times are as follows
● Engine-3000, Body-4000, Wheels-5000

Create three threads namely engineThread, bodyThread, wheelThread and use Join
method for Sysnchronization.

public class CarAssembly implements Runnable {

// Private fields

private String componentName;

private int timeToPrepare;

// Constructor to initialize the fields

public CarAssembly(String componentName, int timeToPrepare) {

this.componentName = componentName;

this.timeToPrepare = timeToPrepare;

// Run method to simulate the assembly process

@Override

public void run() {

try {
// Print that the component is preparing

System.out.println(componentName + " is preparing.");

// Sleep for the specified preparation time (simulates time for assembly)

Thread.sleep(timeToPrepare);

// Print that the component is ready

System.out.println(componentName + " is ready.");

} catch (InterruptedException e) {

System.out.println(e);

// Main method to create threads and synchronize them using join()

public static void main(String[] args) {

// Create CarAssembly instances for Engine, Body, and Wheels

CarAssembly engineAssembly = new CarAssembly("Engine", 3000);

CarAssembly bodyAssembly = new CarAssembly("Body", 4000);

CarAssembly wheelAssembly = new CarAssembly("Wheels", 5000);

// Create threads for each component

Thread engineThread = new Thread(engineAssembly);


Thread bodyThread = new Thread(bodyAssembly);

Thread wheelThread = new Thread(wheelAssembly);

// Start the threads

engineThread.start();

bodyThread.start();

wheelThread.start();

try {

// Ensure that all threads finish before the main thread completes

engineThread.join();

bodyThread.join();

wheelThread.join();

} catch (InterruptedException e) {

System.out.println(e);

System.out.println("Car assembly is complete!");

12) Design a Java program to manage an ArrayList of integers that supports


dynamic insertion at any position, deletion, updating values, and efficiently
computing the sum of elements between two given indices after each modification.
Sample Input Sample Output

insert 0 5 [5]

insert 1 10 [5, 10]

insert 1 15 [5, 15, 10]

update 2 20 [5, 15, 20]

sum 0 2 25

delete 1 [5, 20]

sum 0 1 25

import java.util.*;

public class ArrayListManager {

private List<Integer> list;

public ArrayListManager() {
list = new ArrayList<>();
}

public void insert(int index, int value) {


list.add(index, value);
System.out.println(list);
}

public void update(int index, int value) {


if (index >= 0 && index < list.size()) {
list.set(index, value);
System.out.println(list);
} else {
System.out.println("Index out of bounds.");
}
}
public void delete(int index) {
if (index >= 0 && index < list.size()) {
list.remove(index);
System.out.println(list);
} else {
System.out.println("Index out of bounds.");
}
}

public void sum(int index1, int index2) {


if (index1 >= 0 && index1 < list.size() && index2 >= 0 && index2 < list.size())
{
int result = list.get(index1) + list.get(index2);
System.out.println(result);
} else {
System.out.println("Invalid indices.");
}
}

public static void main(String[] args) {


ArrayListManager manager = new ArrayListManager();

// Hardcoded operations
manager.insert(0, 5); // [5]
manager.insert(1, 10); // [5, 10]
manager.insert(1, 15); // [5, 15, 10]
manager.update(2, 20); // [5, 15, 20]
manager.sum(0, 2); // 5 + 20 = 25
manager.delete(1); // [5, 20]
manager.sum(0, 1); // 5 + 20 = 25
}
}

13) Write a Java program using HashMap to add, remove, and track the frequency
of words. You also need to find the most frequent word, and if there’s a tie, return
the smallest word alphabetically. The program should handle up to 10^5 operations
efficiently.
Sample Input Sample Output

add apple Frequency of 'apple': 1

add banana Most frequent word: banana

add apple

remove apple

query apple

mostFrequent

import java.util.*;

public class WordFrequency {

private static Map<String, Integer> wordCount = new HashMap<>();

// Add word
public static void add(String word) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}

// Remove word (reduce frequency or delete)


public static void remove(String word) {
if (wordCount.containsKey(word)) {
int freq = wordCount.get(word);
if (freq == 1) {
wordCount.remove(word);
} else {
wordCount.put(word, freq - 1);
}
}
}

// Query frequency of a word


public static void query(String word) {
int freq = wordCount.getOrDefault(word, 0);
System.out.println("Frequency of '" + word + "': " + freq);
}
// Print most frequent word (alphabetically smallest if tie)
public static void mostFrequent() {
String result = "";
int maxFreq = 0;

for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {


String word = entry.getKey();
int freq = entry.getValue();

if (freq > maxFreq || (freq == maxFreq && word.compareTo(result) < 0)) {


maxFreq = freq;
result = word;
}
}

if (!result.isEmpty()) {
System.out.println("Most frequent word: " + result);
} else {
System.out.println("No words available.");
}
}

public static void main(String[] args) {


// Sample Input (Hardcoded)
add("apple"); // apple: 1
add("banana"); // banana: 1
add("apple"); // apple: 2
remove("apple"); // apple: 1
query("apple"); // Frequency of 'apple': 1
mostFrequent(); // Most frequent word: banana
}
}

14) Design and implement a multi-threaded banking system in Java that simulates
multiple users performing concurrent transactions on shared bank accounts. Each
transaction can be a deposit, withdrawal, or transfer between accounts.

class BankAccount {
private String accountName;
private double balance;
public BankAccount(String name, double initialBalance) {
this.accountName = name;
this.balance = initialBalance;
}

public String getName() {


return accountName;
}

public synchronized void deposit(double amount) {


balance += amount;
System.out.println(accountName + " deposited: " + amount + " | Balance: " +
balance);
}

public synchronized void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
System.out.println(accountName + " withdrew: " + amount + " | Balance: "
+ balance);
} else {
System.out.println(accountName + " tried to withdraw " + amount + " but
insufficient funds.");
}
}

public void transfer(BankAccount toAccount, double amount) {


synchronized (this) {
if (amount <= balance) {
balance -= amount;
System.out.println(accountName + " transferring " + amount + " to " +
toAccount.getName());
} else {
System.out.println(accountName + " tried to transfer " + amount + " to "
+ toAccount.getName() + " but insufficient funds.");
return;
}
}
toAccount.deposit(amount);
}

public synchronized double getBalance() {


return balance;
}
}

class BankUser implements Runnable {


private BankAccount from;
private BankAccount to;
private int userId;

public BankUser(int userId, BankAccount from, BankAccount to) {


this.userId = userId;
this.from = from;
this.to = to;
}

@Override
public void run() {
System.out.println("User " + userId + " started transactions.");
from.deposit(1000);
from.withdraw(400);
from.transfer(to, 300);
System.out.println("User " + userId + " finished transactions.\n");
}
}

public class MultiThreadedBanking {


public static void main(String[] args) {
BankAccount accountA = new BankAccount("Alice", 2000);
BankAccount accountB = new BankAccount("Bob", 1500);

Thread user1 = new Thread(new BankUser(1, accountA, accountB));


Thread user2 = new Thread(new BankUser(2, accountB, accountA));
Thread user3 = new Thread(new BankUser(3, accountA, accountB));

user1.start();
user2.start();
user3.start();

try {
user1.join();
user2.join();
user3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final Balance of Alice: " + accountA.getBalance());
System.out.println("Final Balance of Bob: " + accountB.getBalance());
}
}

15)Design a shopping cart program where users can add items, apply discount
codes, and check out. Use custom exceptions to handle scenarios like invalid
coupon codes, out-of-stock items, and negative quantity inputs. (Exception
handling)

import java.util.*;

class InvalidCouponException extends Exception {


public InvalidCouponException(String msg) {
super(msg);
}
}

class OutOfStockException extends Exception {


public OutOfStockException(String msg) {
super(msg);
}
}

class NegativeQuantityException extends Exception {


public NegativeQuantityException(String msg) {
super(msg);
}
}

class Item {
String name;
double price;
int stock;

Item(String name, double price, int stock) {


this.name = name;
this.price = price;
this.stock = stock;
}
}

class CartItem {
Item item;
int quantity;

CartItem(Item item, int quantity) {


this.item = item;
this.quantity = quantity;
}
}

class ShoppingCart {
private List<Item> inventory = new ArrayList<>();
private List<CartItem> cart = new ArrayList<>();
private double discount = 0.0;

// Initialize inventory with predefined items


ShoppingCart() {
inventory.add(new Item("laptop", 50000, 5));
inventory.add(new Item("phone", 30000, 10));
inventory.add(new Item("mouse", 1000, 20));
}

// Add item to the shopping cart


public void addItem(String itemName, int quantity) throws OutOfStockException,
NegativeQuantityException {
if (quantity < 0) {
throw new NegativeQuantityException("Quantity cannot be negative.");
}

Item item = findItemInInventory(itemName);


if (item == null || item.stock < quantity) {
throw new OutOfStockException("Item out of stock or insufficient quantity
for: " + itemName);
}

cart.add(new CartItem(item, quantity));


item.stock -= quantity;
System.out.println(quantity + " x " + itemName + " added to cart.");
}

// Find item in inventory


private Item findItemInInventory(String itemName) {
for (Item item : inventory) {
if (item.name.equalsIgnoreCase(itemName)) {
return item;
}
}
return null;
}

// Apply discount coupon


public void applyCoupon(String code) throws InvalidCouponException {
switch (code.toUpperCase()) {
case "SAVE10": discount = 0.10; break;
case "SAVE20": discount = 0.20; break;
default: throw new InvalidCouponException("Invalid coupon code: " + code);
}
System.out.println("Coupon applied: " + code + " (" + (int)(discount * 100) +
"% off)");
}

// Checkout and display total


public void checkout() {
double total = 0;
System.out.println("\n--- Checkout ---");
for (CartItem cartItem : cart) {
double itemTotal = cartItem.item.price * cartItem.quantity;
System.out.println(cartItem.quantity + " x " + cartItem.item.name + " = ₹"
+ itemTotal);
total += itemTotal;
}
double finalTotal = total - (total * discount);
System.out.println("Discount: " + (discount * 100) + "%");
System.out.println("Total after discount: ₹" + finalTotal);
}
}

public class Main {


public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();

try {
cart.addItem("laptop", 1);
cart.addItem("mouse", 2);
cart.addItem("phone", 1);
cart.applyCoupon("SAVE10");
cart.checkout();
} catch (OutOfStockException | InvalidCouponException |
NegativeQuantityException e) {
System.out.println("Error: " + e.getMessage());
}

System.out.println("\n--- Trying invalid cases ---");

try {
cart.addItem("laptop", -1); // Negative quantity
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}

try {
cart.addItem("phone", 100); // Out of stock
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}

try {
cart.applyCoupon("FREE100"); // Invalid coupon
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}

16) Design an interface Vehicle with methods startRide(), endRide(), and


calculateFare(int distance). Implement classes like Bike, Auto, and Cab, where each
vehicle calculates fares differently. Use a PricingStrategy interface to dynamically
adjust fares based on conditions like peak hours and holidays.

// Vehicle Interface
interface Vehicle {
void startRide();
void endRide();
double calculateFare(int distance);
}

// PricingStrategy Interface
interface PricingStrategy {
double adjustFare(double baseFare);
}

// Bike class implementing Vehicle and PricingStrategy


class Bike implements Vehicle {
private PricingStrategy pricingStrategy;

// Constructor to inject pricing strategy


public Bike(PricingStrategy pricingStrategy) {
this.pricingStrategy = pricingStrategy;
}

@Override
public void startRide() {
System.out.println("Bike ride started.");
}

@Override
public void endRide() {
System.out.println("Bike ride ended.");
}

@Override
public double calculateFare(int distance) {
double baseFare = 5 + 2 * distance; // Base fare: 5 + 2 per km
System.out.println("Base fare for Bike ride: ₹" + baseFare);
return pricingStrategy.adjustFare(baseFare);
}
}

// Auto class implementing Vehicle and PricingStrategy


class Auto implements Vehicle {
private PricingStrategy pricingStrategy;

// Constructor to inject pricing strategy


public Auto(PricingStrategy pricingStrategy) {
this.pricingStrategy = pricingStrategy;
}

@Override
public void startRide() {
System.out.println("Auto ride started.");
}
@Override
public void endRide() {
System.out.println("Auto ride ended.");
}

@Override
public double calculateFare(int distance) {
double baseFare = 10 + 3 * distance; // Base fare: 10 + 3 per km
System.out.println("Base fare for Auto ride: ₹" + baseFare);
return pricingStrategy.adjustFare(baseFare);
}
}

// Cab class implementing Vehicle and PricingStrategy


class Cab implements Vehicle {
private PricingStrategy pricingStrategy;

// Constructor to inject pricing strategy


public Cab(PricingStrategy pricingStrategy) {
this.pricingStrategy = pricingStrategy;
}

@Override
public void startRide() {
System.out.println("Cab ride started.");
}

@Override
public void endRide() {
System.out.println("Cab ride ended.");
}

@Override
public double calculateFare(int distance) {
double baseFare = 20 + 5 * distance; // Base fare: 20 + 5 per km
System.out.println("Base fare for Cab ride: ₹" + baseFare);
return pricingStrategy.adjustFare(baseFare);
}
}

// PeakHourPricingStrategy class implements PricingStrategy to adjust fare for peak


hours
class PeakHourPricingStrategy implements PricingStrategy {
@Override
public double adjustFare(double baseFare) {
double adjustedFare = baseFare * 1.5; // 50% more for peak hours
System.out.println("Peak hours surcharge applied: 1.5x");
return adjustedFare;
}
}

// HolidayPricingStrategy class implements PricingStrategy to adjust fare for


holidays
class HolidayPricingStrategy implements PricingStrategy {
@Override
public double adjustFare(double baseFare) {
double adjustedFare = baseFare * 2; // Double fare on holidays
System.out.println("Holiday surcharge applied: 2x");
return adjustedFare;
}
}

// RegularPricingStrategy class implements PricingStrategy for normal fare


calculations
class RegularPricingStrategy implements PricingStrategy {
@Override
public double adjustFare(double baseFare) {
System.out.println("No additional surcharge.");
return baseFare; // No additional surcharge
}
}

// Main Class for testing


public class VehicleRideSystem {
public static void main(String[] args) {
// Create different pricing strategies
PricingStrategy regular = new RegularPricingStrategy();
PricingStrategy peakHour = new PeakHourPricingStrategy();
PricingStrategy holiday = new HolidayPricingStrategy();

// Create vehicles with different pricing strategies


Vehicle bike = new Bike(regular);
Vehicle auto = new Auto(peakHour);
Vehicle cab = new Cab(holiday);

// Simulate rides
System.out.println("\nBike ride for 10 km:");
bike.startRide();
double bikeFare = bike.calculateFare(10);
System.out.println("Total fare: ₹" + bikeFare);
bike.endRide();

System.out.println("\nAuto ride for 15 km:");


auto.startRide();
double autoFare = auto.calculateFare(15);
System.out.println("Total fare: ₹" + autoFare);
auto.endRide();

System.out.println("\nCab ride for 20 km:");


cab.startRide();
double cabFare = cab.calculateFare(20);
System.out.println("Total fare: ₹" + cabFare);
cab.endRide();
}
}

17) Design a University Staff Management System using a base class Staff and
derived classes Professor, AdministrativeStaff, and MaintenanceStaff.
Override methods like displayDetails() and calculateBonus() differently in each
subclass using polymorphism.
Use a list of base class pointers or references to manage multiple staff objects and
demonstrate runtime polymorphism.
(Advanced) Implement a promote() method with different behaviors in each
subclass.

import java.util.ArrayList;
import java.util.List;

// Base class: Staff


class Staff {
protected String name;
protected String id;
protected double salary;

public Staff(String name, String id, double salary) {


this.name = name;
this.id = id;
this.salary = salary;
}

// Method to display details (to be overridden by subclasses)


public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("ID: " + id);
System.out.println("Salary: ₹" + salary);
}

// Method to calculate bonus (to be overridden by subclasses)


public double calculateBonus() {
return 0; // Base class will not calculate bonus
}

// Method to promote staff (to be overridden by subclasses)


public void promote() {
System.out.println(name + " has been promoted!");
}
}

// Derived class: Professor


class Professor extends Staff {
private String department;

public Professor(String name, String id, double salary, String department) {


super(name, id, salary);
this.department = department;
}

@Override
public void displayDetails() {
super.displayDetails();
System.out.println("Department: " + department);
}

@Override
public double calculateBonus() {
return salary * 0.20; // Professors get a 20% bonus
}

@Override
public void promote() {
System.out.println(name + " has been promoted to Senior Professor!");
}
}

// Derived class: AdministrativeStaff


class AdministrativeStaff extends Staff {
private String department;

public AdministrativeStaff(String name, String id, double salary, String


department) {
super(name, id, salary);
this.department = department;
}

@Override
public void displayDetails() {
super.displayDetails();
System.out.println("Department: " + department);
}

@Override
public double calculateBonus() {
return salary * 0.10; // Administrative staff get a 10% bonus
}

@Override
public void promote() {
System.out.println(name + " has been promoted to Senior Administrative
Staff!");
}
}

// Derived class: MaintenanceStaff


class MaintenanceStaff extends Staff {
private String shift;

public MaintenanceStaff(String name, String id, double salary, String shift) {


super(name, id, salary);
this.shift = shift;
}

@Override
public void displayDetails() {
super.displayDetails();
System.out.println("Shift: " + shift);
}

@Override
public double calculateBonus() {
return salary * 0.05; // Maintenance staff get a 5% bonus
}

@Override
public void promote() {
System.out.println(name + " has been promoted to Senior Maintenance
Staff!");
}
}

public class UniversityStaffManagementSystem {


public static void main(String[] args) {
// Create staff objects of different types
Staff professor = new Professor("Dr. John", "P001", 75000, "Computer
Science");
Staff adminStaff = new AdministrativeStaff("Alice", "A001", 40000,
"Administration");
Staff maintenanceStaff = new MaintenanceStaff("Bob", "M001", 25000,
"Night");

// Create a list of Staff objects (base class references)


List<Staff> staffList = new ArrayList<>();
staffList.add(professor);
staffList.add(adminStaff);
staffList.add(maintenanceStaff);

// Demonstrate polymorphism: Display details and calculate bonus for each


staff
System.out.println("Staff Details and Bonuses:");
for (Staff staff : staffList) {
staff.displayDetails();
System.out.println("Bonus: ₹" + staff.calculateBonus());
System.out.println("-----------------------------");
}

// Demonstrate polymorphism: Promote each staff


System.out.println("Promoting Staff:");
for (Staff staff : staffList) {
staff.promote();
}
}
}

18)
1. Create a class Rectangle with attributes length and breadth. Write a
constructor that uses this keyword to initialize the attributes. Also, create a
method compareArea(Rectangle r) that compares the area of two rectangles.
2. Create a class MathOperations with:
● A static method square(int n) that returns the square of a number.
● An instance method cube(int n) that returns the cube of a number.
Write a Java program that demonstrates calling both static and
instance methods properly.

// Rectangle.java
class Rectangle {
private int length;
private int breadth;

// Constructor using 'this' keyword


public Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}

// Method to calculate area


public int area() {
return length * breadth;
}

// Method to compare area with another rectangle


public void compareArea(Rectangle r) {
int thisArea = this.area();
int otherArea = r.area();

System.out.println("Area of current rectangle: " + thisArea);


System.out.println("Area of passed rectangle: " + otherArea);

if (thisArea > otherArea) {


System.out.println("Current rectangle has a larger area.");
} else if (thisArea < otherArea) {
System.out.println("Passed rectangle has a larger area.");
} else {
System.out.println("Both rectangles have the same area.");
}
}
}
// MathOperations.java
class MathOperations {
// Static method to return square of a number
public static int square(int n) {
return n * n;
}

// Instance method to return cube of a number


public int cube(int n) {
return n * n * n;
}
}
// Main.java
public class Main {
public static void main(String[] args) {
// Part 1: Rectangle Area Comparison
Rectangle r1 = new Rectangle(5, 4); // Area = 20
Rectangle r2 = new Rectangle(6, 3); // Area = 18

System.out.println(" Rectangle Comparison ");


r1.compareArea(r2);

// Part 2: Math Operations


int num = 3;
System.out.println("Math Operations: ");

// Calling static method


int sq = MathOperations.square(num);
System.out.println("Square of " + num + " is: " + sq);

// Calling instance method


MathOperations mathOps = new MathOperations();
int cb = mathOps.cube(num);
System.out.println("Cube of " + num + " is: " + cb);
}
}

19) Create a Java program for a seating system in a cinema hall


represented by a 2D array (rows × columns).
● Mark all seats as available (e.g., 0) initially.

● Allow the user to book seats by marking them as booked (e.g., 1).

● Display the current seat map (matrix form).

● Add functionality to check if a given seat is available before booking.


public class CinemaSeating {

public static void main(String[] args) {

int rows = 5;

int cols = 5;

int[][] seats = new int[rows][cols]; // 0 = available, 1 = booked

// Booked seats (hardcoded)

int[][] bookings = {

{0, 0},

{1, 1},

{2, 2},

{1, 1}, // Duplicate booking, should be skipped

{3, 4}

};

// Booking logic

for (int[] booking : bookings) {

int r = booking[0];

int c = booking[1];

if (seats[r][c] == 0) {

seats[r][c] = 1;

System.out.println("Seat booked at [" + r + "][" + c + "]");

} else {
System.out.println("Seat already booked at [" + r + "][" + c + "]");

// Display seat map

System.out.println("\nSeat Map (0 = Available, 1 = Booked):");

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

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

System.out.println();

20)

Develop a Java program that takes a paragraph input from the user and:
● Remove all vowels (a, e, i, o, u) from the paragraph using
StringBuilder.

● Efficiently update the paragraph after each deletion.

● Finally, display the transformed paragraph along with the count of


characters removed.

public class RemoveVowelsHardcoded {


public static void main(String[] args) {
String paragraph = "Artificial intelligence is transforming the world.";
StringBuilder result = new StringBuilder();
int removedCount = 0;

for (int i = 0; i < paragraph.length(); i++) {


char ch = paragraph.charAt(i);
if (!isVowel(ch)) {
result.append(ch); // keep character
} else {
removedCount++; // count vowels
}
}

System.out.println("Original Paragraph:\n" + paragraph);


System.out.println("\nTransformed Paragraph (without vowels):");
System.out.println(result);
System.out.println("\nTotal vowels removed: " + removedCount);
}

// Helper method to check for vowels (case-insensitive)


public static boolean isVowel(char ch) {
ch = Character.toLowerCase(ch);
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
}

21) Create a base class `Employee` with attributes: name, id, and
basicSalary, along with methods `displayDetails()` and
`calculateSalary()`. Derive two subclasses: `Manager` with an additional
bonus attribute and `Developer` with a projectAllowance attribute.
Override the `calculateSalary()` method in both subclasses to include
their respective additional amounts. In the main method, create objects of
Manager and Developer, and call `displayDetails()` for each.
Demonstrate polymorphism by invoking `calculateSalary()` using base
class references and display the total salary.

// Base class

class Employee {

String name;

int id;

double basicSalary;
// Constructor

public Employee(String name, int id, double basicSalary) {

this.name = name;

this.id = id;

this.basicSalary = basicSalary;

// Method to display employee details

public void displayDetails() {

System.out.println("Name: " + name);

System.out.println("ID: " + id);

System.out.println("Basic Salary: " + basicSalary);

// Method to calculate salary (to be overridden)

public double calculateSalary() {

return basicSalary;

// Subclass: Manager

class Manager extends Employee {

double bonus;
public Manager(String name, int id, double basicSalary, double bonus) {

super(name, id, basicSalary);

this.bonus = bonus;

@Override

public double calculateSalary() {

return basicSalary + bonus;

@Override

public void displayDetails() {

super.displayDetails();

System.out.println("Bonus: " + bonus);

// Subclass: Developer

class Developer extends Employee {

double projectAllowance;

public Developer(String name, int id, double basicSalary, double


projectAllowance) {

super(name, id, basicSalary);


this.projectAllowance = projectAllowance;

@Override

public double calculateSalary() {

return basicSalary + projectAllowance;

@Override

public void displayDetails() {

super.displayDetails();

System.out.println("Project Allowance: " + projectAllowance);

// Main class to test the program

public class EmployeeTest {

public static void main(String[] args) {

// Creating Manager and Developer objects

Employee emp1 = new Manager("Alice", 101, 50000, 10000);

Employee emp2 = new Developer("Bob", 102, 45000, 8000);

// Displaying details and salary using polymorphism

System.out.println("Manager Details:");
emp1.displayDetails();

System.out.println("Total Salary: " + emp1.calculateSalary());

System.out.println("\nDeveloper Details:");

emp2.displayDetails();

System.out.println("Total Salary: " + emp2.calculateSalary());

22) Create a class BankAccount with the following attributes and methods:

Attributes:

accountNumber (String)

balance (double)

Methods:

A constructor that initializes the accountNumber and balance.

A method withdraw(double amount) that:

Throws an ArithmeticException if the withdrawal amount is greater


than the current balance.

Throws an IllegalArgumentException if the withdrawal amount is


less than or equal to zero.

In the main() method:

Create an object of the BankAccount class with an initial balance.

Use try-catch blocks to handle the following scenarios:

Catch the ArithmeticException and display a message "Insufficient funds


for withdrawal."

Catch the IllegalArgumentException and display a message "Invalid


withdrawal amount."
After handling the exception, allow the program to continue running.

Display the current balance after each operation.

class BankAccount {

private String accountNumber;

private double balance;

// Constructor

public BankAccount(String accountNumber, double balance) {

this.accountNumber = accountNumber;

this.balance = balance;

// Withdraw method with exception handling

public void withdraw(double amount) {

if (amount <= 0) {

throw new IllegalArgumentException("Withdrawal amount must be


greater than zero.");

if (amount > balance) {

throw new ArithmeticException("Not enough balance.");

balance -= amount;

System.out.println("Withdrawal of " + amount + " successful.");

}
// Method to get current balance

public double getBalance() {

return balance;

public class BankAccountTest {

public static void main(String[] args) {

BankAccount myAccount = new BankAccount("ACC123", 1000.0);

// Withdrawal attempts

double[] withdrawals = {200.0, -50.0, 1000.0, 300.0};

for (double amount : withdrawals) {

try {

System.out.println("\nAttempting to withdraw: " + amount);

myAccount.withdraw(amount);

} catch (ArithmeticException ae) {

System.out.println("Insufficient funds for withdrawal.");

} catch (IllegalArgumentException iae) {

System.out.println("Invalid withdrawal amount.");

System.out.println("Current Balance: " + myAccount.getBalance());


}

23)Create a class Printer with a method printNumbers() that prints the numbers
from 1 to 10 with a small delay between each number (use Thread.sleep(500) to
simulate the delay).

Create two threads:

One thread will call the printNumbers() method and print numbers from 1 to 10.

The second thread will call the printNumbers() method and also print numbers
from 1 to 10.

In the main() method:

Create two Printer objects.

Create two threads and start them to execute the printNumbers() method
concurrently.

Ensure that the numbers from both threads are printed without any interruption.

● Additional attribute: department (String)

class Printer {

private String department;

public Printer(String department) {

this.department = department;

// Synchronized to ensure clean output per thread

public synchronized void printNumbers() {

for (int i = 1; i <= 10; i++) {


System.out.println(department + " prints: " + i);

try {

Thread.sleep(500); // Simulate delay

} catch (InterruptedException e) {

System.out.println("Thread interrupted.");

// Runnable implementation for thread task

class PrintTask implements Runnable {

private Printer printer;

public PrintTask(Printer printer) {

this.printer = printer;

@Override

public void run() {

printer.printNumbers();

public class PrinterTest {

public static void main(String[] args) {


Printer dept1Printer = new Printer("HR");

Printer dept2Printer = new Printer("IT");

Thread thread1 = new Thread(new PrintTask(dept1Printer));

Thread thread2 = new Thread(new PrintTask(dept2Printer));

thread1.start();

thread2.start();

24) Create a Java program to demonstrate access modifiers (private, public,


protected, and default).

1. Class Person:

○ Attributes:

■ name (private), age (public), address (protected), phoneNumber


(default)

○ Methods:

■ Constructor to initialize all attributes.

■ displayDetails() (public) to display name, age, and address.

■ updatePhoneNumber() (public) to update phoneNumber.

2. Class Employee (extends Person):

○ Additional attribute: employeeId (public)

○ Override displayDetails() to include employeeId.

3. In the main() method:


○ Create an Employee object and demonstrate access to attributes and
methods using different access modifiers.

// Class Person

class Person {

private String name; // private: accessible only within Person

public int age; // public: accessible anywhere

protected String address; // protected: accessible in subclass or same package

String phoneNumber; // default: accessible in same package

// Constructor to initialize attributes

public Person(String name, int age, String address, String phoneNumber) {

this.name = name;

this.age = age;

this.address = address;

this.phoneNumber = phoneNumber;

// Public method to display details

public void displayDetails() {

System.out.println("Name: " + name); // accessing private attribute inside the


class

System.out.println("Age: " + age);

System.out.println("Address: " + address);

}
// Public method to update default access attribute

public void updatePhoneNumber(String newNumber) {

this.phoneNumber = newNumber;

System.out.println("Phone number updated to: " + phoneNumber);

// Class Employee extends Person

class Employee extends Person {

public String employeeId; // public attribute

// Constructor to initialize everything

public Employee(String name, int age, String address, String phoneNumber,


String employeeId) {

super(name, age, address, phoneNumber); // Call to Person constructor

this.employeeId = employeeId;

// Overriding displayDetails

@Override

public void displayDetails() {

super.displayDetails(); // call Person's displayDetails

System.out.println("Employee ID: " + employeeId);

}
}

// Main class

public class AccessModifierDemo {

public static void main(String[] args) {

Employee emp = new Employee("Alice", 30, "123 Main St", "9876543210",


"EMP001");

// Call public method to display details

emp.displayDetails();

// Accessing public attribute

emp.age = 35;

System.out.println("Updated Age: " + emp.age);

// Calling method to update default attribute

emp.updatePhoneNumber("9999999999");

// Accessing protected attribute directly (within same package)

System.out.println("Address (protected): " + emp.address);

// Accessing default attribute directly (same package)

System.out.println("Phone Number (default): " + emp.phoneNumber);


// ❌ Can't access private attribute `name` directly — this line would cause an
error:

// System.out.println(emp.name); // Uncommenting this line will cause a


compile error

25)

1) Create an application for employee management with the following


classes:

a) Create an Employee class with following attributes and behaviors:

i) int empId
ii) String empName
iii) String email
iv) String gender
v) float salary
vi) void GetEmployeeDetails() -> prints employee details

b) Create one more class EmployeeDB with the following attributes and
behaviors:
i) ArrayList list;
ii) boolean addEmployee(Employee e) -> adds the employee object to the
collection
iii) boolean deleteEmployee(int empId) -> delete the employee object from
the collection with the given empid
iv) String showPaySlip(int empId) -> returns the payslip of the employee with
the given empId
import java.util.ArrayList;

// Class to represent an Employee

class Employee {

int empId;

String empName;
String email;

String gender;

float salary;

// Constructor to initialize Employee attributes

public Employee(int empId, String empName, String email, String gender,


float salary) {

this.empId = empId;

this.empName = empName;

this.email = email;

this.gender = gender;

this.salary = salary;

// Method to print employee details

public void GetEmployeeDetails() {

System.out.println("Employee ID: " + empId);

System.out.println("Employee Name: " + empName);

System.out.println("Email: " + email);

System.out.println("Gender: " + gender);

System.out.println("Salary: " + salary);

// Class to represent EmployeeDB


class EmployeeDB {

private ArrayList<Employee> list;

// Constructor to initialize the list

public EmployeeDB() {

list = new ArrayList<>();

// Method to add an employee to the list

public boolean addEmployee(Employee e) {

return list.add(e);

// Method to delete an employee from the list using empId

public boolean deleteEmployee(int empId) {

for (Employee e : list) {

if (e.empId == empId) {

list.remove(e);

return true;

return false;

}
// Method to show payslip for an employee with given empId

public String showPaySlip(int empId) {

for (Employee e : list) {

if (e.empId == empId) {

return "Payslip for " + e.empName + ":\n" +

"Employee ID: " + e.empId + "\n" +

"Salary: " + e.salary;

return "Employee not found!";

public class EmployeeManagementApp {

public static void main(String[] args) {

// Creating Employee objects

Employee emp1 = new Employee(101, "Alice", "[email protected]",


"Female", 50000f);

Employee emp2 = new Employee(102, "Bob", "[email protected]",


"Male", 60000f);

// Creating EmployeeDB object to manage employees

EmployeeDB employeeDB = new EmployeeDB();

// Adding employees to the database


employeeDB.addEmployee(emp1);

employeeDB.addEmployee(emp2);

// Displaying details of employees

System.out.println("Employee Details:");

emp1.GetEmployeeDetails();

emp2.GetEmployeeDetails();

// Show payslip for an employee

System.out.println("\n" + employeeDB.showPaySlip(101));

// Deleting an employee

System.out.println("\nDeleting employee with ID 102:");

employeeDB.deleteEmployee(102);

// Trying to show payslip for deleted employee

System.out.println("\n" + employeeDB.showPaySlip(102));

// Display remaining employee details

System.out.println("\nRemaining Employee Details:");

emp1.GetEmployeeDetails();

}
26)

You are given a sorted integer array nums in non-decreasing order. Your task
is to remove the duplicate elements in-place such that each element appears
only once, and return the new length of the modified array.

You must not allocate extra space for another array; you must do this by
modifying the input array in-place with O(1) extra memory.

After removing the duplicates, the first part of the array should contain the
unique elements, and the remaining elements can be left as any value
(underscores _ or any arbitrary values).

public class RemoveDuplicates {

public static void main(String[] args) {

// Hardcoded input array

int[] nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};

// Logic to remove duplicates

int i = 0; // Pointer for the last unique element position

// Traverse the array starting from the second element

for (int j = 1; j < nums.length; j++) {

if (nums[j] != nums[i]) {

i++; // Move the pointer for unique elements

nums[i] = nums[j]; // Place the current element in the correct


position

// The new length of the array is i + 1


int newLength = i + 1;

// Output the results

System.out.println("New length: " + newLength);

System.out.print("Modified array: ");

for (int j = 0; j < newLength; j++) {

System.out.print(nums[j] + " ");

Example:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]

27)

Write a class MathOperation which accepts 5 integers through the command


line.
Create an array using these parameters.
Loop through the array and obtain the sum and average of all the elements
and display the result.

Handle various exceptions that may arise such as:

● ArithmeticException

● NumberFormatException

● and other relevant exceptions.


public class MathOperation {

public static void main(String[] args) {

// Check if 5 arguments are provided

if (args.length != 5) {

System.out.println("Error: Please provide exactly 5 integers as command


line arguments.");

return;

// Declare an array to store the integers

int[] numbers = new int[5];

int sum = 0;

double average = 0;

try {

// Loop through the arguments and parse the integers

for (int i = 0; i < args.length; i++) {

numbers[i] = Integer.parseInt(args[i]);

sum += numbers[i];

// Calculate the average

if (args.length > 0) {

average = (double) sum / args.length;

}
// Display the results

System.out.println("Sum: " + sum);

System.out.println("Average: " + average);

} catch (NumberFormatException e) {

System.out.println("Error: Invalid number format. Please provide valid


integers.");

} catch (ArithmeticException e) {

System.out.println("Error: Arithmetic error occurred while calculating the


average.");

} catch (Exception e) {

System.out.println("An unexpected error occurred: " + e.getMessage());

28)

Create a base class named Fruit with the following attributes:

● name (String)

● taste (String)

● size (String)

Define a method eat() in the Fruit class that prints the name and taste of the
fruit.

Now, create two subclasses, Apple and Orange, that inherit from the Fruit
class.
Override the eat() method in each subclass to display the specific taste of
that fruit.
// Base class Fruit

class Fruit {

// Attributes of the Fruit class

String name;

String taste;

String size;

// Constructor to initialize Fruit attributes

public Fruit(String name, String taste, String size) {

this.name = name;

this.taste = taste;

this.size = size;

// Method to display the name and taste of the fruit

public void eat() {

System.out.println("Eating a " + name + ". It tastes " + taste + ".");

// Subclass Apple that inherits from Fruit

class Apple extends Fruit {

// Constructor for Apple


public Apple(String name, String taste, String size) {

super(name, taste, size);

// Overriding eat() method to provide specific behavior for Apple

@Override

public void eat() {

System.out.println("Eating an Apple. It tastes " + taste + ".");

// Subclass Orange that inherits from Fruit

class Orange extends Fruit {

// Constructor for Orange

public Orange(String name, String taste, String size) {

super(name, taste, size);

// Overriding eat() method to provide specific behavior for Orange

@Override

public void eat() {

System.out.println("Eating an Orange. It tastes " + taste + ".");

}
}

// Main class to test the functionality

public class FruitTest {

public static void main(String[] args) {

// Creating objects of Apple and Orange

Fruit apple = new Apple("Apple", "sweet", "medium");

Fruit orange = new Orange("Orange", "tangy", "large");

// Calling the eat() method on both objects

apple.eat();

orange.eat();

29)
Given a number N, the task is to count the number of unique digits in the
given number.
Examples:

Input: N = 22342 Output: 2

Explanation: The digits 3 and 4 occurs only once. Hence, the output is 2.

Input: N = 99677 Output: 1


Explanation: The digit 6 occurs only once. Hence, the output is 1.
public class UniqueDigits {

public static int countUniqueDigits(int N) {


// Convert the number to string to easily iterate through digits

String numStr = String.valueOf(N);

// Create an array to store the frequency of each digit (0-9)

int[] digitCount = new int[10];

// Count the frequency of each digit

for (char digit : numStr.toCharArray()) {

digitCount[digit - '0']++; // Update frequency of the digit

// Count how many digits have a frequency of 1 (unique digits)

int uniqueDigitCount = 0;

for (int count : digitCount) {

if (count == 1) {

uniqueDigitCount++;
}

return uniqueDigitCount;

public static void main(String[] args) {

// Example 1

int N1 = 22342;

System.out.println("Input: " + N1 + " => Output: " +


countUniqueDigits(N1));

// Example 2

int N2 = 99677;

System.out.println("Input: " + N2 + " => Output: " +


countUniqueDigits(N2));

}
}

30)

Given an array of positive integers nums and a positive integer target, return
the minimal length of a subarray whose sum is greater than or equal to
target. If there is no such subarray, return 0 instead.

Example 1: Input: target = 7, nums = [2,3,1,2,4,3] Output: 2

Example 2: Input: target = 11, nums = [1,1,1,1,1,1,1,1] Output:0

public class MinSubarrayLength {

public static int minSubArrayLen(int target, int[] nums) {

int n = nums.length;

int minLength = Integer.MAX_VALUE; // Start with a large number

int sum = 0; // To store the sum of the current window

int left = 0; // Left pointer of the window

// Iterate with the right pointer

for (int right = 0; right < n; right++) {


sum += nums[right]; // Add the current number to the sum

// Once the sum is >= target, try to shrink the window

while (sum >= target) {

minLength = Math.min(minLength, right - left + 1); // Update the


min length

sum -= nums[left]; // Remove the leftmost element from the sum

left++; // Shrink the window from the left

// If no valid subarray is found, return 0

return minLength == Integer.MAX_VALUE ? 0 : minLength;

public static void main(String[] args) {


// Example 1

int target1 = 7;

int[] nums1 = {2, 3, 1, 2, 4, 3};

System.out.println("Example 1: " + minSubArrayLen(target1,


nums1)); // Output: 2

// Example 2

int target2 = 11;

int[] nums2 = {1, 1, 1, 1, 1, 1, 1, 1};

System.out.println("Example 2: " + minSubArrayLen(target2,


nums2)); // Output: 0

31)
Write a Java program to receive an integer number as a command-line
argument, and print the binary, octal, and hexadecimal equivalents of the
given number.

Given Number : 20
Binary equivalent : 10100
Octal equivalent : 24
Hexadecimal equivalent : 14
public class NumberConversion {
public static void main(String[] args) {
// Hardcoded number
int number = 20;

// Print the binary, octal, and hexadecimal equivalents


System.out.println("Given Number: " + number);
System.out.println("Binary equivalent: " +
Integer.toBinaryString(number));
System.out.println("Octal equivalent: " +
Integer.toOctalString(number));
System.out.println("Hexadecimal equivalent: " +
Integer.toHexString(number).toUpperCase());
}
}

32) Develop an online payment system that supports different payment methods.

Requirements:

1. Create an abstract class Payment with:


○ Attributes: amount, transactionID.
○ Abstract method processPayment().
○ Concrete method showTransactionDetails().
2. Create subclasses:
○ CreditCardPayment (cardNumber, CVV, expiryDate).
○ PayPalPayment (email, password).
○ UPIPayment (UPI ID).
3. Implement the processPayment() method in each subclass to handle
payments uniquely.
4. Create a PaymentGateway class to process transactions dynamically.

// Abstract class Payment

abstract class Payment {

protected double amount;

protected String transactionID;


// Constructor to initialize the payment attributes

public Payment(double amount, String transactionID) {

this.amount = amount;

this.transactionID = transactionID;

// Abstract method to process the payment (to be implemented by


subclasses)

public abstract void processPayment();

// Concrete method to display transaction details

public void showTransactionDetails() {

System.out.println("Transaction ID: " + transactionID);

System.out.println("Amount: $" + amount);

// CreditCardPayment class extends Payment

class CreditCardPayment extends Payment {

private String cardNumber;

private String CVV;

private String expiryDate;

// Constructor to initialize CreditCardPayment attributes


public CreditCardPayment(double amount, String transactionID, String
cardNumber, String CVV, String expiryDate) {

super(amount, transactionID);

this.cardNumber = cardNumber;

this.CVV = CVV;

this.expiryDate = expiryDate;

// Implement processPayment method for CreditCardPayment

@Override

public void processPayment() {

System.out.println("Processing Credit Card payment...");

System.out.println("Card Number: " + cardNumber);

System.out.println("Expiry Date: " + expiryDate);

// Simulate payment processing

System.out.println("Payment of $" + amount + " has been processed


successfully.");

// PayPalPayment class extends Payment

class PayPalPayment extends Payment {

private String email;

private String password;


// Constructor to initialize PayPalPayment attributes

public PayPalPayment(double amount, String transactionID, String email,


String password) {

super(amount, transactionID);

this.email = email;

this.password = password;

// Implement processPayment method for PayPalPayment

@Override

public void processPayment() {

System.out.println("Processing PayPal payment...");

System.out.println("Email: " + email);

// Simulate payment processing

System.out.println("Payment of $" + amount + " has been processed


successfully.");

// UPIPayment class extends Payment

class UPIPayment extends Payment {

private String upiID;

// Constructor to initialize UPIPayment attributes

public UPIPayment(double amount, String transactionID, String upiID) {


super(amount, transactionID);

this.upiID = upiID;

// Implement processPayment method for UPIPayment

@Override

public void processPayment() {

System.out.println("Processing UPI payment...");

System.out.println("UPI ID: " + upiID);

// Simulate payment processing

System.out.println("Payment of $" + amount + " has been processed


successfully.");

// PaymentGateway class to manage payments

class PaymentGateway {

public void processTransaction(Payment payment) {

// Process the payment dynamically using polymorphism

payment.processPayment();

payment.showTransactionDetails();

// Main class to demonstrate the payment system


public class Main {

public static void main(String[] args) {

// Create different payment method objects

Payment creditCardPayment = new CreditCardPayment(150.0,


"TXN12345", "1234-5678-9876-5432", "123", "12/23");

Payment payPalPayment = new PayPalPayment(200.0, "TXN12346",


"[email protected]", "securepassword");

Payment upiPayment = new UPIPayment(50.0, "TXN12347",


"user@upi");

// Create PaymentGateway object to process transactions

PaymentGateway paymentGateway = new PaymentGateway();

// Process payments using the PaymentGateway

System.out.println("Processing Credit Card Payment:");

paymentGateway.processTransaction(creditCardPayment);

System.out.println("\nProcessing PayPal Payment:");

paymentGateway.processTransaction(payPalPayment);

System.out.println("\nProcessing UPI Payment:");

paymentGateway.processTransaction(upiPayment);

33) Design a simple system to calculate the area of different 2D shapes using
interfaces in Java.
Define an interface named Shape with a method:
Create the following classes that implement the Shape interface:

● Circle with a field radius

● Rectangle with fields length and width

● Triangle with fields base and height

Each class must implement the calculateArea() method according to the respective
formula:

● Circle: π × radius²

● Rectangle: length × width

● Triangle: 0.5 × base × height

In the main() method, use polymorphism to create an array of Shape references and
call calculateArea() on each.

// Shape Interface
interface Shape {
double calculateArea(); // Abstract method to calculate the area of the shape
}

// Circle class implementing Shape interface


class Circle implements Shape {
private double radius;

// Constructor to initialize radius


public Circle(double radius) {
this.radius = radius;
}

// Implementing the calculateArea() method for Circle


@Override
public double calculateArea() {
return Math.PI * radius * radius; // Area = π * radius²
}
}

// Rectangle class implementing Shape interface


class Rectangle implements Shape {
private double length;
private double width;

// Constructor to initialize length and width


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Implementing the calculateArea() method for Rectangle


@Override
public double calculateArea() {
return length * width; // Area = length * width
}
}

// Triangle class implementing Shape interface


class Triangle implements Shape {
private double base;
private double height;

// Constructor to initialize base and height


public Triangle(double base, double height) {
this.base = base;
this.height = height;
}

// Implementing the calculateArea() method for Triangle


@Override
public double calculateArea() {
return 0.5 * base * height; // Area = 0.5 * base * height
}
}

// Main class to demonstrate polymorphism and calculate areas


public class ShapeAreaCalculator {
public static void main(String[] args) {
// Create an array of Shape references and instantiate different shape objects
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(5.0); // Circle with radius 5
shapes[1] = new Rectangle(4.0, 6.0); // Rectangle with length 4 and width 6
shapes[2] = new Triangle(4.0, 5.0); // Triangle with base 4 and height 5

// Loop through each shape in the array and calculate its area using
polymorphism
for (Shape shape : shapes) {
System.out.println("Area of " + shape.getClass().getSimpleName() + ": " +
shape.calculateArea());
}
}
}

34). simple banking system that handles user withdrawals, including proper use of
exception handling and custom exceptions.
Requirements:
1. Create a class BankAccount with the following:

○ Field: double balance

○ Constructor to initialize balance

○ Method:

If the withdrawal amount is greater than the balance, throw a custom


exception named InsufficientFundsException.

○ Otherwise, deduct the amount from the balance.

2. Define a custom exception class:


● Include a constructor that accepts a custom error message.

In the main() method:

● Create a BankAccount object with an initial balance.

● Try to withdraw different amounts (some valid, some invalid).

● Catch the exception and display appropriate error messages.

// Custom Exception Class


class InsufficientFundsException extends Exception {
// Constructor to accept a custom error message
public InsufficientFundsException(String message) {
super(message); // Passing the message to the superclass (Exception)
}
}

// BankAccount Class
class BankAccount {
private double balance;

// Constructor to initialize the balance


public BankAccount(double balance) {
this.balance = balance;
}

// Method to withdraw money from the account


public void withdraw(double amount) throws InsufficientFundsException {
// If withdrawal amount is greater than balance, throw the custom
exception
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds for
withdrawal. Balance: " + balance);
}
// Deduct the amount from balance if there are sufficient funds
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + balance);
}

// Getter for balance (optional, for displaying the balance)


public double getBalance() {
return balance;
}
}

// Main class to test the banking system


public class BankingSystem {
public static void main(String[] args) {
// Create a BankAccount object with an initial balance of 1000
BankAccount account = new BankAccount(1000);

// Try to withdraw different amounts


try {
// Valid withdrawal
account.withdraw(500); // Should be successful
// Invalid withdrawal (insufficient funds)
account.withdraw(600); // Should throw exception
} catch (InsufficientFundsException e) {
// Catch the custom exception and display the error message
System.out.println(e.getMessage());
}

// Try another withdrawal after handling the exception


try {
// Valid withdrawal again after handling the first exception
account.withdraw(200); // Should be successful
} catch (InsufficientFundsException e) {
// Catch the custom exception and display the error message
System.out.println(e.getMessage());
}
}
}

35)
The Citizen class should have following attributes name, id, country, sex,
maritalStatus, anualIncome, and economyStatus. Validate the fields if the age is
below 18 and country is not ‘India’ throw NonEligibleException and give
proper message. Use toString method to display the citizen object in
proper format. Use separate packages for Exception and application classes
36)
A. Write a Java program to remove prime numbers between 1 to 25 from ArrayList
using an iterator.
B. Write a Java program to
a. create and traverse (or iterate) ArrayList using for-loop, iterator,
and advance for-loop.
b. check if element(value) exists in ArrayList?
c. add element at particular index of ArrayList?

same as 8

37).

Write a Java program that handles various types of exceptions while performing
different operations. The application should read data from a file specified by the
user, handling potential `FileNotFoundException` and `IOException`. It should also
allow the user to input values for arithmetic operations and handle division by zero
using `ArithmeticException`. Additionally, implement exception handling for
`InputMismatchException` when the user provides invalid input,
`ArrayIndexOutOfBoundsException` for accessing invalid indices in arrays, and
`NullPointerException` when performing operations on `null` values. The program
should provide user-friendly error messages and ensure smooth execution even
when exceptions occur.

import java.io.*;

public class ExceptionHandlingHardcoded {

public static void main(String[] args) {

// 1. File Reading (FileNotFoundException and IOException)

String fileName = "nonexistent_file.txt";

try {

BufferedReader br = new BufferedReader(new FileReader(fileName));

String line;

System.out.println("Reading file:");

while ((line = br.readLine()) != null) {


System.out.println(line);

br.close();

} catch (FileNotFoundException e) {

System.out.println("FileNotFoundException: File not found - " + fileName);

} catch (IOException e) {

System.out.println("IOException occurred while reading the file.");

// 2. ArithmeticException

int numerator = 10;

int denominator = 0;

try {

int result = numerator / denominator;

System.out.println("Result: " + result);

} catch (ArithmeticException e) {

System.out.println("ArithmeticException: Cannot divide by zero.");

// 3. ArrayIndexOutOfBoundsException

int[] arr = {1, 2, 3};

try {

int value = arr[5];

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

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("ArrayIndexOutOfBoundsException: Invalid index


access.");
}

// 4. NullPointerException

String text = null;

try {

int len = text.length();

System.out.println("Length: " + len);

} catch (NullPointerException e) {

System.out.println("NullPointerException: Attempt to access null object.");

System.out.println("\nExecution completed.");

38)
Create an abstract class Person with:
● Fields: name, age

● Constructor to initialize the fields

● Abstract method:
● Create a class Student that inherits from Person:

○ Additional fields: rollNumber, course

○ Override the displayDetails() method to print all student details

● Create another class Teacher that also extends Person:

○ Additional fields: employeeId, subject

○ Override the displayDetails() method to print all teacher details

● Demonstrate encapsulation by making all fields private and using getter and
setter methods.
● In the main() method:

○ Create an array of Person references (use polymorphism).

○ Store both Student and Teacher objects.

○ Call the displayDetails() method for each object using a loop.

// Abstract base class


abstract class Person {
private String name;
private int age;

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Getters and setters


public String getName() { return name; }
public void setName(String name) { this.name = name; }

public int getAge() { return age; }


public void setAge(int age) { this.age = age; }

// Abstract method
public abstract void displayDetails();
}

// Student class
class Student extends Person {
private int rollNumber;
private String course;

public Student(String name, int age, int rollNumber, String course) {


super(name, age);
this.rollNumber = rollNumber;
this.course = course;
}

public int getRollNumber() { return rollNumber; }


public void setRollNumber(int rollNumber) { this.rollNumber = rollNumber; }

public String getCourse() { return course; }


public void setCourse(String course) { this.course = course; }

@Override
public void displayDetails() {
System.out.println("Student Details:");
System.out.println("Name: " + getName());
System.out.println("Age: " + getAge());
System.out.println("Roll Number: " + rollNumber);
System.out.println("Course: " + course);
System.out.println();
}
}

// Teacher class
class Teacher extends Person {
private String employeeId;
private String subject;

public Teacher(String name, int age, String employeeId, String subject) {


super(name, age);
this.employeeId = employeeId;
this.subject = subject;
}

public String getEmployeeId() { return employeeId; }


public void setEmployeeId(String employeeId) { this.employeeId = employeeId; }

public String getSubject() { return subject; }


public void setSubject(String subject) { this.subject = subject; }

@Override
public void displayDetails() {
System.out.println("Teacher Details:");
System.out.println("Name: " + getName());
System.out.println("Age: " + getAge());
System.out.println("Employee ID: " + employeeId);
System.out.println("Subject: " + subject);
System.out.println();
}
}

// Main class
public class Main {
public static void main(String[] args) {
Person[] people = new Person[4];

people[0] = new Student("Alice", 20, 101, "Computer Science");


people[1] = new Teacher("Dr. Smith", 45, "T123", "Mathematics");
people[2] = new Student("Bob", 22, 102, "Electronics");
people[3] = new Teacher("Prof. Jane", 50, "T456", "Physics");

for (Person p : people) {


p.displayDetails(); // Polymorphic call
}
}
}

39) A) Write a Java program to create a class called Employee with


methods called work() and getSalary(). Create a subclass called HRManager
that overrides the work() method and adds a new method called
addEmployee().

// Employee base class


class Employee {
public void work() {
System.out.println("Employee is working.");
}

public double getSalary() {


return 50000.0; // base salary
}
}

// HRManager subclass
class HRManager extends Employee {
@Override
public void work() {
System.out.println("HR Manager is managing hiring and employee
relations.");
}

public void addEmployee() {


System.out.println("New employee added to the system.");
}
}

// Main class to test


public class EmployeeDemo {
public static void main(String[] args) {
Employee emp = new Employee();
emp.work();
System.out.println("Salary: " + emp.getSalary());

HRManager hr = new HRManager();


hr.work();
hr.addEmployee();
System.out.println("Salary: " + hr.getSalary());
}
}

B) Develop a JAVA program to create a class named shape. Create three sub
classes namely: circle, triangle and square, each class has two member
functions named draw () and erase (). Demonstrate polymorphism
concepts by developing suitable methods, defining member data and
main program.

// Base class
class Shape {
public void draw() {
System.out.println("Drawing a shape.");
}

public void erase() {


System.out.println("Erasing a shape.");
}
}

// Circle class
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle.");
}

@Override
public void erase() {
System.out.println("Erasing a circle.");
}
}

// Triangle class
class Triangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a triangle.");
}

@Override
public void erase() {
System.out.println("Erasing a triangle.");
}
}

// Square class
class Square extends Shape {
@Override
public void draw() {
System.out.println("Drawing a square.");
}

@Override
public void erase() {
System.out.println("Erasing a square.");
}
}

// Main class to demonstrate polymorphism


public class ShapeDemo {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();

for (Shape s : shapes) {


s.draw();
s.erase();
System.out.println();
}
}
}

40) Develop a JAVA program to create an abstract class Shape with


abstract methods calculateArea() and calculatePerimeter(). Create subclasses
Circle and Triangle that extend the Shape class and implement the respective
methods to calculate the area and perimeter of each shape.

// Abstract class Shape


abstract class Shape {
// Abstract methods to be implemented by subclasses
abstract double calculateArea();
abstract double calculatePerimeter();
}

// Circle subclass
class Circle extends Shape {
private double radius;

// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Implement abstract methods


@Override
double calculateArea() {
return Math.PI * radius * radius;
}

@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

// Triangle subclass
class Triangle extends Shape {
private double sideA, sideB, sideC;

// Constructor
public Triangle(double sideA, double sideB, double sideC) {
this.sideA = sideA;
this.sideB = sideB;
this.sideC = sideC;
}

// Implement abstract methods


@Override
double calculateArea() {
// Heron's formula
double s = (sideA + sideB + sideC) / 2;
return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC));
}

@Override
double calculatePerimeter() {
return sideA + sideB + sideC;
}
}
// Main class to run the program
public class ShapeDemo {
public static void main(String[] args) {
Shape circle = new Circle(5);
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());

Shape triangle = new Triangle(3, 4, 5);


System.out.println("Triangle Area: " + triangle.calculateArea());
System.out.println("Triangle Perimeter: " +
triangle.calculatePerimeter());
}
}

41) A) Write a java program to Move all zeroes to end of array

Input: arr[] = {1, 2, 0, 4, 3, 0, 5, 0};

Output: arr[] = {1, 2, 4, 3, 5, 0, 0, 0};


public class MoveZeroes {
public static void main(String[] args) {
int[] arr = {1, 2, 0, 4, 3, 0, 5, 0};

int index = 0; // Points to the position to place next non-zero element

// Move non-zero elements forward


for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
arr[index++] = arr[i];
}
}

// Fill remaining positions with 0


while (index < arr.length) {
arr[index++] = 0;
}
// Print result
System.out.print("Output: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}

B)Write a Java program to create an interface Sortable with a method sort()


that sorts an array of integers in ascending order. Create two classes
BubbleSort and SelectionSort that implement the Sortable interface and
provide their own implementations of the sort() method.

// Define the interface


interface Sortable {
void sort(int[] arr);
}

// BubbleSort implementation
class BubbleSort implements Sortable {
public void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}
// SelectionSort implementation
class SelectionSort implements Sortable {
public void sort(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;
}
}
// Swap
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}

// Main class to test


public class SortDemo {
public static void main(String[] args) {
int[] array1 = {5, 3, 8, 4, 2};
int[] array2 = {9, 7, 1, 6, 0};

Sortable sorter1 = new BubbleSort();


sorter1.sort(array1);
System.out.print("BubbleSort: ");
for (int num : array1) System.out.print(num + " ");
System.out.println();

Sortable sorter2 = new SelectionSort();


sorter2.sort(array2);
System.out.print("SelectionSort: ");
for (int num : array2) System.out.print(num + " ");
}
}

42) A) Write a Java program to create a class called "Book" with instance
variables title, author, and price. Implement a default constructor and two
parameterized constructors:

One constructor takes the title and author as parameters.


The other constructor takes title, author, and price as parameters.
Print the values of the variables for each constructor.

class Book {
String title;
String author;
double price;

// Default constructor
Book() {
this.title = "Unknown";
this.author = "Unknown";
this.price = 0.0;
}

// Constructor with title and author


Book(String title, String author) {
this.title = title;
this.author = author;
this.price = 0.0;
}

// Constructor with title, author, and price


Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}

void printDetails() {
System.out.println("Title: " + title + ", Author: " + author + ", Price: " +
price);
}

public static void main(String[] args) {


Book b1 = new Book();
Book b2 = new Book("1984", "George Orwell");
Book b3 = new Book("Sapiens", "Yuval Noah Harari", 499.99);

b1.printDetails();
b2.printDetails();
b3.printDetails();
}
}

B) Write a Java program to create a class called "TrafficLight" with attributes


for color and duration, and methods to change the color and check for red or
green.

class TrafficLight {
private String color;
private int duration; // in seconds

public TrafficLight(String color, int duration) {


this.color = color;
this.duration = duration;
}

public void changeColor(String newColor, int newDuration) {


this.color = newColor;
this.duration = newDuration;
System.out.println("Changed to " + color + " for " + duration + "
seconds.");
}

public void checkSignal() {


if (color.equalsIgnoreCase("Red")) {
System.out.println("Stop! It's RED.");
} else if (color.equalsIgnoreCase("Green")) {
System.out.println("Go! It's GREEN.");
} else {
System.out.println("Caution! It's " + color);
}
}

public static void main(String[] args) {


TrafficLight light = new TrafficLight("Red", 30);
light.checkSignal();

light.changeColor("Green", 45);
light.checkSignal();

light.changeColor("Yellow", 5);
light.checkSignal();
}
}

You might also like