Question 1:
● Create a class Fruit that contains a name attribute for the fruit.
● Create a generic class Bucket that can hold values of any two types.
● Demonstrate in a main function that Bucket can contain:
1. Integers and Strings
2. String and Fruit
3. Integer and Fruit.
// Class Fruit
class Fruit {
private String name;
public Fruit(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Fruit{name='" + name + "'}";
}
}
// Generic Class Bucket
class Bucket<T1, T2> {
private T1 first;
private T2 second;
public Bucket(T1 first, T2 second) {
this.first = first;
this.second = second;
}
public T1 getFirst() {
return first;
}
public T2 getSecond() {
return second;
}
@Override
public String toString() {
return "Bucket{" + "first=" + first + ", second=" + second + '}';
}
}
// Main Class
public class Main {
public static void main(String[] args) {
// Example 1: Integer and String
Bucket<Integer, String> bucket1 = new Bucket<>(42, "Hello");
System.out.println(bucket1);
// Example 2: String and Fruit
Fruit apple = new Fruit("Apple");
Bucket<String, Fruit> bucket2 = new Bucket<>("FruitBucket", apple);
System.out.println(bucket2);
// Example 3: Integer and Fruit
Bucket<Integer, Fruit> bucket3 = new Bucket<>(100, new Fruit("Banana"));
System.out.println(bucket3);
}
}
Question 2:
● Create a Bank class with an attribute money.
● Implement methods for:
1. Adding money
2. Withdrawing money.
● Demonstrate error handling by using a custom exception for scenarios where withdrawal
might fail.
// Custom Exception Class
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
// Bank Class
class Bank {
private double money;
public Bank(double initialMoney) {
this.money = initialMoney;
}
public void addMoney(double amount) {
if (amount > 0) {
money += amount;
System.out.println("Added: $" + amount + ". Current Balance: $" + money);
} else {
System.out.println("Cannot add negative or zero amount.");
}
}
public void withdrawMoney(double amount) throws InsufficientFundsException {
if (amount > money) {
throw new InsufficientFundsException("Insufficient funds! Cannot withdraw $" + amount);
} else if (amount <= 0) {
throw new IllegalArgumentException("Invalid withdrawal amount!");
} else {
money -= amount;
System.out.println("Withdrawn: $" + amount + ". Current Balance: $" + money);
}
}
public double getBalance() {
return money;
}
}
// Main Class
public class Main {
public static void main(String[] args) {
Bank bank = new Bank(500); // Initial balance: $500
try {
bank.addMoney(200); // Add $200
bank.withdrawMoney(100); // Withdraw $100
bank.withdrawMoney(700); // Attempt to withdraw $700
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
System.out.println("Final Balance: $" + bank.getBalance());
}
}
Question 1(a): BankAccount with Custom Exceptions
// Custom Exception for UnderAgeException
class UnderAgeException extends Exception {
public UnderAgeException(String message) {
super(message);
}
}
// Custom Exception for InvalidAmountException
class InvalidAmountException extends RuntimeException {
public InvalidAmountException(String message) {
super(message);
}
}
// BankAccount Class
class BankAccount {
private String username;
private int userAge;
private String accountNumber;
private double initialAmount;
public BankAccount(String username, int userAge, String accountNumber, double
initialAmount) throws UnderAgeException {
if (userAge < 18) {
throw new UnderAgeException("User is under 18 years old. Account creation not
allowed.");
}
this.username = username;
this.userAge = userAge;
this.accountNumber = accountNumber;
this.initialAmount = initialAmount;
}
public void deposit(double amount) {
if (amount <= 0) {
throw new InvalidAmountException("Deposit amount must be greater than zero.");
}
initialAmount += amount;
System.out.println("Deposited: $" + amount + ". Current Balance: $" + initialAmount);
}
public void withdraw(double amount) {
if (amount <= 0) {
throw new InvalidAmountException("Withdrawal amount must be greater than zero.");
} else if (amount > initialAmount) {
throw new InvalidAmountException("Insufficient funds. Cannot withdraw $" + amount);
}
initialAmount -= amount;
System.out.println("Withdrawn: $" + amount + ". Current Balance: $" + initialAmount);
}
}
// Main Class
public class Main {
public static void main(String[] args) {
try {
BankAccount account = new BankAccount("John Doe", 20, "12345", 500.0);
account.deposit(200);
account.withdraw(100);
account.withdraw(700); // Should throw InvalidAmountException
} catch (UnderAgeException e) {
System.out.println(e.getMessage());
} catch (InvalidAmountException e) {
System.out.println(e.getMessage());
}
}
}
Question 2: Division with Exception Handling
import java.util.InputMismatchException;
import java.util.Scanner;
public class DivisionExample {
// Method to divide two numbers
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero.");
}
return a / b;
}
// Method to handle input and call divide method
public static void calculate() {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Enter first number:");
int num1 = scanner.nextInt();
System.out.println("Enter second number:");
int num2 = scanner.nextInt();
int result = divide(num1, num2);
System.out.println("Result: " + result);
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter only integers.");
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
// Main Method
public static void main(String[] args) {
calculate();
}
}
Question 3(a): EOFExample Output When File Does Not Exist
If the example.txt file does not exist, the program will throw a FileNotFoundException,
and the output will be:
BUBT
example.txt (No such file or directory)
Question 3(b): EOFExample Output When File Exists
Given the file contents:
5
12
13
65
23
23
The program reads the first number (5) and loops 5 times, printing each number from the file,
adding 10 to it. The output will be:
BUBT
22
23
75
33
33
Question 1
import java.util.*;
import java.util.stream.Collectors;
public class Day5Assignment {
public static void main(String[] args) {
// List of student IDs for Day 5
List<String> ids = Arrays.asList(
"22234103097", "22234103098", "22234103099", "22234103096", "22234103098",
"22234103097", "22234103099", "18134103095", "18134103096", "22234103097"
);
// Task (a) Find unique IDs
Set<String> uniqueIds = new HashSet<>(ids);
System.out.println("Unique IDs: " + uniqueIds);
// Task (b) Find most senior and most junior batch
Optional<String> mostSeniorBatch = ids.stream()
.min(Comparator.comparingInt(id -> Integer.parseInt(id.substring(0, 3))));
Optional<String> mostJuniorBatch = ids.stream()
.max(Comparator.comparingInt(id -> Integer.parseInt(id.substring(0, 3))));
mostSeniorBatch.ifPresent(s -> System.out.println("Most Senior Batch: " + s.substring(0,
3)));
mostJuniorBatch.ifPresent(s -> System.out.println("Most Junior Batch: " + s.substring(0,
3)));
}
}
Question 2
public class SentenceOperations {
public static void main(String[] args) {
String sentence = "Hello, world! How are you today?";
// Word count
int wordCount = countWords(sentence);
System.out.println("Word Count: " + wordCount);
// Remove punctuation
String cleanSentence = removePunctuation(sentence);
System.out.println("Cleaned Sentence: " + cleanSentence);
}
// Method to count words in a sentence
public static int countWords(String sentence) {
if (sentence == null || sentence.isEmpty()) {
return 0;
}
String[] words = sentence.trim().split("\\s+");
return words.length;
}
// Method to remove punctuation from a sentence
public static String removePunctuation(String sentence) {
if (sentence == null) {
return "";
}
return sentence.replaceAll("[.,!?;:]", "");
}
}
Question 3
import java.util.HashMap;
import java.util.Map;
public class SalaryLookup {
public static void main(String[] args) {
// ShortCode to Name mapping
Map<String, String> shortCodeToName = new HashMap<>();
shortCodeToName.put("JD", "John Doe");
shortCodeToName.put("TS", "Tom Smith");
shortCodeToName.put("RS", "Ralph Smith");
shortCodeToName.put("JB", "Jane Bake");
// Name to Salary mapping
Map<String, Double> nameToSalary = new HashMap<>();
nameToSalary.put("Jane Bake", 200000.00);
nameToSalary.put("Tom Smith", 100000.00);
nameToSalary.put("Ralph Smith", 50000.00);
// Lookup Salary by ShortCode
String shortCode = "TS"; // Example input
Double salary = getSalaryByShortCode(shortCode, shortCodeToName, nameToSalary);
if (salary != null) {
System.out.println("Salary for ShortCode " + shortCode + ": " + salary);
} else {
System.out.println("Salary not found for ShortCode: " + shortCode);
}
}
public static Double getSalaryByShortCode(String shortCode, Map<String, String>
shortCodeToName, Map<String, Double> nameToSalary) {
String name = shortCodeToName.get(shortCode);
if (name != null) {
return nameToSalary.get(name);
}
return null; // Salary not found
}
}
Explanation
1. Question 1:
○ Finds unique student IDs using a HashSet.
○ Determines the senior-most and junior-most batch by extracting the first three
digits of the IDs and comparing them.
2. Question 2:
○ countWords splits the sentence by spaces and counts the words.
○ removePunctuation uses a regular expression to remove punctuation marks.
3. Question 3:
○ Uses Map to relate ShortCode to Name and Name to Salary.
○ Retrieves the salary by resolving the ShortCode to a Name and then looking up
the Salary.
Question 1
You need to:
1. Create a Book class with attributes:
○ title, author, isBorrowed.
2. Create a Library class to:
○ Manage a single book and handle borrowing/returning of books.
3. Define custom exceptions:
○ BookNotAvailableException: Thrown when a user tries to borrow a book
that is already borrowed.
○ BookNotFoundException: Thrown when a user tries to borrow/return a book
not present in the library.
○ InvalidBookOperationException: Thrown when a user tries to return a
book that wasn’t borrowed.
Question 2
Design a Generic Storage System with:
1. A generic class Storage<T>:
○ Stores and manages items of any type.
○ Implements methods:
■ addItem(T item): Adds an item.
■ removeItem(int index): Removes an item at a given index.
2. Demonstrate use cases for storing:
○ Integers, Strings, and custom objects (e.g., Book).
Code Implementation
Question 1: Library System
// Book class
class Book {
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author) {
this.title = title;
this.author = author;
this.isBorrowed = false;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public boolean isBorrowed() {
return isBorrowed;
}
public void borrow() {
this.isBorrowed = true;
}
public void returnBook() {
this.isBorrowed = false;
}
}
// Custom exceptions
class BookNotAvailableException extends Exception {
public BookNotAvailableException(String message) {
super(message);
}
}
class BookNotFoundException extends Exception {
public BookNotFoundException(String message) {
super(message);
}
}
class InvalidBookOperationException extends Exception {
public InvalidBookOperationException(String message) {
super(message);
}
}
// Library class
class Library {
private Book book;
public void addBook(Book book) {
this.book = book;
}
public void borrowBook() throws BookNotAvailableException, BookNotFoundException {
if (book == null) {
throw new BookNotFoundException("Book not found in the library.");
}
if (book.isBorrowed()) {
throw new BookNotAvailableException("Book is already borrowed.");
}
book.borrow();
}
public void returnBook() throws InvalidBookOperationException, BookNotFoundException {
if (book == null) {
throw new BookNotFoundException("Book not found in the library.");
}
if (!book.isBorrowed()) {
throw new InvalidBookOperationException("Book was not borrowed.");
}
book.returnBook();
}
}
// Main class for testing
public class LibrarySystem {
public static void main(String[] args) {
try {
Book book = new Book("The Great Gatsby", "F. Scott Fitzgerald");
Library library = new Library();
library.addBook(book);
library.borrowBook();
System.out.println("Book borrowed successfully.");
library.returnBook();
System.out.println("Book returned successfully.");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Question 2: Generic Storage System
import java.util.ArrayList;
import java.util.List;
// Generic Storage class
class Storage<T> {
private List<T> items = new ArrayList<>();
public void addItem(T item) {
items.add(item);
}
public void removeItem(int index) {
if (index < 0 || index >= items.size()) {
System.out.println("Invalid index.");
return;
}
items.remove(index);
}
public void displayItems() {
for (T item : items) {
System.out.println(item);
}
}
}
// Main class for testing
public class GenericStorageSystem {
public static void main(String[] args) {
// Example 1: Storing integers
Storage<Integer> intStorage = new Storage<>();
intStorage.addItem(10);
intStorage.addItem(20);
intStorage.addItem(30);
System.out.println("Integer storage:");
intStorage.displayItems();
intStorage.removeItem(1);
intStorage.displayItems();
// Example 2: Storing strings
Storage<String> stringStorage = new Storage<>();
stringStorage.addItem("Hello");
stringStorage.addItem("World");
System.out.println("\nString storage:");
stringStorage.displayItems();
// Example 3: Storing custom objects
Storage<Book> bookStorage = new Storage<>();
bookStorage.addItem(new Book("1984", "George Orwell"));
bookStorage.addItem(new Book("To Kill a Mockingbird", "Harper Lee"));
System.out.println("\nBook storage:");
bookStorage.displayItems();
}
}
Explanation
1. Question 1:
○ The Book class manages the attributes and state of a book.
○ The Library class manages a single book and handles exceptions during
borrowing and returning operations.
○ Custom exceptions are thrown for specific error scenarios.
2. Question 2:
○ The Storage<T> class uses a generic type T to handle any type of item.
○ Demonstrates adding and removing integers, strings, and custom objects (Book)
from the storage.
Question 1
Create a custom class Vehicle and a generic class Pair to handle any data type combination.
// Vehicle class
class Vehicle {
private String name;
public Vehicle(String name) {
this.name = name;
@Override
public String toString() {
return "Vehicle{name='" + name + "'}";
// Generic Pair class
class Pair<T, U> {
private T first;
private U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
public T getFirst() {
return first;
public U getSecond() {
return second;
@Override
public String toString() {
return "Pair{" + "first=" + first + ", second=" + second + '}';
// Main class to test the flexibility of Pair
public class GenericPairExample {
public static void main(String[] args) {
// Pair with doubles and booleans
Pair<Double, Boolean> pair1 = new Pair<>(10.5, true);
System.out.println(pair1);
// Pair with strings and Vehicle objects
Pair<String, Vehicle> pair2 = new Pair<>("Car", new Vehicle("Toyota"));
System.out.println(pair2);
// Pair with integers and Vehicle objects
Pair<Integer, Vehicle> pair3 = new Pair<>(100, new Vehicle("Bike"));
System.out.println(pair3);
// Pair with strings and strings
Pair<String, String> pair4 = new Pair<>("Hello", "World");
System.out.println(pair4);
Question 2
Design a FuelStation class with a custom exception for fuel dispensing errors.
// Custom exception
class InsufficientFuelException extends Exception {
public InsufficientFuelException(String message) {
super(message);
// FuelStation class
class FuelStation {
private double fuelAmount;
public FuelStation(double fuelAmount) {
this.fuelAmount = fuelAmount;
public void refuel(double amount) {
fuelAmount += amount;
System.out.println(amount + " liters of fuel added. Current fuel: " + fuelAmount + " liters.");
public void dispenseFuel(double requestedAmount) throws InsufficientFuelException {
if (requestedAmount > fuelAmount) {
throw new InsufficientFuelException("Requested fuel exceeds available fuel. Available: "
+ fuelAmount + " liters.");
fuelAmount -= requestedAmount;
System.out.println(requestedAmount + " liters of fuel dispensed. Remaining fuel: " +
fuelAmount + " liters.");
// Main class to test FuelStation
public class FuelStationExample {
public static void main(String[] args) {
FuelStation station = new FuelStation(100.0);
try {
// Refueling
station.refuel(50.0);
// Dispensing fuel
station.dispenseFuel(120.0); // Should throw an exception
} catch (InsufficientFuelException e) {
System.out.println("Error: " + e.getMessage());
try {
// Dispensing valid amount
station.dispenseFuel(80.0);
} catch (InsufficientFuelException e) {
System.out.println("Error: " + e.getMessage());
Explanation
1. Question 1:
○ The Vehicle class stores the name of a vehicle.
○ The generic Pair<T, U> class allows pairing two objects of any type.
○ Demonstrates flexibility by creating pairs with various data type combinations.
2. Question 2:
○ The FuelStation class manages the fuel amount and handles fuel dispensing
and refueling.
○ Throws a custom exception (InsufficientFuelException) if requested fuel
exceeds available fuel.
○ Demonstrates exception handling during fuel operations.