OOP_Problem_Statement_2024-25_Sem_2_solutions
OOP_Problem_Statement_2024-25_Sem_2_solutions
CODE :
CaesarCipher.java
mainkey = key;
if (idx != -1) {
encrypted.setCharAt(i, isLower ?
Character.toLowerCase(newChar) : newChar);
return encrypted.toString();
return cc.encrypt(input);
TestCaeserCipher.java
import java.util.Scanner;
scanner.close();
}
OUTPUT :
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*)?$";
return matcher.matches();
}
}
TestURLFinder.java
import java.util.Scanner;
if (isValid) {
System.out.println("The URL is valid.");
} else {
System.out.println("The URL is invalid.");
}
scanner.close();
}
}
OUTPUT:
1 2 3
M = 4 5 6
7 8 9
1. Transpose
2. Determinant
3. Inverse
CODE:
import java.util.*;
public class Matrix {
transposed[i][j] = matrix[j][i];
return transposed;
}
// to compute the inverse of a matrix (only if determinant is non-
zero)
if (determinant == 0) {
return null;
}
return inverse;
System.out.println();
}
System.out.println();
matrix[i][j] = sc.nextInt();
printMatrix(transposedMatrix);
printMatrix(inverseMatrix);
sc.close();
OUTPUT:
Code :
import java.util.Scanner;
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();
System.out.println();
}
}
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)
CODE:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
if (n % i == 0)
return false;
return true;
System.out.println("\nUsing for-loop:");
System.out.println("\nUsing Iterator:");
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
System.out.println();
numbers.add(i);
printArrayList(numbers);
while (iterator.hasNext()) {
if (isPrime(num)) {
iterator.remove();
printArrayList(numbers);
if (numbers.contains(search)) {
} else {
numbers.add(index, element);
printArrayList(numbers);
} else {
System.out.println("Invalid index!");
sc.close();
}
}
6)
CODE:
import java.util.*;
System.out.println();
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
java.util.Arrays.sort(merged);
return merged;
int n = sc.nextInt();
array_int[i] = sc.nextInt();
}
// Find min and max
reverseArray(array_int);
printArray(array_int);
int m = sc.nextInt();
array2[i] = sc.nextInt();
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;
if (cleanStr.charAt(left) != cleanStr.charAt(right)) {
return false;
left++;
right--;
return true;
int count = 0;
if (ch == target) {
count++;
return count;
}
// Input String
// Check Palindrome
if (isPalindrome(input)) {
// Count character
char ch = sc.next().charAt(0);
// Remove whitespaces
sc.close();
}
BankAccount.java
import java.util.*;
class BankAccount {
this.balance = initialBalance;
if (amount > 0) {
balance += amount;
} else {
balance -= amount;
BankApp.java
import java.util.*;
while (true) {
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
try {
switch (choice) {
case 1:
myAccount.deposit(depositAmount);
break;
case 2:
break;
case 3:
myAccount.checkBalance();
break;
case 4:
sc.close();
return;
default:
}
} catch (InsufficientFundsException e) {
}
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.*;
int charCount = 0;
int wordCount = 0;
try {
String line;
// Count characters
charCount += line.length();
if (!line.trim().isEmpty()) {
wordCount += words.length;
br.close();
fr.close();
} catch (IOException e) {
}
10)
import java.util.Scanner;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
return a;
num = num / 2;
return binary;
// GCD part
System.out.println("GCD of " + num1 + " and " + num2 + " is: " +
gcd);
// Decimal to binary conversion
sc.close();
}
11) Create the CarAssembly class which implements Runnable
interface with the following parts:
insert 0 5 [5]
sum 0 2 25
sum 0 1 25
import java.util.*;
while (sc.hasNextLine()) {
String input = sc.nextLine().trim();
if (input.isEmpty()) break; // Optional: stop if empty line
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.
add apple
remove apple
query apple
mostFrequent
import java.util.*;
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
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();
}
}
@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);
user1.start();
user2.start();
user3.start();
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);
}
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:
interface PricingStrategy {
double applyPricing(double baseFare);
}
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";
}
}
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.");
}
}
}
import java.util.Scanner;
System.out.println();
if (row < 0 || row >= ROWS || col < 0 || col >= COLUMNS) {
} else if (seats[row][col] == 1) {
} else {
seats[row][col] = 1;
// Main method
do {
System.out.println("\nMenu:");
System.out.println("3. Exit");
choice = scanner.nextInt();
switch (choice) {
case 1:
displaySeats();
break;
case 2:
bookSeat(row, col);
break;
case 3:
break;
default:
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.
CODE:
import java.util.Scanner;
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);
22)
Create a class BankAccount with the following attributes and
methods:
Attributes:
accountNumber (String)
balance (double)
Methods:
import java.util.Scanner;
class BankAccount {
// Constructor
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
if (amount <= 0) {
balance -= amount;
return balance;
try {
myAccount.withdraw(amount);
}
System.out.println("Current Balance: ₹" +
myAccount.getBalance());
scanner.close();
}
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).
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.
Ensure that the numbers from both threads are printed without any
interruption.
class Printer{
this.department = department;
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
this.printer = printer;
@Override
printer.printNumbers();
t1.start();
t2.start();
Attributes:
Methods:
class Person {
// Constructor
this.name = name;
this.age = age;
this.address = address;
this.phoneNumber = phoneNumber;
this.phoneNumber = newPhoneNumber;
// Subclass: Employee
// Constructor
@Override
emp.updatePhoneNumber("9090909090");
25)
i) int empId
ii) String empName
iii) String email
iv) String gender
v) float salary
vi) void GetEmployeeDetails() -> prints employee details
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 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.
ArithmeticException
NumberFormatException
try {
if (args.length != 5) {
int sum = 0;
sum += numbers[i];
catch (NumberFormatException e) {
catch (ArithmeticException e) {
catch (ArrayIndexOutOfBoundsException e) {
catch (Exception e) {
}
28)
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
this.name = name;
this.taste = taste;
this.size = size;
// Method to be overridden
void eat() {
// Subclass: Apple
Apple(String size) {
@Override
void eat() {
// Subclass: Orange
Orange(String size) {
}
@Override
void eat() {
// Main class
apple.eat();
orange.eat();
}
29)
Given a number N, the task is to count the number of unique digits in the
given number.
Examples:
Explanation: The digits 3 and 4 occurs only once. Hence, the output is 2.
import java.util.Scanner;
scanner.close();
if (Character.isDigit(ch)) {
} else {
int uniqueCount = 0;
if (count == 1) {
uniqueCount++;
30)
int sum = 0;
int target1 = 7;
}
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
Requirements:
Code:
import java.util.*;
this.amount = amount;
this.transactionId = UUID.randomUUID().toString();
}
//subclass CreditCardPayment
super(amount);
this.cardNumber = cardNumber;
this.CVV = CVV;
this.expiryDate = expiryDate;
@Override
System.out.println("Payment successful!");
showTransactionId();
// Subclass: PayPal
super(amount);
this.email = email;
this.password = password;
@Override
// Subclass: UPI
super(amount);
this.upiId = upiId;
@Override
//Processors gateaway
class PaymentGateway {
payment.processPayment();
System.out.println("Payment Successful!\n");
System.out.println("2. PayPal");
System.out.println("3. UPI");
sc.nextLine();
switch (choice) {
case 1:
gateway.processTransaction(ccPayment);
break;
case 2:
gateway.processTransaction(paypal);
break;
case 3:
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.
Circle: π × radius²
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();
}
}
}
Requirements:
1. Create a class BankAccount with the following:
Method:
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).
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.");
}}
Abstract method:
Create a class Student that inherits from Person:
@Override
public void work() {
System.out.println("HR Manager is managing human
resources...");
}
System.out.println(); // spacer