0% found this document useful (0 votes)
29 views125 pages

OOP_Problem_Statement_2024-25_Sem_2_solutions

The document outlines several programming tasks in Java, including the implementation of a CaesarCipher class for encryption and decryption, a URLFinder class for validating URLs, matrix operations like transpose and inverse, triangle pattern printing, and ArrayList manipulations. Each task includes a problem statement, code implementation, and expected output. The document serves as a comprehensive guide for practicing object-oriented programming and data structures in Java.

Uploaded by

t9875297
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)
29 views125 pages

OOP_Problem_Statement_2024-25_Sem_2_solutions

The document outlines several programming tasks in Java, including the implementation of a CaesarCipher class for encryption and decryption, a URLFinder class for validating URLs, matrix operations like transpose and inverse, triangle pattern printing, and ArrayList manipulations. Each task includes a problem statement, code implementation, and expected output. The document serves as a comprehensive guide for practicing object-oriented programming and data structures in Java.

Uploaded by

t9875297
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/ 125

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.

CODE :

CaesarCipher.java

public class CaesarCipher{

private String alphabet;

private String shifted_alphabet;

private int mainkey;

public CaesarCipher(int key){


alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

shifted_alphabet = alphabet.substring(key) + alphabet.substring(0,


key);

mainkey = key;

public String encrypt(String input){

//strings are immutable but a stringbuilder is mutable

StringBuilder encrypted = new StringBuilder(input);

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

char currChar = input.charAt(i);

boolean isLower = Character.isLowerCase(currChar);

char upperChar = Character.toUpperCase(currChar);

int idx = alphabet.indexOf(upperChar);

if (idx != -1) {

char newChar = shifted_alphabet.charAt(idx);

encrypted.setCharAt(i, isLower ?
Character.toLowerCase(newChar) : newChar);

return encrypted.toString();

public String decrypt(String input) {


CaesarCipher cc = new CaesarCipher(26 - mainkey);

return cc.encrypt(input);

TestCaeserCipher.java

import java.util.Scanner;

public class TestCaesarCipher {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a message to encrypt: ");

String message = scanner.nextLine();

CaesarCipher cipher = new CaesarCipher(18);

String encrypted = cipher.encrypt(message);

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

String decrypted = cipher.decrypt(encrypted);

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

scanner.close();
}

OUTPUT :

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

URLFinder.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//regex (regular expression) is a special sequence of characters that
defines a search pattern.
public class URLFinder {
private String URL;
public URLFinder(String URL){
this.URL = URL;
}
public boolean urlChecker(String inputUrl) {
// Basic URL pattern (simplified for most use cases)
String regex = "^(https?://)?(www\\.)?([\\w-]+)\\.+[\\w]{2,}(/\\
S*)?$";

Pattern pattern = Pattern.compile(regex);


Matcher matcher = pattern.matcher(inputUrl);

return matcher.matches();
}
}

TestURLFinder.java
import java.util.Scanner;

public class TestURLFinder {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a URL to validate: ");


String input = scanner.nextLine();

// Create URLFinder object


URLFinder finder = new URLFinder(input);
// Check if URL is valid
boolean isValid = finder.urlChecker(input);

if (isValid) {
System.out.println("The URL is valid.");
} else {
System.out.println("The URL is invalid.");
}

scanner.close();
}
}

OUTPUT:

3) Perform the following operations on given matrix

1 2 3

M = 4 5 6

7 8 9

1. Transpose
2. Determinant
3. Inverse

CODE:

import java.util.*;
public class Matrix {

//FUNCTION TO CALCULATE THE TRANSPOSE OF THE MARTIX

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;

// to compute the determinant of a matrix

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

return matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2]


* matrix[2][1])

- matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2]


* matrix[2][0])

+ matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1]


* matrix[2][0]);

}
// to compute the inverse of a matrix (only if determinant is non-
zero)

public static double[][] inverse(int[][] matrix, int determinant) {

if (determinant == 0) {

System.out.println("Inverse does not exist as the determinant


is 0.");

return null;

double[][] inverse = new double[3][3];

// Calculate the adjoint matrix and then multiply it by 1/det

int[][] adjoint = new int[3][3];

adjoint[0][0] = (matrix[1][1] * matrix[2][2] - matrix[1][2] *


matrix[2][1]);

adjoint[0][1] = -(matrix[1][0] * matrix[2][2] - matrix[1][2] *


matrix[2][0]);

adjoint[0][2] = (matrix[1][0] * matrix[2][1] - matrix[1][1] *


matrix[2][0]);
adjoint[1][0] = -(matrix[0][1] * matrix[2][2] - matrix[0][2] *
matrix[2][1]);

adjoint[1][1] = (matrix[0][0] * matrix[2][2] - matrix[0][2] *


matrix[2][0]);

adjoint[1][2] = -(matrix[0][0] * matrix[2][1] - matrix[0][1] *


matrix[2][0]);

adjoint[2][0] = (matrix[0][1] * matrix[1][2] - matrix[0][2] *


matrix[1][1]);

adjoint[2][1] = -(matrix[0][0] * matrix[1][2] - matrix[0][2] *


matrix[1][0]);

adjoint[2][2] = (matrix[0][0] * matrix[1][1] - matrix[0][1] *


matrix[1][0]);

// Find inverse by multiplying adjoint by 1/det

double invDet = 1.0 / determinant;

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

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

inverse[i][j] = adjoint[i][j] * invDet;

}
return inverse;

// For int matrices (input and transpose)

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

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

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

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

System.out.println();

// For double matrices (inverse)

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

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

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

System.out.printf("%.2f ", matrix[i][j]);

}
System.out.println();

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

System.out.println("Enter the elements of the 3x3 matrix:");

int[][] matrix = new int[3][3];

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

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

matrix[i][j] = sc.nextInt();

System.out.println("The Transpose of the matrix is : ");

int[][] transposedMatrix = transpose(matrix);

printMatrix(transposedMatrix);

int determinant = determinant(matrix);

System.out.println("\nDeterminant of the matrix: " + determinant);

double[][] inverseMatrix = inverse(matrix, determinant);


if (inverseMatrix != null) {

System.out.println("\nInverse of the matrix:");

printMatrix(inverseMatrix);

sc.close();

OUTPUT:

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


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

Code :
import java.util.Scanner;

public class TrianglePatterns {

public void PascalsTriangle() {


Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows for Pascals Triangle: ");
int rows = sc.nextInt();

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


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

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

System.out.println();
}
}
public void NumbersTriangle() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = sc.nextInt();

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


// Print leading spaces for pyramid alignment
for (int space = 1; space <= rows - i; space++) {
System.out.print(" "); // Two spaces for spacing
}

// Print numbers with extra spacing


for (int j = 1; j <= i; j++) {
System.out.print(i + " "); // One number and 3 spaces
}

System.out.println();
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
TrianglePatterns tp = new TrianglePatterns(); // create object to
call non-static methods

System.out.println("WHAT DO YOU WANT TO PRINT? (1: PASCAL TRIANGLE


2: NUMBER TRIANGLE): ");
int key = sc.nextInt();

switch (key) {
case 1:
System.out.println("THIS IS THE PASCAL'S TRIANGLE");
tp.PascalsTriangle();
break;
case 2:
System.out.println("THIS IS THE NUMBER TRIANGLE");
tp.NumbersTriangle();
break;
default:
System.out.println("PRINTING BOTH:");
tp.PascalsTriangle();
tp.NumbersTriangle();
}
}
}

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?

CODE:

import java.util.ArrayList;

import java.util.Iterator;

import java.util.Scanner;

public class Array {


public static boolean isPrime(int n) {

if (n <= 1) return false;

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

if (n % i == 0)

return false;

return true;

public static void printArrayList(ArrayList<Integer> list) {

System.out.println("\nUsing for-loop:");

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

System.out.print(list.get(i) + " ");

System.out.println("\nUsing Iterator:");

Iterator<Integer> it = list.iterator();

while (it.hasNext()) {

System.out.print(it.next() + " ");

System.out.println("\nUsing enhanced for-loop:");

for (int num : list) {

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


}

System.out.println();

public static void main(String args[]){

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

//adding numbers 1-25 in the numbers arraylist

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

numbers.add(i);

//printing the arraylist elements

printArrayList(numbers);

// Remove prime numbers using iterator

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

while (iterator.hasNext()) {

int num = iterator.next();

if (isPrime(num)) {

iterator.remove();

System.out.println("\nArrayList after removing prime numbers:");

printArrayList(numbers);

// b) Check if an element exists


Scanner sc = new Scanner(System.in);

System.out.print("\nEnter a number to search in the list: ");

int search = sc.nextInt();

if (numbers.contains(search)) {

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

} else {

System.out.println(search + " does NOT exist in the list.");

// c) Add an element at a specific index

System.out.print("Enter index to insert an element: ");

int index = sc.nextInt();

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

int element = sc.nextInt();

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

numbers.add(index, element);

System.out.println("After inserting " + element + " at index "


+ index + ":");

printArrayList(numbers);

} else {

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

sc.close();

}
}

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.

CODE:

import java.util.*;

public class ArrayOperations {

// Method to print the array


public static void printArray(int[] arr) {

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

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

System.out.println();

// Method to reverse array in place

public static void reverseArray(int[] arr) {

int start = 0, end = arr.length - 1;

while (start < end) {

int temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

start++;

end--;

// Method to merge and sort two arrays

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


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

System.arraycopy(arr1, 0, merged, 0, arr1.length);

System.arraycopy(arr2, 0, merged, arr1.length, arr2.length);

// Use Java's built-in Arrays class

java.util.Arrays.sort(merged);

return merged;

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the size of the array:");

int n = sc.nextInt();

int[] array_int = new int[n];

System.out.println("Enter the Elements of the array:");

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

array_int[i] = sc.nextInt();

}
// Find min and max

int min = array_int[0];

int max = array_int[0];

for (int num : array_int) {

if (num < min) min = num;

if (num > max) max = num;

System.out.println("Largest Number : " + max + " Smallest Number :


" + min);

// Reverse the array

reverseArray(array_int);

System.out.println("The reversed array:");

printArray(array_int);

// Input second array for merging

System.out.print("\nEnter number of elements in second array: ");

int m = sc.nextInt();

int[] array2 = new int[m];

System.out.println("Enter " + m + " integers:");


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

array2[i] = sc.nextInt();

int[] merged = mergeAndSortArrays(array_int, array2);

System.out.println("Merged and Sorted Array: " +


java.util.Arrays.toString(merged));

sc.close();

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

import java.util.Scanner;

public class StringOps {

// 1. Check if a string is a palindrome

public static boolean isPalindrome(String str) {

String cleanStr = str.replaceAll("\\s+", "").toLowerCase();

int left = 0, right = cleanStr.length() - 1;

while (left < right) {

if (cleanStr.charAt(left) != cleanStr.charAt(right)) {

return false;

left++;
right--;

return true;

// 2. Count occurrences of a specific character

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

int count = 0;

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

if (ch == target) {

count++;

return count;
}

// 3. Remove all whitespaces from the string

public static String removeWhitespace(String str) {

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

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input String

System.out.print("Enter a string: ");

String input = sc.nextLine();

// Check Palindrome

if (isPalindrome(input)) {

System.out.println("The string is a PALINDROME.");


} else {

System.out.println("The string is NOT a palindrome.");

// Count character

System.out.print("Enter a character to count: ");

char ch = sc.next().charAt(0);

int count = countCharacter(input, ch);

System.out.println("Character '" + ch + "' occurs " + count + "


times.");

// Remove whitespaces

String noSpace = removeWhitespace(input);

System.out.println("String without spaces: \"" + noSpace + "\"");

sc.close();
}

8) Design a class BankAccount with methods for deposit, withdraw,


and check balance. Implement exception handling for insufficient
funds during withdrawal.

BankAccount.java

import java.util.*;

class InsufficientFundsException extends Exception {

public InsufficientFundsException(String message) {


super(message);

class BankAccount {

private double balance;

public BankAccount(double initialBalance) {

this.balance = initialBalance;

public void deposit(double amount) {

if (amount > 0) {
balance += amount;

System.out.println("Deposited: ₹" + amount);

} else {

System.out.println("Deposit amount must be positive.");

public void withdraw(double amount) throws InsufficientFundsException


{

if (amount > balance) {

throw new InsufficientFundsException("Insufficient balance!


You only have ₹" + balance);

} else if (amount <= 0) {

System.out.println("Withdrawal amount must be positive.");


} else {

balance -= amount;

System.out.println("Withdrew: ₹" + amount);

public void checkBalance() {

System.out.println("Current Balance: ₹" + balance);

BankApp.java
import java.util.*;

public class BankApp {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

BankAccount myAccount = new BankAccount(1000.0); // Starting with


₹1000

while (true) {

System.out.println("\n--- Bank Menu ---");

System.out.println("1. Deposit");

System.out.println("2. Withdraw");

System.out.println("3. Check Balance");

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

int choice = sc.nextInt();

try {

switch (choice) {

case 1:

System.out.print("Enter amount to deposit: ₹");

double depositAmount = sc.nextDouble();

myAccount.deposit(depositAmount);

break;

case 2:

System.out.print("Enter amount to withdraw: ₹");

double withdrawAmount = sc.nextDouble();


myAccount.withdraw(withdrawAmount);

break;

case 3:

myAccount.checkBalance();

break;

case 4:

System.out.println("Thank you for using our bank


services!");

sc.close();

return;

default:

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

}
} catch (InsufficientFundsException e) {

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

}
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 FileWordCharCount {

public static void main(String[] args) {

// Update the file path as per your file location


String fileName = "sample.txt"; // You can change this to your own
filename

int charCount = 0;

int wordCount = 0;

try {

FileReader fr = new FileReader(fileName);

BufferedReader br = new BufferedReader(fr);

String line;

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

// Count characters

charCount += line.length();

// Split the line into words using regex

String[] words = line.trim().split("\\s+");


// Avoid counting if the line is empty

if (!line.trim().isEmpty()) {

wordCount += words.length;

br.close();

fr.close();

System.out.println("Total Characters: " + charCount);

System.out.println("Total Words: " + wordCount);

} catch (IOException e) {

System.out.println("Error reading the 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.

import java.util.Scanner;

public class GCDandBinary {

// Method to find GCD using Euclid's Algorithm

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

while (b != 0) {

int temp = b;

b = a % b;

a = temp;

return a;

// Method to convert decimal to binary manually


public static String decimalToBinaryManual(int num) {

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

String binary = "";

while (num > 0) {

binary = (num % 2) + binary;

num = num / 2;

return binary;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// GCD part

System.out.print("Enter first number for GCD: ");

int num1 = sc.nextInt();

System.out.print("Enter second number for GCD: ");

int num2 = sc.nextInt();

int gcd = findGCD(num1, num2);

System.out.println("GCD of " + num1 + " and " + num2 + " is: " +
gcd);
// Decimal to binary conversion

System.out.print("\nEnter a decimal number to convert to binary:


");

int decimal = sc.nextInt();

String builtInBinary = Integer.toBinaryString(decimal);

String manualBinary = decimalToBinaryManual(decimal);

System.out.println("Binary (Using Built-in Method): " +


builtInBinary);

System.out.println("Binary (Using Manual Method): " +


manualBinary);

sc.close();

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

class CarAssembly implements Runnable {


private String componentName;
private int timeToPrepare;

// Constructor to initialize fields


public CarAssembly(String componentName, int timeToPrepare) {
this.componentName = componentName;
this.timeToPrepare = timeToPrepare;
}

// The run method which will be executed by the thread


public void run() {
try {
System.out.println(componentName + " is preparing...");
Thread.sleep(timeToPrepare); // Sleep for preparation time
System.out.println(componentName + " is ready.");
} catch (InterruptedException e) {
System.out.println(componentName + " interrupted!");
}
}
// Main method
public static void main(String[] args) {
// Create thread objects for each component
Thread engineThread = new Thread(new CarAssembly("Engine", 3000));
Thread bodyThread = new Thread(new CarAssembly("Body", 4000));
Thread wheelsThread = new Thread(new CarAssembly("Wheels", 5000));

// Start all threads


engineThread.start();
bodyThread.start();
wheelsThread.start();

// Wait for all threads to complete


try {
engineThread.join();
bodyThread.join();
wheelsThread.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}

System.out.println("All car components are ready. Car is


assembled!");
}
}

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


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();

while (sc.hasNextLine()) {
String input = sc.nextLine().trim();
if (input.isEmpty()) break; // Optional: stop if empty line

String[] parts = input.split(" ");


String command = parts[0];

switch (command) {
case "insert":
int insertIndex = Integer.parseInt(parts[1]);
int value = Integer.parseInt(parts[2]);
list.add(insertIndex, value);
System.out.println(list);
break;

case "update":
int updateIndex = Integer.parseInt(parts[1]);
int newValue = Integer.parseInt(parts[2]);
list.set(updateIndex, newValue);
System.out.println(list);
break;

case "delete":
int deleteIndex = Integer.parseInt(parts[1]);
list.remove(deleteIndex);
System.out.println(list);
break;

case "sum":
int left = Integer.parseInt(parts[1]);
int right = Integer.parseInt(parts[2]);
int sum = 0;
for (int i = left; i <= right; i++) {
sum += list.get(i);
}
System.out.println(sum);
break;

default:
System.out.println("Unknown command: " + command);
}
}

sc.close();
}
}

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


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

// Add a word to the frequency map


public static void addWord(String word) {
freqMap.put(word, freqMap.getOrDefault(word, 0) + 1);
}

// Remove a word (decrease its frequency, and remove if 0)


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

// Query the frequency of a word


public static void queryWord(String word) {
System.out.println("Frequency of '" + word + "': " +
freqMap.getOrDefault(word, 0));
}

// Find the most frequent word (smallest lexicographically in case of


tie)
public static void mostFrequent() {
int maxFreq = 0;
String result = "";

for (Map.Entry<String, Integer> entry : freqMap.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 present.");
}
}

// Driver
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

while (sc.hasNextLine()) {
String input = sc.nextLine().trim();
if (input.isEmpty()) break; // optional: stop on empty line

String[] parts = input.split(" ");


String command = parts[0];

switch (command) {
case "add":
addWord(parts[1]);
break;
case "remove":
removeWord(parts[1]);
break;
case "query":
queryWord(parts[1]);
break;
case "mostFrequent":
mostFrequent();
break;
default:
System.out.println("Unknown command: " + command);
}
}
sc.close();
}
}

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.
// BankAccMT.java
public class BankAccMT {
private String accountHolder;
private int balance;

// Constructor to initialize the account holder and initial balance


public BankAccMT(String name, int initialBalance) {
this.accountHolder = name;
this.balance = initialBalance;
}

// Synchronized method for depositing money into the account


public synchronized void deposit(int amount) {
balance += amount;
System.out.println(accountHolder + " deposited " + amount + ",
Balance: " + balance);
}

// Synchronized method for withdrawing money from the account


public synchronized void withdraw(int amount) {
if (balance >= amount) {
balance -= amount;
System.out.println(accountHolder + " withdrew " + amount + ",
Balance: " + balance);
} else {
System.out.println(accountHolder + " attempted to withdraw " +
amount + " but has insufficient funds.");
}
}

// Synchronized method to transfer money from one account to another


public synchronized void transferTo(BankAccMT target, int amount) {
if (balance >= amount) {
this.withdraw(amount); // Withdraw from the current account
target.deposit(amount); // Deposit into the target account
System.out.println("Transferred " + amount + " from " +
accountHolder + " to " + target.getAccountHolder());
} else {
System.out.println(accountHolder + " attempted to transfer " +
amount + " but has insufficient funds.");
}
}

// Method to get the current balance of the account


public synchronized int getBalance() {
return balance;
}

// Getter method for the account holder's name


public String getAccountHolder() {
return accountHolder;
}
}

class User extends Thread {


private BankAccMT account;
private BankAccMT[] allAccounts;

public User(String name, BankAccMT account, BankAccMT[] allAccounts) {


super(name);
this.account = account;
this.allAccounts = allAccounts;
}

@Override
public void run() {
for (int i = 0; i < 5; i++) {
int operation = (int)(Math.random() * 3);
int amount = 100 + (int)(Math.random() * 400);

switch (operation) {
case 0:
account.deposit(amount);
break;
case 1:
account.withdraw(amount);
break;
case 2:
int index;
do {
index = (int)(Math.random() * allAccounts.length);
} while (allAccounts[index] == account);
account.transferTo(allAccounts[index], amount);
break;
}

try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
System.out.println(getName() + " was interrupted.");
}
}
}
}

// BankSimulation.java
public class BankSimulation {
public static void main(String[] args) {
// Create shared bank accounts
BankAccMT acc1 = new BankAccMT("Alice", 1000);
BankAccMT acc2 = new BankAccMT("Bob", 1000);
BankAccMT acc3 = new BankAccMT("Charlie", 1000);

BankAccMT[] accounts = { acc1, acc2, acc3 };

// Create and start user threads


User user1 = new User("User-Alice", acc1, accounts);
User user2 = new User("User-Bob", acc2, accounts);
User user3 = new User("User-Charlie", acc3, accounts);

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

// Wait for threads to complete


try {
user1.join();
user2.join();
user3.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}

System.out.println("\nFinal Balances:");
for (BankAccMT acc : accounts) {
System.out.println(acc.getAccountHolder() + ": " +
acc.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)

Code:
import java.util.*;
class OutOfStockException extends Exception{
public OutOfStockException(String message) {
super(message);
}
}
class NegativeQuantityException extends Exception{
public NegativeQuantityException(String message){
super(message);
}
}
class InvalidCuponCodeException extends Exception{
public InvalidCuponCodeException(String message){
super(message);
}
}
class Item{
String name;
int price;
int stock;
//constuctor
public Item(String name , int price , int stock){
this.name = name;
this.price = price;
this.stock = stock;
}
}
class ShoppingCart{
//creating an hashmap to store the item name and quantity
private Map<String, Integer> cart = new HashMap<>();
private int discount = 0;
//creating an add item function
public void addItem(String itemName , int quantity , Map<String ,
Item> inventory)
throws NegativeQuantityException, OutOfStockException {
if (quantity <= 0) {
throw new NegativeQuantityException("Quantity must be
positive.");
}
if (!inventory.containsKey(itemName)) {
System.out.println("Item not found in inventory.");
return;
}
Item item = inventory.get(itemName);
if (item.stock < quantity) {
throw new OutOfStockException("Not enough stock for " +
itemName + ". Available stock: " + item.stock);
}
cart.put(itemName, cart.getOrDefault(itemName, 0) + quantity);
item.stock -= quantity; // Update the inventory
System.out.println(quantity + " " + itemName + "(s) added to the
cart.");
}
//creating an apply coupon function
public void applycoupon(String code , Map<String , Integer>coupon)
throws InvalidCuponCodeException{
if (!coupon.containsKey(code)) {
throw new InvalidCuponCodeException("Invalid coupon
code.");
}
discount = coupon.get(code);
System.out.println("Coupon "+code+" applied. Discount:
"+discount+"%");
}
//Now checkout function
public void checkout(Map<String, Item> inventory) {
int total = 0;
System.out.println("\n--- Checkout Summary ---");
for (String itemName : cart.keySet()) {
int quantity = cart.get(itemName);
int price = inventory.get(itemName).price;
int cost = price * quantity;
total += cost;
System.out.println(itemName + ": " + quantity + " x ₹" + price + "
= ₹" + cost);
}

int discountAmount = total * discount / 100;


int finalAmount = total - discountAmount;
System.out.println("Subtotal: ₹" + total);
System.out.println("Discount: -₹" + discountAmount);
System.out.println("Total Payable: ₹" + finalAmount);
}
}
public class ShoppingCartProgram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ShoppingCart cart = new ShoppingCart();
System.out.println("Welcome to the Shopping Cart Program!");
Map<String, Item> inventory = new HashMap<>();
inventory.put("apple", new Item("apple", 10, 10));
inventory.put("banana", new Item("banana", 5, 20));
inventory.put("milk", new Item("milk", 25, 5));
Map<String, Integer> coupons = new HashMap<>();
coupons.put("SAVE10", 10);
coupons.put("DISCOUNT20", 20);
while (true) {
System.out.println("\nOptions: 1. Add Item 2. Apply Coupon
3. Checkout 4. Exit");
System.out.print("Enter your choice: ");
String choice = sc.next();

try {
switch (choice) {
case "1":
System.out.print("Enter item name: ");
String item = sc.next().toLowerCase();
System.out.print("Enter quantity: ");
int qty = sc.nextInt();
cart.addItem(item, qty, inventory);
break;
case "2":
System.out.print("Enter coupon code: ");
String code = sc.next().toUpperCase();
cart.applycoupon(code, coupons);
break;
case "3":
cart.checkout(inventory);
break;
case "4":
System.out.println("Thank you for shopping!");
sc.close();
return;
default:
System.out.println("Invalid option.");
}
} catch (NegativeQuantityException | OutOfStockException |
InvalidCuponCodeException e) {
System.out.println("Error: " + e.getMessage());
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter correct
values.");
sc.next();
}
}
}
}
OUPTPUT:

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

interface PricingStrategy {
double applyPricing(double baseFare);
}

// Default Strategy (No extra charges)


class NormalPricing implements PricingStrategy {
public double applyPricing(double baseFare) {
return baseFare;
}
}

// Peak Hour Pricing (adds 25%)


class PeakHourPricing implements PricingStrategy {
public double applyPricing(double baseFare) {
return baseFare * 1.25;
}
}

// Holiday Pricing (adds 50%)


class HolidayPricing implements PricingStrategy {
public double applyPricing(double baseFare) {
return baseFare * 1.5;
}
}
interface Vehicle{
void startRide();
void endRide();
double calculateFare(int distance);
}

//creating a bike class which is the child of vehicle


class Bike implements Vehicle{
private PricingStrategy pricingStrategy;
public Bike(PricingStrategy pricingStrategy) {
this.pricingStrategy = pricingStrategy;
}
public void startRide() {
System.out.println("Bike ride started.");
}
public void endRide() {
System.out.println("Bike ride ended.");
}
public double calculateFare(int distance) {
double baseFare = 5*distance; // Base fare for the ride
return pricingStrategy.applyPricing(baseFare);
}
}
// Auto Implementation
class Auto implements Vehicle {
private PricingStrategy strategy;
public Auto(PricingStrategy strategy) {
this.strategy = strategy;
}
public void startRide() {
System.out.println("Auto ride started.");
}
public void endRide() {
System.out.println("Auto ride ended.");
}
public double calculateFare(int distance) {
double baseFare = 8 * distance; // ₹8 per km
return strategy.applyPricing(baseFare);
}
}
// Cab Implementation
class Cab implements Vehicle {
private PricingStrategy strategy;
public Cab(PricingStrategy strategy) {
this.strategy = strategy;
}
public void startRide() {
System.out.println("Cab ride started.");
}
public void endRide() {
System.out.println("Cab ride ended.");
}
public double calculateFare(int distance) {
double baseFare = 15 * distance; // ₹15 per km
return strategy.applyPricing(baseFare);
}
}

public class RideApp {


public static void main(String[] args) {
//testing and trying different vehicle types and prcing
Vehicle bike = new Bike(new NormalPricing());
Vehicle auto = new Auto(new PeakHourPricing());
Vehicle cab = new Cab(new HolidayPricing());
int distance = 10;
// Bike
bike.startRide();
System.out.println("Bike Fare for " + distance + "km: ₹" +
bike.calculateFare(distance));
bike.endRide();
System.out.println();
// Auto
auto.startRide();
System.out.println("Auto Fare for " + distance + "km: ₹" +
auto.calculateFare(distance));
auto.endRide();
System.out.println();
// Cab
cab.startRide();
System.out.println("Cab Fare for " + distance + "km: ₹" +
cab.calculateFare(distance));
cab.endRide();
}
}

OUTPUT:

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.

Code:
import java.util.*;
//BASE CLASS : STAFF
abstract class Staff{
protected String name;
protected int id;
protected double salary;
public Staff(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
public abstract void displayDetails();
public abstract double calculateBonus();
public abstract void promote();
}
//DERIVED CLASS : PROFESSOR
class Professor extends Staff{
private String department;
public Professor(String name,int id,double salary,String department){
super(name, id, salary);
}
@Override
public void displayDetails(){ System.out.println("Professor: " + name
+ " | ID: " + id + " | Department: " + department + " | Salary: ₹" +
salary);}
@Override
public double calculateBonus(){ return salary * 0.15; }
@Override
public void promote() {
System.out.println(name + " promoted to Senior Professor. Salary
increased by 15%.");
salary *= 1.15;
System.out.println(salary);
}
}
// Administrative Staff class
class AdministrativeStaff extends Staff {
private String role;
public AdministrativeStaff(String name, int id, double salary, String
role) {
super(name, id, salary);
this.role = role;
}
@Override
public void displayDetails() {
System.out.println("Admin Staff: " + name + " | ID: " + id + " |
Role: " + role + " | Salary: ₹" + salary);
}
@Override
public double calculateBonus() {
return salary * 0.10; // 10% bonus
}
@Override
public void promote() {
System.out.println(name + " promoted to Senior " + role + ".
Salary increased by 10%.");
salary *= 1.10;
}
}
// Maintenance Staff class
class MaintenanceStaff extends Staff {
private String shift;
public MaintenanceStaff(String name, int id, double salary, String
shift) {
super(name, id, salary);
this.shift = shift;
}
@Override
public void displayDetails() {
System.out.println("Maintenance Staff: " + name + " | ID: " + id +
" | Shift: " + shift + " | Salary: ₹" + salary);
}
@Override
public double calculateBonus() {
return 2000; // fixed bonus
}
@Override
public void promote() {
System.out.println(name + " shift changed to Day and given ₹1000
hike.");
salary += 1000;
shift = "Day";
}
}

public class UniversityStaffManagement {


public static void main(String[] args) {
List<Staff> staffList = new ArrayList<>();
staffList.add(new Professor("Dr. Smith", 101, 80000, "Computer
Science"));
staffList.add(new AdministrativeStaff("Alice", 102, 50000,
"Registrar"));
staffList.add(new MaintenanceStaff("Bob", 103, 30000, "Night"));
System.out.println("=== Staff Details Before Promotion ===");
for (Staff staff : staffList) {
staff.displayDetails();
System.out.println("Bonus: ₹" + staff.calculateBonus());
System.out.println();
}
System.out.println("=== Promoting Staff ===");
for (Staff staff : staffList) {
staff.promote();
}
System.out.println("\n=== Staff Details After Promotion ===");
for (Staff staff : staffList) {
staff.displayDetails();
System.out.println("Updated Bonus: ₹" +
staff.calculateBonus());
System.out.println();
}
}
}
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.

CODE:
public class Rectangle {
private double length;
private double width;
//creating a constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double area(){
return length * width;
}
public void compareArea(Rectangle r){
double thisArea = this.area();
double otherArea = r.area();
System.out.println("Area of this rectangle: " + thisArea);
System.out.println("Area of other rectangle: " + otherArea);
if (thisArea > otherArea) {
System.out.println("This rectangle has a larger area.");
} else if (thisArea < otherArea) {
System.out.println("Other rectangle has a larger area.");
} else {
System.out.println("Both rectangles have equal area.");
}
}
}

public class MathOperation {


//static method to caclulate square of a number
public static int square(int number) {
return number * number;
}
//instace method to calculate cube of a number
public int cube(int number) {
return number * number * number;
}
}

public class RectangleMathDemo {


public static void main(String[] args){
Rectangle r1 = new Rectangle(1.2,1.2);
Rectangle r2 = new Rectangle(2.5,12.5);
System.out.println("== Comparing Rectangles ==");
r1.compareArea(r2);
// Demonstrate MathOperations
System.out.println("\n== Math Operations ==");
int number = 3;
// Static method call
System.out.println("Square of " + number + ": " +
MathOperation.square(number));
// Instance method call
MathOperation math = new MathOperation();
System.out.println("Cube of " + number + ": " +
math.cube(number));
}
}

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.

import java.util.Scanner;

public class CinemaSeatingSystem {

private static final int ROWS = 5;

private static final int COLUMNS = 6;

private static int[][] seats = new int[ROWS][COLUMNS];

// Display current seating map

public static void displaySeats() {

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


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

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

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

System.out.println();

// Book a seat if available

public static void bookSeat(int row, int col) {

if (row < 0 || row >= ROWS || col < 0 || col >= COLUMNS) {

System.out.println("Invalid seat number. Please try again.");

} else if (seats[row][col] == 1) {

System.out.println("Seat already booked!");

} else {

seats[row][col] = 1;

System.out.println("Seat (" + row + "," + col + ") booked


successfully.");

// Main method

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


int choice;

System.out.println(" Welcome to Cinema Seat Booking System");

do {

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

System.out.println("1. Display Seat Map");

System.out.println("2. Book a Seat");

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

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

choice = scanner.nextInt();

switch (choice) {

case 1:

displaySeats();

break;

case 2:

System.out.print("Enter row number (0 to " + (ROWS -


1) + "): ");

int row = scanner.nextInt();

System.out.print("Enter column number (0 to " +


(COLUMNS - 1) + "): ");

int col = scanner.nextInt();

bookSeat(row, col);
break;

case 3:

System.out.println("Thank you for using the Cinema


Booking System!");

break;

default:

System.out.println("Invalid choice. Please try


again.");

} while (choice != 3);

scanner.close();

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.

CODE:
import java.util.Scanner;

public class RemoveVowels {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input paragraph from user
System.out.println("Enter a paragraph:");
String input = scanner.nextLine();
// StringBuilder to efficiently modify the paragraph
StringBuilder modified = new StringBuilder(input);
int removedCount = 0;
// Iterate and remove vowels
for (int i = 0; i < modified.length(); ) {
char ch = modified.charAt(i);
if (isVowel(ch)) {
modified.deleteCharAt(i); // delete without moving
to next char
removedCount++;
} else {
i++; // move to next character only if not deleted
}
}
// Output results
System.out.println("\nTransformed Paragraph (without
vowels):");
System.out.println(modified.toString());
System.out.println("Total vowels removed: " + removedCount);
scanner.close();
}
// Helper method to check if character is a vowel
private static boolean isVowel(char ch) {
return "aeiouAEIOU".indexOf(ch) != -1;
}
}

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 {
protected String name;
protected int id;
protected double basicSalary;
public Employee(String name, int id, double basicSalary) {
this.name = name;
this.id = id;
this.basicSalary = basicSalary;
}
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("ID: " + id);
System.out.println("Basic Salary: ₹" + basicSalary);
}
public double calculateSalary() {
return basicSalary;
}
}
// Manager subclass
class Manager extends Employee {
private 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);
}
}
// Developer subclass
class Developer extends Employee {
private 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 functionality
public class EmployeeSalaryDemo {
public static void main(String[] args) {
Employee emp1 = new Manager("Alice", 101, 50000, 10000);
Employee emp2 = new Developer("Bob", 102, 40000, 8000);

System.out.println("\n--- Manager Details ---");


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

System.out.println("\n--- Developer 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.

import java.util.Scanner;

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("Insufficient funds.");

balance -= amount;

System.out.println("Withdrawal of ₹" + amount + "


successful.");

// Getter for balance

public double getBalance() {

return balance;

// Main class to test the BankAccount


public class BankAccountDemo {

public static void main(String[] args) {

BankAccount myAccount = new BankAccount("ACC123456", 10000.00);

Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to the Bank Account Demo.");

System.out.println("Account Number: ACC123456, Initial Balance:


₹" + myAccount.getBalance());

// Allow multiple operations

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

System.out.print("\nEnter amount to withdraw: ₹");

double amount = scanner.nextDouble();

try {

myAccount.withdraw(amount);

} catch (ArithmeticException ae) {

System.out.println("Insufficient funds for


withdrawal.");

} catch (IllegalArgumentException ie) {

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

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

scanner.close();

System.out.println("\nThank you for using the Bank Account


system.");

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

// Printer class with printNumbers method and department attribute

class Printer{

private String department;

public Printer(String department) {

this.department = department;

//creating a synchrqqqonized method to prevent overlapping prints

public synchronized void printNumbers(){

System.out.println("print number for department: " + department);

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

System.out.println("[" + department + "] " + i);


try {

Thread.sleep(500); // 500ms delay

} catch (InterruptedException e) {

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

System.out.println("Completed printing for department: " +


department + "\n");

//Runnable tasks to print numbers

class PrinterTask implements Runnable {

private Printer printer;

public PrinterTask(Printer printer) {

this.printer = printer;

@Override

public void run() {

printer.printNumbers();

public class PrinterNum {

public static void main(String[] args) {

// Create two Printer objects for different departments


Printer printer1 = new Printer("HR");

Printer printer2 = new Printer("IT");

Thread t1 = new Thread(new PrinterTask(printer1));

Thread t2 = new Thread(new PrinterTask(printer2));

t1.start();

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

// Base class: Person

class Person {

private String name; // private

public int age; // public

protected String address; // protected

String phoneNumber; // default

// Constructor

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 selected details

public void displayDetails() {

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


accessible here

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

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

// Public method to update phone number

public void updatePhoneNumber(String newPhoneNumber) {

this.phoneNumber = newPhoneNumber;

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

// Subclass: Employee

class Employee extends Person {

public String employeeId; // public

// Constructor

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


phoneNumber, String employeeId) {

super(name, age, address, phoneNumber);


this.employeeId = employeeId;

// Overridden method to display all details

@Override

public void displayDetails() {

super.displayDetails(); // Call parent version

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

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


accessible within same package

public class AccessModifier {

public static void main(String[] args) {

// Create Employee object

Employee emp = new Employee("Alice", 28, "Pune", "9876543210",


"EMP102");

System.out.println("Accessing public method:");

emp.displayDetails(); // public method

System.out.println("\nUpdating phone number using public


method:");

emp.updatePhoneNumber("9090909090");

// Direct access to public attribute

System.out.println("\nDirect access to public attribute (age):


" + emp.age);

// Direct access to protected attribute from same package


System.out.println("Direct access to protected attribute
(address): " + emp.address);

// Direct access to default attribute from same package

System.out.println("Direct access to default attribute


(phoneNumber): " + emp.phoneNumber);

// The following line would give an error because 'name' is


private

// System.out.println("Name: " + emp.name); // ❌ Not allowed

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

Code:
import java.util.ArrayList;
// Employee class
class Employee {
int empId;
String empName;
String email;
String gender;
float salary;
// Constructor
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 display employee details
void GetEmployeeDetails() {
System.out.println("Employee ID: " + empId);
System.out.println("Name: " + empName);
System.out.println("Email: " + email);
System.out.println("Gender: " + gender);
System.out.println("Salary: ₹" + salary);
}
}
// EmployeeDB class to manage Employee objects
class EmployeeDB {
ArrayList<Employee> list = new ArrayList<>();
// Add an employee
boolean addEmployee(Employee e) {
return list.add(e);
}
// Delete employee by ID
boolean deleteEmployee(int empId) {
for (Employee e : list) {
if (e.empId == empId) {
list.remove(e);
return true;
}
}
return false; // Not found
}
// Show payslip for employee by ID
String showPaySlip(int empId) {
for (Employee e : list) {
if (e.empId == empId) {
return "Pay slip for employee ID " + empId + ": ₹" +
e.salary;
}
}
return "Employee not found.";
}
}
// Main class
public class EmployeeManagement {
public static void main(String[] args) {
Employee e1 = new Employee(101, "Alice", "[email protected]",
"Female", 50000);
Employee e2 = new Employee(102, "Bob", "[email protected]",
"Male", 45000);
Employee e3 = new Employee(103, "Charlie",
"[email protected]", "Male", 60000);
EmployeeDB db = new EmployeeDB();
db.addEmployee(e1);
db.addEmployee(e2);
db.addEmployee(e3);
System.out.println("=== Employee Details ===");
e1.GetEmployeeDetails();
System.out.println();
e2.GetEmployeeDetails();
System.out.println();
System.out.println("=== Pay Slip ===");
System.out.println(db.showPaySlip(102));
System.out.println();
System.out.println("=== Deleting Employee 102 ===");
if (db.deleteEmployee(102)) {
System.out.println("Employee deleted successfully.");
} else {
System.out.println("Employee not found.");
}
System.out.println("\n=== Pay Slip After Deletion ===");
System.out.println(db.showPaySlip(102));
}
}

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

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

import java.util.Arrays;
public class RemoveDuplicate {
public static int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0; // slow pointer
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j]; // update next unique element position
}
}
// Optional: Fill the rest of the array with underscores or placeholders
for (int k = i + 1; k < nums.length; k++) {
nums[k] = Integer.MIN_VALUE; // represents _ or unused value
}
return i + 1; // new length of unique elements
}
public static void main(String[] args) {
int[] nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
int newLength = removeDuplicates(nums);
System.out.println("New Length: " + newLength);
System.out.print("Modified Array: ");
for (int n : nums) {
if (n == Integer.MIN_VALUE) System.out.print("_ ");
else System.out.print(n + " ");
}
}
}

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

public static void main(String[] args) {

try {

if (args.length != 5) {

throw new ArrayIndexOutOfBoundsException("Please enter


exactly 5 integers as command-line arguments.");

int[] numbers = new int[5];

int sum = 0;

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

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


NumberFormatException

sum += numbers[i];

double average = sum / 5.0; // might throw ArithmeticException


if divided by zero (though here not possible unless hardcoded 0 divisor)

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


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

catch (NumberFormatException e) {

System.out.println("Error: All inputs must be valid


integers.");

catch (ArithmeticException e) {

System.out.println("Error: Arithmetic exception occurred


(possible divide by zero).");

catch (ArrayIndexOutOfBoundsException e) {

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

catch (Exception e) {

System.out.println("Unexpected Error: " + 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

class Fruit {

String name;

String taste;

String size;

// Constructor

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

this.name = name;
this.taste = taste;

this.size = size;

// Method to be overridden

void eat() {

System.out.println("Fruit: " + name + ", Taste: " + taste);

// Subclass: Apple

class Apple extends Fruit {

Apple(String size) {

super("Apple", "Sweet", size);

@Override

void eat() {

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


".");

// Subclass: Orange

class Orange extends Fruit {

Orange(String size) {

super("Orange", "Tangy", size);

}
@Override

void eat() {

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


".");

// Main class

public class FruitTest {

public static void main(String[] args) {

Fruit apple = new Apple("Medium");

Fruit orange = new Orange("Large");

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.

import java.util.Scanner;

public class UniqueDigitCounter {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number (N): ");

String input = scanner.nextLine();

scanner.close();

int[] freq = new int[10]; // for digits 0 to 9

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

if (Character.isDigit(ch)) {

freq[ch - '0']++; // increment frequency of digit

} else {

System.out.println("Invalid input. Please enter digits only.");


return;

int uniqueCount = 0;

for (int count : freq) {

if (count == 1) {

uniqueCount++;

System.out.println("Number of unique digits: " + uniqueCount);

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 minLength = Integer.MAX_VALUE; // start with a large
value

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

int sum = 0;

// Right pointer moves through the array

for (int right = 0; right < nums.length; right++) {

sum += nums[right]; // add current element to the sum

// While the sum is >= target, update minLength and


shrink the window from left

while (sum >= target) {

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


// update result

sum -= nums[left]; // subtract leftmost element

left++; // move the left pointer forward

// If no valid subarray was found


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

public static void main(String[] args) {

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

int target1 = 7;

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

int target2 = 11;

System.out.println("Example 1 Output: " +


minSubArrayLen(target1, nums1)); // Output: 2

System.out.println("Example 2 Output: " +


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


public static void main(String[] args) {
// Check if the user has passed an argument
if (args.length != 1) {
System.out.println("Usage: java NumberConverter
<integer>");
return;
}
try {
// Parse the command-line argument to an integer
int number = Integer.parseInt(args[0]);
// Convert to different number systems
String binary = Integer.toBinaryString(number);
String octal = Integer.toOctalString(number);
String hex = Integer.toHexString(number).toUpperCase();
// Capital letters for hex
// Output the results
System.out.println("Given Number : " + number);
System.out.println("Binary equivalent : " + binary);
System.out.println("Octal equivalent : " + octal);
System.out.println("Hexadecimal equivalent: " + hex);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid integer.");
}
}
}
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.

Code:

import java.util.*;

//abstract class Payment

abstract class Payment {

protected double amount;

protected String transactionId;

public Payment(double amount) {

this.amount = amount;

this.transactionId = UUID.randomUUID().toString();
}

public abstract void processPayment();

public void showTransactionId() {

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

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

//subclass CreditCardPayment

class CreditCardPayment extends Payment{

private String cardNumber;

private String CVV;

private String expiryDate;

public CreditCardPayment(double amount, String cardNumber,


String CVV, String expiryDate) {

super(amount);

this.cardNumber = cardNumber;

this.CVV = CVV;

this.expiryDate = expiryDate;

@Override

public void processPayment() {

System.out.println("Processing credit card payment .... of "


+ amount);

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


System.out.println("CVV: " + CVV);

System.out.println("Payment successful!");

showTransactionId();

// Subclass: PayPal

class PayPalPayment extends Payment {

private String email;

private String password;

public PayPalPayment(double amount, String email, String


password) {

super(amount);

this.email = email;

this.password = password;

@Override

public void processPayment() {

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

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

showTransactionId(); // Corrected method call

// Subclass: UPI

class UPIPayment extends Payment {


private String upiId;

public UPIPayment(double amount, String upiId) {

super(amount);

this.upiId = upiId;

@Override

public void processPayment() {

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

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

showTransactionId(); // Corrected method call

//Processors gateaway

class PaymentGateway {

public void processTransaction(Payment payment) {

payment.processPayment();

System.out.println("Payment Successful!\n");

public class PaymentSystem {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

PaymentGateway gateway = new PaymentGateway();


System.out.println("Welcome to the Online Payment System");

System.out.println("Select Payment Method:");

System.out.println("1. Credit Card");

System.out.println("2. PayPal");

System.out.println("3. UPI");

int choice = sc.nextInt();

sc.nextLine(); // Consume newline

System.out.print("Enter amount: ₹");

double amount = sc.nextDouble();

sc.nextLine();

switch (choice) {

case 1:

System.out.print("Enter Card Number: ");

String card = sc.nextLine();

System.out.print("Enter CVV: ");

String cvv = sc.nextLine();

System.out.print("Enter Expiry Date (MM/YY): ");

String expiry = sc.nextLine();

Payment ccPayment = new CreditCardPayment(amount,


card, cvv, expiry);

gateway.processTransaction(ccPayment);

break;

case 2:

System.out.print("Enter PayPal Email: ");


String email = sc.nextLine();

System.out.print("Enter Password: ");

String pwd = sc.nextLine();

Payment paypal = new PayPalPayment(amount, email,


pwd);

gateway.processTransaction(paypal);

break;

case 3:

System.out.print("Enter UPI ID: ");

String upi = sc.nextLine();

Payment upiPayment = new UPIPayment(amount, upi);

gateway.processTransaction(upiPayment);

break;

default:

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

sc.close();

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

interface Shapex {
void calculateArea();
}
class Circle implements Shapex { // Implements Shapex
private double radius;
public Circle(double radius){
this.radius = radius;
}
public void calculateArea(){
System.out.println("Area of Circle: " + (Math.PI * radius *
radius));
}
}
// Rectangle class
class Rectangle implements Shapex {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public void calculateArea() {
double area = length * width;
System.out.printf("Area of Rectangle: %.2f\n", area);
}
}
// Triangle class
class Triangle implements Shapex {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public void calculateArea() {
double area = 0.5 * base * height;
System.out.printf("Area of Triangle: %.2f\n", area);
}
}
// Main class
public class Shape { // Renamed the main class
public static void main(String[] args) {
// Array of Shapex interface references
Shapex[] shapes = new Shapex[3];
shapes[0] = new Circle(5.0);
shapes[1] = new Rectangle(4.0, 6.0); // length = 4, width = 6
shapes[2] = new Triangle(3.0, 7.0); // base = 3, height = 7
// Polymorphic call to calculateArea
for (Shapex shape : shapes) { // Corrected the loop variable type
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.

Code:
// Custom Exception Class
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
// BankAccount Class
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public void withdraw(double amount) throws InsufficientFundsException
{
if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be
positive.");
} else if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds. Your
balance is: " + balance);
} else {
balance -= amount;
System.out.println("Withdrawal successful! Remaining balance:
" + balance);
}
}
public double getBalance() {
return balance;
}
}
// Main Class
public class BankingSystem {
public static void main(String[] args) {
BankAccount account = new BankAccount(5000); // Initial balance
double[] testWithdrawals = {1000, -200, 6000, 3000};
for (double amount : testWithdrawals) {
try {
System.out.println("\nAttempting to withdraw: " + amount);
account.withdraw(amount);
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
System.out.println("\nFinal Balance: " + account.getBalance());
}
}
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

package app;
import exception.NonEligibleException;
class Citizen {
private String name;
private int id;
private String country;
private String sex;
private String maritalStatus;
private double annualIncome;
private String economyStatus;
private int age;
public Citizen(String name, int id, String country, String sex, String
maritalStatus,
double annualIncome, String economyStatus, int age) throws
NonEligibleException {
if (age < 18 || !country.equalsIgnoreCase("India")) {
throw new NonEligibleException("Citizen not eligible: Must be
at least 18 and an Indian citizen.");
}

this.name = name;
this.id = id;
this.country = country;
this.sex = sex;
this.maritalStatus = maritalStatus;
this.annualIncome = annualIncome;
this.economyStatus = economyStatus;
this.age = age;
}
@Override
public String toString() {
return "Citizen Details:\n" +
"Name: " + name + "\n" +
"ID: " + id + "\n" +
"Age: " + age + "\n" +
"Sex: " + sex + "\n" +
"Country: " + country + "\n" +
"Marital Status: " + maritalStatus + "\n" +
"Annual Income: " + annualIncome + "\n" +
"Economy Status: " + economyStatus;
}
}
public class CitizenTest {
public static void main(String[] args) {
try {
Citizen c1 = new Citizen("Ravi Kumar", 101, "India", "Male",
"Single", 550000, "Middle", 25);
System.out.println(c1);
Citizen c2 = new Citizen("Alex", 102, "USA", "Male", "Single",
700000, "Upper", 22);
System.out.println(c2); // This will not execute due to
exception
} catch (NonEligibleException e) {
System.out.println("Eligibility Error: " + e.getMessage());
}
}
}

package exception;
public class NonEligibleException extends Exception {
public NonEligibleException(String message) {
super(message);
}
}

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 QUE 5

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.*;
import java.util.*;
public class ExceptionHandlingDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 1. File Reading with FileNotFoundException and IOException
try {
System.out.print("Enter the file path to read: ");
String filePath = scanner.nextLine();
BufferedReader reader = new BufferedReader(new
FileReader(filePath));
System.out.println("\nFile Contents:");
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("Error: File not found. Please check the
file path.");
} catch (IOException e) {
System.out.println("Error: An I/O error occurred while reading
the file.");
}
// 2. Arithmetic Operation with ArithmeticException and
InputMismatchException
try {
System.out.print("\nEnter numerator: ");
int num = scanner.nextInt();
System.out.print("Enter denominator: ");
int den = scanner.nextInt();
int result = num / den;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} catch (InputMismatchException e) {
System.out.println("Error: Invalid input. Please enter integer
values.");
scanner.nextLine(); // clear the invalid input
}
// 3. Array Access with ArrayIndexOutOfBoundsException
try {
int[] arr = {10, 20, 30};
System.out.print("\nEnter index to access array: ");
int index = scanner.nextInt();
System.out.println("Value at index " + index + ": " +
arr[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds. Valid indices
are 0 to 2.");
}
// 4. NullPointerException
try {
String str = null;
System.out.println("\nLength of string: " + str.length());
} catch (NullPointerException e) {
System.out.println("Error: Cannot operate on null object.");
}
System.out.println("\nProgram executed successfully with exception
handling.");
}}

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 class Person {


private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter and Setter
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("\n--- Student Details ---");
System.out.println("Name: " + getName());
System.out.println("Age: " + getAge());
System.out.println("Roll Number: " + rollNumber);
System.out.println("Course: " + course);
}
}
// Teacher class
class Teacher extends Person {
private int employeeId;
private String subject;
public Teacher(String name, int age, int employeeId, String subject) {
super(name, age);
this.employeeId = employeeId;
this.subject = subject;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
@Override
public void displayDetails() {
System.out.println("\n--- Teacher Details ---");
System.out.println("Name: " + getName());
System.out.println("Age: " + getAge());
System.out.println("Employee ID: " + employeeId);
System.out.println("Subject: " + subject);
}
}
// Main class
public class PersonStudentTeacherDemo {
public static void main(String[] args) {
// Array of Person references (polymorphism)
Person[] people = new Person[4];
// Adding Students
people[0] = new Student("Alice", 20, 101, "Computer Science");
people[1] = new Student("Bob", 21, 102, "Mechanical Engineering");
// Adding Teachers
people[2] = new Teacher("Dr. Smith", 45, 501, "Mathematics");
people[3] = new Teacher("Prof. Jane", 38, 502, "Physics");
// Display details using polymorphism
for (Person p : people) {
p.displayDetails();
}
}
}
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().
public class Employee {
// Default constructor
public Employee() {
System.out.println("Employee object created.");
}

public void work() {


System.out.println("Employee is working...");
}

public double getSalary() {


return 30000.0;
}
}

public class HRManager extends Employee {


public HRManager() {
System.out.println("HRManager object created.");
}

@Override
public void work() {
System.out.println("HR Manager is managing human
resources...");
}

public void addEmployee() {


System.out.println("HR Manager is adding a new employee.");
}
}

public class EmployeeTest {


public static void main(String[] args) {
Employee emp = new Employee(); // using no-arg
constructor
emp.work();
System.out.println("Salary: " + emp.getSalary());

System.out.println(); // spacer

HRManager hr = new HRManager(); // HRManager object


hr.work(); // overridden method
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.

abstract class Shape {


public abstract void draw();
public abstract void erase();
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a Circle");
}
@Override
public void erase() {
System.out.println("Erasing a Circle");
}
}
class Triangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a Triangle");
}
@Override
public void erase() {
System.out.println("Erasing a Triangle");
}
}
class Square extends Shape {
@Override
public void draw() {
System.out.println("Drawing a Square");
}
@Override
public void erase() {
System.out.println("Erasing a Square");
}
}
public class ShapeTest {
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 {


public abstract double calculateArea();
public abstract double calculatePerimeter();
}
// Subclass for Circle
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double calculateArea() {
return Math.PI * radius * radius;
}
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
// Subclass for Triangle
class Triangle extends Shape {
private double sideA, sideB, sideC;
public Triangle(double a, double b, double c) {
this.sideA = a;
this.sideB = b;
this.sideC = c;
}
public double calculateArea() {
double s = (sideA + sideB + sideC) / 2;
return Math.sqrt(s * (s - sideA) * (s - sideB) * (s -
sideC)); // Heron's formula
}
public double calculatePerimeter() {
return sideA + sideB + sideC;
}
}
// Main class
public class ShapeAreaPeri {
public static void main(String[] args) {
Shape circle = new Circle(7);
Shape triangle = new Triangle(3, 4, 5);
System.out.println("Circle:");
System.out.println("Area = " + circle.calculateArea());
System.out.println("Perimeter = " +
circle.calculatePerimeter());
System.out.println("\nTriangle:");
System.out.println("Area = " + triangle.calculateArea());
System.out.println("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 MoveZeros {
public static void main(String[] args) {
int[] arr = {1, 2, 0, 4, 3, 0, 5, 0};
moveZeroesToEnd(arr);
System.out.print("Output: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void moveZeroesToEnd(int[] arr) {
int count = 0; // Count of non-zero elements
// Traverse the array, if element is non-zero, put it at the
next available index
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
arr[count++] = arr[i];
}
}
// Fill remaining positions with zeroes
while (count < arr.length) {
arr[count++] = 0;
}
}
}
Output: 1 2 4 3 5 0 0 0
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.
interface Sortable {
void sort(int[] arr);
}
// Bubble Sort 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;
}
}
}
}
}
// Selection Sort implementation
class SelectionSort implements Sortable {
public void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
// swap
int temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}
}
// Test class
public class SortTest {
public static void main(String[] args) {
int[] arr1 = {5, 2, 9, 1, 5, 6};
int[] arr2 = arr1.clone();
Sortable bubble = new BubbleSort();
Sortable selection = new SelectionSort();
bubble.sort(arr1);
selection.sort(arr2);
System.out.print("Bubble Sort: ");
for (int num : arr1) System.out.print(num + " ");
System.out.print("\nSelection Sort: ");
for (int num : arr2) 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.
public class Book {
private String title;
private String author;
private double price;
// Default constructor
public Book() {
title = "Unknown";
author = "Unknown";
price = 0.0;
}
// Constructor with title and author
public Book(String title, String author) {
this.title = title;
this.author = author;
this.price = 0.0;
}
// Constructor with title, author, and price
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
// Method to display book info
public void display() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: ₹" + price);
System.out.println("----------------------------");
}
// Main method to test
public static void main(String[] args) {
Book b1 = new Book(); // default constructor
Book b2 = new Book("The Alchemist", "Paulo Coelho");
Book b3 = new Book("1984", "George Orwell", 299.99);
b1.display();
b2.display();
b3.display();
}
}
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.

public class TrafficLight {


private String color;
private int duration; // in seconds
public TrafficLight(String color, int duration) {
this.color = color;
this.duration = duration;
}
// Method to change the color
public void changeColor(String newColor, int newDuration) {
this.color = newColor;
this.duration = newDuration;
}
// Check if the light is red
public boolean isRed() {
return color.equalsIgnoreCase("Red");
}
// Check if the light is green
public boolean isGreen() {
return color.equalsIgnoreCase("Green");
}
public void displayStatus() {
System.out.println("Current Color: " + color);
System.out.println("Duration: " + duration + " seconds");
System.out.println("Is Red? " + isRed());
System.out.println("Is Green? " + isGreen());
System.out.println("--------------------------");
}
public static void main(String[] args) {
TrafficLight light = new TrafficLight("Red", 60);
light.displayStatus();
light.changeColor("Green", 45);
light.displayStatus();} }

You might also like