Java MTE Solutions 1to60
Java MTE Solutions 1to60
Explain the key features of Object-Oriented Programming (OOP) and how they are
implemented in Java. Provide examples for at least two features.
Object oriented programming can be defined as a programming model, which is based upon the
concept of object .Object contain data in the form of attributes and code in the form of method.
The key features of object oriented programming are:
• Encapsulation:- Encapsulation is a concept in object oriented programming that involves
bundling data and method into a single unit. Encapsulation. Can be used to hide data members
, data function and method.
• Inheritance:- Inheritance allows us to define a class that inherits all the methods and
properties from another class.
• Polymorphism :- Polymorphism is considered one of the important features of Object-Oriented
Programming. Polymorphism allows us to perform a single action in different ways.
• Abstraction:- Abstraction in Java is the process in which we only show essential
details/functionality to the user. The non-essential implementation details are not displayed to
the user.
• Inheritance • Polymorphism
class Animal { class Calculator {
void eat() { public int add(int a, int b) {
System.out.println("This animal eats food."); return a + b;
} }
} public double add(double a, double b) {
return a + b;
class Dog extends Animal { }
void bark() { }
System.out.println("The dog barks.");
} public class Main {
} public static void main(String[] args) {
Calculator calculator = new Calculator();
public class Main {
public static void main(String[] args) { System.out.println("Sum of integers 5 and 10: " +
calculator.add(5, 10));
Dog dog = new Dog();
dog.eat(); // Inherited from Animal class
System.out.println("Sum of doubles 5.5 and 10.5: " +
dog.bark(); // Defined in Dog class calculator.add(5.5, 10.5));
} }
} }
2.Differentiate between JDK, JVM, and JRE. Illustrate their roles in Java program execution.
// Overloaded method 1: Adds two integers public static void main(String[] args) {
// Overloaded method 2: Adds three integers System.out.println("Sum of two integers: " + sum1);
public int add(int a, int b, int c) { // Calling the method to add three integers
// Overloaded method 3: Concatenates two strings // Calling the method to concatenate two strings
public String add(String str1, String str2) { String concatenated = demo.add("Hello, ", "World!");
return str1 + str2;
System.out.println("Concatenated string: " + concatenated);
}
} Output: Sum of two integers: 30
} Sum of three integers: 60
}
Concatenated string: Hello, World!
6.Create a Java class with both static and non-static members. Write a program to call these
members from the main method and explain the difference between their behavior.
public class StaticNonStaticDemo { // Non-static method
public void incrementInstanceCounter() {
// Static member instanceCounter++;
static int staticCounter = 0; System.out.println("Instance Counter: " +
instanceCounter);
// Non-static member }
public static void main(String[] args) {
int instanceCounter = 0;
// Call static member using the class name
// Static method
StaticNonStaticDemo.incrementStaticCounter();
public static void incrementStaticCounter() {
staticCounter++;
// Create an object to call non-static members
System.out.println("Static Counter: " + staticCounter);
StaticNonStaticDemo obj1 = new
} StaticNonStaticDemo();
obj1.incrementInstanceCounter();
// Create another object and call non-static method
obj2.incrementInstanceCounter();
Output:-
Static Counter: 1
Instance Counter: 1
Instance Counter: 1
Final Static Counter: 1
8. Develop a Java program that creates a user-defined exception to handle invalid input for a specific scenario (e.g., age below 18
for voting). Include a try-catch block to handle the exception.
// User-defined exception class public static void main(String[] args) {
class InvalidAgeException extends Exception { try {
public InvalidAgeException(String message) { // Example input: Replace 16 with any age to test
super(message); int age = 16;
} checkAge(age);
} } catch (InvalidAgeException e) {
System.out.println("Caught an exception: " + e.getMessage());
public class VotingEligibility { }
// Method to check age for voting eligibility }
public static void checkAge(int age) throws InvalidAgeException { }
if (age < 18) { Output:
throw new InvalidAgeException("Age must be 18 or above to Input: age=16
vote.");
Output: Caught an exception: Age must be 18 or above to vote
}
Input: age=20
System.out.println("You are eligible to vote.");
Output: You are eligible to vote.
}
9.Explain the difference between `abstract` classes and `interfaces` in Java. Write a Java program to implement an `Interface` and
demonstrate how a class can implement multiple interfaces. Include methods from each interface and call them in the main
method.
interface Shape { }
void draw(); }
} circle.draw();
@Override }
HashMap Demonstration:
Employees: {101=Alice, 102=Bob, 103=Charlie}
After removing employee with ID 102: {101=Alice, 103=Charlie}
Iterating over HashMap:
ID: 101, Name: Alice
ID: 103, Name: Charlie
Q. Design a Java program to demonstrate linked structures by implementing a simple singly
linked list with operations like add, delete, and display.
{
class Node {
current = current.next;
int data;
}
Node next;
current.next = newNode;
}
// Constructor to create a new node
}
public Node(int data) {
this.data = data;
// Method to delete a node by value
this.next = null;
public void delete(int data) {
}
if (head == null) {
}
System.out.println("List is empty. Cannot delete.");
return;
class SinglyLinkedList {
}
private Node head;
// If the node to be deleted is the head
// Method to add a new node at the end of the list
if (head.data == data) {
public void add(int data) {
head = head.next;
Node newNode = new Node(data);
return;
if (head == null) {
}
head = newNode;
} else {
Node current = head;
Node current = head;
Vivek Node previous = null;
while (current.next != null)
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
while (current != null && current.data != data) {
}
previous = current;
System.out.println("null");
current = current.next;
}
}
}
if (current == null) {
public class LinkedListDemo {
System.out.println("Node with value " + data + " not found.");
public static void main(String[] args) {
return;
SinglyLinkedList list = new SinglyLinkedList();
}
// Adding nodes to the linked list
previous.next = current.next; // Bypass the current node
list.add(10);
}
list.add(20);
list.add(30);
// Method to display the linked list
list.display(); // Displaying the list
public void display() {
if (head == null) {
// Deleting a node
System.out.println("List is empty.");
list.delete(20);
return;
list.display(); // Displaying the list after deletion
}
// Attempting to delete a node that doesn't exist
Node current = head; Vivek list.delete(40); // Node not found
// Deleting the head node
list.delete(10);
list.display(); // Displaying the list after deleting head
}
}
Q. Write a Java program to implement exception handling strategies by demonstrating the use of `try-catch-finally`
and `throws` keywords with a scenario involving division by zero.
// Method that performs division and throws an exception if there is an attempt to divide by zero
public static double divide(int numerator, int denominator) throws ArithmeticException {
if (denominator == 0) {
throw new ArithmeticException("Denominator cannot be zero.");
}
return (double) numerator / denominator;
}
try {
// Attempt to perform division finally {
double result = divide(numerator, denominator); System.out.println("Execution of the second try-
System.out.println("Result: " + result); catch block is complete.");
} catch (ArithmeticException e) { }
// Catch the exception and handle it }
System.out.println("Error: " + e.getMessage()); }
} finally {
// This block will execute regardless of whether an exception occurred or not
System.out.println("Execution of the try-catch block is complete.");
}
try {
double result = divide(numerator, denominator);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} Vivek
Q. Write a Java program to create multiple threads and assign different priorities to them. Observe and explain
the impact of thread priority on their execution order.
@Override
public void run() {
// Simulating some work with a sleep
try {
System.out.println("Thread " + threadNumber + " with priority " + this.getPriority() + " is starting.");
Thread.sleep(1000); // Simulate some work
System.out.println("Thread " + threadNumber + " with priority " + this.getPriority() + " is finished.");
} catch (InterruptedException e) {
System.out.println("Thread " + threadNumber + " was interrupted.");
}
}
Vivek
}
public class ThreadPriorityExample {
public static void main(String[] args) {
// Creating threads with different priorities
PriorityThread thread1 = new PriorityThread(1); // Wait for all threads to finish
PriorityThread thread2 = new PriorityThread(2); try {
PriorityThread thread3 = new PriorityThread(3); thread1.join();
PriorityThread thread4 = new PriorityThread(4); thread2.join();
PriorityThread thread5 = new PriorityThread(5); thread3.join();
thread4.join();
// Setting priorities thread5.join();
thread1.setPriority(Thread.MIN_PRIORITY); // 1 } catch (InterruptedException e) {
thread2.setPriority(Thread.NORM_PRIORITY); // 5 System.out.println("Main thread was interrupted.");
thread3.setPriority(Thread.NORM_PRIORITY); // 5 }
thread4.setPriority(Thread.MAX_PRIORITY); // 10
thread5.setPriority(Thread.NORM_PRIORITY); // 5 System.out.println("All threads have finished execution.");
}
// Starting threads }
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
Vivek
Explanation:
Vivek
Q.Write a Java program to demonstrate the use of generic collections by implementing a `HashMap` to store and
retrieve student details (e.g., roll number and name). Include operations to add, remove, and search for students.
"Student{" + "rollNumber='" + rollNumber + '\'' +", name='" + name
import java.util.HashMap;
+ '\'' +'}';
import java.util.Scanner;
}
}
class Student {
public class StudentManagement {
private String rollNumber;
private HashMap<String, Student> studentMap;
private String name;
public StudentManagement() {
public Student(String rollNumber, String name) {
studentMap = new HashMap<>();
this.rollNumber = rollNumber;
}
this.name = name;
// Method to add a student
}
public void addStudent(String rollNumber, String name) {
Student student = new Student(rollNumber, name);
public String getRollNumber() {
studentMap.put(rollNumber, student);
return rollNumber;
System.out.println("Student added: " + student);
}
}
public String getName() {
// Method to remove a student
return name;
public void removeStudent(String rollNumber) {
}
if (studentMap.containsKey(rollNumber)) {
@Override
Student removedStudent =
public String toString() {
studentMap.remove(rollNumber);
return Vivek System.out.println("Removed student: " + removedStudent);
} else {
System.out.println("No student found with roll number: " + rollNumber);
}
}
do {
System.out.println("\nStudent Management System");
Vivek
System.out.println("1. Add Student");
System.out.println("2. Remove Student");
System.out.println("3. Search Student");
System.out.println("4. Exit");
management.searchStudent(rollNumber);
System.out.print("Enter your choice: ");
break;
choice = scanner.nextInt();
case 4:
scanner.nextLine(); // Consume newline
System.out.println("Exiting...");
break;
switch (choice) {
default:
case 1:
System.out.println("Invalid choice. Please try agai
System.out.print("Enter roll number: ");
}
String rollNumber = scanner.nextLine();
} while (choice != 4);
System.out.print("Enter name: ");
String name = scanner.nextLine();
scanner.close();
management.addStudent(rollNumber, name);
}
break;
}
case 2:
System.out.print("Enter roll number to remove: ");
rollNumber = scanner.nextLine();
management.removeStudent(rollNumber);
break;
case 3:
System.out.print("Enter roll number to search: ");
rollNumber = scanner.nextLine(); Vivek
Q. What is method overriding in Java? What is basic Difference between Overriding and Overloading?
If any error occurs, can be caught at If any error occurs, can be caught at
8)
compile-time. run-time.
In case of method
In case of method overriding, parameter
3) overloading, parameter must be
must be same.
different.
It is applicable to both private and final It is not applicable to private and
9)
methods. final methods.
Vivek
// Step 1: Define the custom exception class
class InvalidTransactionException extends Exception {
public InvalidTransactionException(String message) {
super(message);
}
}
try {
bank.withdraw(-50.00); // Invalid transaction (negative amount)
} catch (InvalidTransactionException e) { Vivek
System.out.println("Transaction failed: " + e.getMessage()); }
Q. Differentiate between `Set` and `List` in the Java Collections Framework. Write a program to demonstrate their
usage by storing and iterating over elements.
22. Explain the concept of object serialization in Java. Write a program to serialize and
deserialize an object of a custom class that stores employee details.
Sol.
Serialization is the process of converting an object's state into a byte stream, which can be stored in a file, sent over
a network, or persisted for later use. The reverse process of restoring the object from the byte stream is called
deserialization.
Key Points:
1. Purpose: Serialization is used to save the state of an object or transfer it over a network.
2. Serializable Interface: A class must implement the java.io.Serializable interface to be serializable. This is a
marker interface, meaning it does not have any methods.
3. transient Keyword: Fields marked as transient are not serialized.
4. serialVersionUID: A unique identifier that ensures the class's compatibility during deserialization. If the class
structure changes, deserialization may fail without matching serialVersionUID.
23. Create a menu based calculator to perform various operations.
Sol.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("Menu-based Calculator");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
if (choice == 5) {
System.out.println("Calculator exited.");
break;
}
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
switch (choice) {
case 1:
System.out.println("Result: " + (num1 + num2));
break;
case 2:
System.out.println("Result: " + (num1 - num2));
break;
case 3:
System.out.println("Result: " + (num1 * num2));
break;
case 4:
if (num2 != 0) {
System.out.println("Result: " + (num1 / num2));
} else {
System.out.println("Error: Division by zero is not allowed.");
}
break;
default:
System.out.println("Invalid choice. Please try again.");
}
System.out.println();
} while (choice != 5);
scanner.close();
}
}
24. Write a Java program to design the patterns
Pattern 1.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
Pattern 2.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
}
}
Pattern 3.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.println();
}
}
}
Pattern 4.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print((char) ('A' + i - 1));
}
System.out.println();
}
}
}
Pattern 5.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (char ch = 'A'; ch < 'A' + i; ch++) {
System.out.print(ch);
}
System.out.println();
}
}
}
Pattern 6.
public class Main {
public static void main(String[] args) {
int first = 1, second = 1;
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}
System.out.println();
}
}
}
Pattern 7.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.print("0");
for (int j = 0; j < i; j++) {
if (j==0) {
System.out.print(j+1);
} else {
System.out.print(j);
}
}
System.out.println();
}
}
}
Pattern 8.
public class Main {
public static void main(String[] args) {
int start = 1;
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
if (start == 10) {
start = 1;
}
System.out.print(start);
start++;
}
System.out.println();
}
}
}
Pattern 9.
public class Main {
public static void main(String[] args) {
int n = 1;
for (int i = 1; i <= 5; i++) {
int a = 0, b = 4;
for (int j = 1; j<=i; j++) {
int s = i+a;
System.out.print(s);
a = a+b;
b--;
}
System.out.println();
}
}
}
Pattern 10.
public class Main {
public static void main(String[] args) {
int odd = 1;
int even = 2;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j<=i; j++) {
if (i%2==0) {
System.out.print(even);
even+=2;
} else {
System.out.print(odd);
odd+=2;
}
}
odd = 1;
even = 2;
System.out.println();
}
}
}
Pattern 11.
public class Main {
public static void main(String[] args) {
int count = 1;
for (int i = 1; i <= 4; i++) {
int[] rowNumbers = new int[i];
for (int j = 0; j < i; j++) {
rowNumbers[j] = count++;
}
for (int j = i - 1; j >= 0; j--) {
System.out.print(rowNumbers[j] + " ");
}
System.out.println();
}
}
}
Pattern 12.
public class Main {
public static void main(String[] args) {
int n = 3;
int x = 1;
int y = 1;
int z = 1;
for (int i = 0; i < n; i++) {
for (int k = n - 1; k >= i; k--) {
System.out.print(" ");
}
for (int j = 0; j < y; j++) {
if (i == j) {
z = (x + 1) * (j + j);
z = (z == 0) ? 1 : z;
System.out.print(" " + z);
continue;
}
x = x + 2;
System.out.print(" " + x);
}
y = y + 2;
System.out.println();
}
}
}
25. Write a java program to take temperature at command line in Celsius and convert in
Fahrenheit.
Sol.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Please provide a temperature in Celsius.");
return;
}
try {
double celsius = Double.parseDouble(args[0]);
double fahrenheit = (celsius * 9/5) + 32;
System.out.println(celsius + "°C is equal to " + fahrenheit + "°F");
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please provide a valid number for Celsius.");
}
}
}
26. Write a java program to find the number of and sum of all integers greater than 50 and
less than 100 and are prime numbers.
Sol.
public class Main {
public static void main(String[] args) {
int count = 0;
int sum = 0;
for (int num = 51; num < 100; num++) {
if (isPrime(num)) {
count++;
sum += num;
}
}
System.out.println("Count of prime numbers: " + count);
System.out.println("Sum of prime numbers: " + sum);
}
public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
27. Write a Java program to insert an element (specific position) into an array.
Sol.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = {10, 20, 30, 40, 50};
System.out.println("Original array:");
printArray(arr);
System.out.print("Enter the element to insert: ");
int element = scanner.nextInt();
System.out.print("Enter the position where the element should be inserted: ");
int position = scanner.nextInt();
arr = insertElement(arr, element, position);
System.out.println("Array after insertion:");
printArray(arr);
}
public static int[] insertElement(int[] arr, int element, int position) {
if (position < 0 || position > arr.length) {
System.out.println("Invalid position.");
return arr;
}
int[] newArr = new int[arr.length + 1];
for (int i = 0; i < position; i++) {
newArr[i] = arr[i];
}
newArr[position] = element;
for (int i = position; i < arr.length; i++) {
newArr[i + 1] = arr[i];
}
return newArr;
}
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}
29. Write a Java program to find the second largest element in a 2D array.
Sol.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] arr = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
System.out.println("Original 2D array:");
print2DArray(arr);
int secondLargest = findSecondLargest(arr);
System.out.println("Second largest element: " + secondLargest);
}
public static int findSecondLargest(int[][] arr) {
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int[] row : arr) {
for (int num : row) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num != largest) {
secondLargest = num;
}
}
}
return secondLargest;
}
public static void print2DArray(int[][] arr) {
for (int[] row : arr) {
System.out.println(Arrays.toString(row));
}
}
}
30. Write a Java recursive method to check if a given array is sorted in ascending order.
Sol.
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
if (isSorted(arr, 0)) {
System.out.println("The array is sorted in ascending order.");
} else {
System.out.println("The array is not sorted in ascending order.");
}
}
public static boolean isSorted(int[] arr, int index) {
if (index == arr.length - 1) {
return true;
}
if (arr[index] > arr[index + 1]) {
return false;
}
return isSorted(arr, index + 1);
}
}
31.Write a Java program to create a class called Circle with a private instance variable
radius. Provide public getter and setter methods to access and modify the radius variable.
However, provide two methods called calculateArea() and calculatePerimeter() that
return the calculated area and perimeter based on the current radius value.
Solution:
32.Write a Java program to compare two strings lexicographically.Two strings are lexicographically equal if they are
the same length and contain the same characters in the same positions.
Solution:
import java.util.Scanner;
if (result == 0) {
System.out.println("The strings are lexicographically equal.");
} else if (result < 0) {
System.out.println("The first string is lexicographically less than the second string.");
} else {
System.out.println("The first string is lexicographically greater than the second string.");
}
33.Write a java program to take a string from user in which words are separated using spaces. Tokenize the string
using space delimiter and find whether India word is there in the token list or not.
Solution:
import java.util.Scanner;
import java.util.StringTokenizer;
// Create a StringTokenizer to split the sentence into tokens using space as a delimiter
StringTokenizer tokenizer = new StringTokenizer(sentence);
// Output result
if (foundIndia) {
System.out.println("\"India\" is present in the sentence.");
} else {
System.out.println("\"India\" is not present in the sentence.");
}
34.Write a Java program that creates a bank account with concurrent deposits and withdrawals using threads.
Solution:
class BankAccount {
private double balance;
@Override
public void run() {
account.deposit(amount);
}
}
try {
// Wait for all threads to finish
deposit1.join();
withdraw1.join();
deposit2.join();
withdraw2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
35.Design a class named Circle. Construct three circle objects with radius 3.0, 3.2 4.1 and display the radius and
area of each. A no-arg constructor set the default value of radius to 1. A getArea() function is used to return the
area of circle. Now implement the class.
Solution:
public class Circle {
// Instance variable for radius
private double radius;
36. Write a Java program to create a class with methods to search for flights and hotels, and to book and cancel
reservations.
Solution:
import java.util.*;
class Flight {
private String flightNumber;
private String departure;
private String destination;
private double price;
@Override
public String toString() {
return "Flight Number: " + flightNumber + ", Departure: " + departure + ", Destination: " + destination + ", Price:
$" + price;
}
}
class Hotel {
private String name;
private String city;
private double pricePerNight;
@Override
public String toString() {
return "Hotel Name: " + name + ", City: " + city + ", Price per Night: $" + pricePerNight;
}
}
class TravelAgency {
private List<Flight> flights;
private List<Hotel> hotels;
private Set<String> bookedFlights;
private Set<String> bookedHotels;
public TravelAgency() {
flights = new ArrayList<>();
hotels = new ArrayList<>();
bookedFlights = new HashSet<>();
bookedHotels = new HashSet<>();
// Search Flights
public void searchFlights(String departure, String destination) {
System.out.println("\nAvailable Flights from " + departure + " to " + destination + ":");
for (Flight flight : flights) {
if (flight.getDeparture().equalsIgnoreCase(departure) &&
flight.getDestination().equalsIgnoreCase(destination)) {
System.out.println(flight);
}
}
}
// Search Hotels
public void searchHotels(String city) {
System.out.println("\nAvailable Hotels in " + city + ":");
for (Hotel hotel : hotels) {
if (hotel.getCity().equalsIgnoreCase(city)) {
System.out.println(hotel);
}
}
}
// Book Flight
public void bookFlight(String flightNumber) {
for (Flight flight : flights) {
if (flight.getFlightNumber().equalsIgnoreCase(flightNumber)) {
if (bookedFlights.contains(flightNumber)) {
System.out.println("\nFlight " + flightNumber + " is already booked.");
} else {
bookedFlights.add(flightNumber);
System.out.println("\nFlight " + flightNumber + " booked successfully!");
}
return;
}
}
System.out.println("\nFlight " + flightNumber + " not found.");
}
// Book Hotel
public void bookHotel(String hotelName) {
for (Hotel hotel : hotels) {
if (hotel.getName().equalsIgnoreCase(hotelName)) {
if (bookedHotels.contains(hotelName)) {
System.out.println("\nHotel " + hotelName + " is already booked.");
} else {
bookedHotels.add(hotelName);
System.out.println("\nHotel " + hotelName + " booked successfully!");
}
return;
}
}
System.out.println("\nHotel " + hotelName + " not found.");
}
// Search Flights
agency.searchFlights("New York", "London");
// Search Hotels
agency.searchHotels("Paris");
// Book a flight
agency.bookFlight("AA123");
agency.bookFlight("AA123"); // Attempt to book again
// Book a hotel
agency.bookHotel("Hotel Luxe");
agency.bookHotel("Hotel Luxe"); // Attempt to book again
37.Write a Java programming to create a banking system with three classes - Bank, Account, SavingsAccount, and
CurrentAccount. The bank should have a list of accounts and methods for adding them. Accounts should be an
interface with methods to deposit, withdraw, calculate interest, and view balances. SavingsAccount and
CurrentAccount should implement the Account interface and have their own unique methods.
Solution:
import java.util.*;
// Account interface
interface Account {
void deposit(double amount);
void withdraw(double amount);
double calculateInterest();
void viewBalance();
}
public Bank() {
accounts = new ArrayList<>();
}
38.Write a Java program to create an abstract class Employee with abstract methods calculateSalary() and
displayInfo(). Create subclasses Manager and Programmer that extend the Employee class and implement the
respective methods to calculate salary and display information for each role.
Solution:
// Abstract class Employee
abstract class Employee {
String name;
int id;
double salary;
// Subclass Manager
class Manager extends Employee {
int numberOfTeamMembers;
// Subclass Programmer
class Programmer extends Employee {
int hoursWorked;
// Calculating salaries
manager.calculateSalary();
programmer.calculateSalary();
// Displaying information
manager.displayInfo();
programmer.displayInfo();
}
}
39. Write a Java program to create a method that takes an integer as a parameter and throws an exception if the
number is odd.
Solution:
// Custom exception class for OddNumberException
class OddNumberException extends Exception {
public OddNumberException(String message) {
super(message); // Passing the message to the parent class Exception
}
}
41.Write a JAVA Program to demonstrate Constructor overloading and Method overloading. Also access
parent class constructor in child class
Solution:
// Parent class
class Parent {
// Parent class constructor
public Parent() {
System.out.println("Parent class default constructor.");
}
// Child class
class Child extends Parent {
// Constructor overloading in child class
public Child() {
super("Hello from Parent class!"); // Access parent class constructor
System.out.println("Child class default constructor.");
}
// Main class
public class OverloadingExample {
public static void main(String[] args) {
// Calling constructor overload
System.out.println("Creating first child object:");
Child child1 = new Child(); // Calls default constructor of Child class
42.Write a Java method that checks whether all the characters in a given string are vowels
(a, e,i,o,u) or not. Return true if each character in the string is a vowel, otherwise return
false.
Sol.
import java.util.Scanner;
public class Main {
public static boolean areAllCharactersVowels(String str) {
if (str == null || str.isEmpty()) {
return false;
}
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(areAllCharactersVowels(str));
}
}
43.Write a Java program in which inherit one abstract class and implement methods of 3
interfaces. One interface is containing default method and static method.
Sol.
abstract class AbstractClass {
public abstract void abstractMethod();
}
interface InterfaceOne {
default void defaultMethod() {
System.out.println("This is a default method in InterfaceOne.");
}
static void staticMethod() {
System.out.println("This is a static method in InterfaceOne.");
}
}
interface InterfaceTwo {
void methodFromInterfaceTwo();
}
interface InterfaceThree {
void methodFromInterfaceThree();
}
public class ConcreteClass extends AbstractClass implements InterfaceOne, InterfaceTwo, InterfaceThree {
@Override
public void abstractMethod() {
System.out.println("Implemented abstract method from AbstractClass.");
}
@Override
public void methodFromInterfaceTwo() {
System.out.println("Implemented method from InterfaceTwo.");
}
@Override
public void methodFromInterfaceThree() {
System.out.println("Implemented method from InterfaceThree.");
}
public void display() {
System.out.println("ConcreteClass method.");
}
public static void main(String[] args) {
ConcreteClass obj = new ConcreteClass();
obj.abstractMethod();
obj.methodFromInterfaceTwo();
obj.methodFromInterfaceThree();
obj.defaultMethod();
InterfaceOne.staticMethod();
obj.display();
}
}
44. Create a class Student (name, roll_no, marks) with one method show() and initialize
instance variables using all the ways: reference, method and constructor.
Sol.
class Student {
String name;
int roll_no;
double marks;
public Student(String name, int roll_no, double marks) {
this.name = name;
this.roll_no = roll_no;
this.marks = marks;
}
public void initializeUsingMethod(String name, int roll_no, double marks) {
this.name = name;
this.roll_no = roll_no;
this.marks = marks;
}
public void show() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + roll_no);
System.out.println("Marks: " + marks);
}
public static void main(String[] args) {
Student student1 = new Student("Alice", 101, 89.5);
System.out.println("Student 1 initialized using constructor:");
student1.show();
Student student2 = new Student("", 0, 0);
student2.initializeUsingMethod("Bob", 102, 92.0);
System.out.println("\nStudent 2 initialized using method:");
student2.show();
Student student3 = new Student("", 0, 0);
student3.name = "Charlie";
student3.roll_no = 103;
student3.marks = 85.5;
System.out.println("\nStudent 3 initialized using reference:");
student3.show();
}
}
45. Discuss the various access specifiers in Java. Create 2 packages P1 & P2 and create
classes Student and BTech in P1 and P2 respectively. Check the accessibility of 3 methods
of the package p1 into package p2. Access specifier of one method is private, one is
protected and third one is default.
Sol.
package P1;
public class Student {
private void privateMethod() {
System.out.println("Private method in Student");
}
protected void protectedMethod() {
System.out.println("Protected method in Student");
}
void defaultMethod() {
System.out.println("Default method in Student");
}
public void publicMethod() {
System.out.println("Public method in Student");
}
}
package P2;
import P1.Student;
public class BTech {
public static void main(String[] args) {
Student student = new Student();
// student.privateMethod(); // Not accessible
student.protectedMethod(); // Accessible (if extended)
// student.defaultMethod(); // Not accessible
student.publicMethod(); // Accessible
}
}
46. Write a Java program to get a substring of a given string at two specified positions.
Sol.
public class Main {
public static String getSubstring(String str, int start, int end) {
if (start < 0 || end > str.length() || start > end) {
return "Invalid positions";
}
return str.substring(start, end);
}
public static void main(String[] args) {
String str = "Hello, Java Programming!";
int start = 7;
int end = 11;
String result = getSubstring(str, start, end);
System.out.println("Substring: " + result);
}
}
47. What will be the output of the following code Inner Class.
Inner Class
class X {
static int x = 3131;
static class Y {
static int y = x++;
static class Z {
static int z = y++;
}
}
}
public class Main {
public static void main(String[] args) {
System.out.println(X.x);
System.out.println(X.Y.y);
System.out.println(X.Y.Z.z);
}
}
Sol.
3131
3131
3131
48. Write a Java program to create an abstract class Employee with abstract methods
calculateSalary() and displayInfo(). Create subclasses Manager and Programmer that
extend the Employee class and implement the respective methods to calculate salary and
display information for each role.
Sol.
abstract class Employee {
String name;
int age;
String role;
public Employee(String name, int age, String role) {
this.name = name;
this.age = age;
this.role = role;
}
public abstract double calculateSalary();
public abstract void displayInfo();
}
class Manager extends Employee {
double baseSalary;
double bonus;
public Manager(String name, int age, double baseSalary, double bonus) {
super(name, age, "Manager");
this.baseSalary = baseSalary;
this.bonus = bonus;
}
@Override
public double calculateSalary() {
return baseSalary + bonus;
}
@Override
public void displayInfo() {
System.out.println("Manager Info:");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Role: " + role);
System.out.println("Base Salary: " + baseSalary);
System.out.println("Bonus: " + bonus);
System.out.println("Total Salary: " + calculateSalary());
}
}
class Programmer extends Employee {
double baseSalary;
double overtimePay;
public Programmer(String name, int age, double baseSalary, double overtimePay) {
super(name, age, "Programmer");
this.baseSalary = baseSalary;
this.overtimePay = overtimePay;
}
@Override
public double calculateSalary() {
return baseSalary + overtimePay;
}
@Override
public void displayInfo() {
System.out.println("Programmer Info:");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Role: " + role);
System.out.println("Base Salary: " + baseSalary);
System.out.println("Overtime Pay: " + overtimePay);
System.out.println("Total Salary: " + calculateSalary());
}
}
public class Main {
public static void main(String[] args) {
Manager manager = new Manager("Alice", 35, 80000, 10000);
manager.displayInfo();
System.out.println("\n--------------------------------\n");
Programmer programmer = new Programmer("Bob", 28, 60000, 5000);
programmer.displayInfo();
}
}
49. Write a Java program to create an interface Shape with the getArea() method. Create
three classes Rectangle, Circle, and Triangle that implement the Shape interface.
Implement the getArea() method for each of the three classes.
Sol.
interface Shape {
double getArea();
}
class Rectangle implements Shape {
double length;
double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
}
class Circle implements Shape {
double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
class Triangle implements Shape {
double base;
double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
public class Main {
public static void main(String[] args) {
Shape rectangle = new Rectangle(5, 3);
Shape circle = new Circle(4);
Shape triangle = new Triangle(6, 4);
50. Write a Java programming to create a banking system with three classes - Bank,
Account, SavingsAccount, and CurrentAccount. The bank should have a list of accounts
and methods for adding them. Accounts should be an interface with methods to deposit,
withdraw, calculate interest, and view balances. SavingsAccount and CurrentAccount
should implement the Account interface and have their own unique methods.
Sol.
import java.util.ArrayList;
import java.util.List;
interface Account {
void deposit(double amount);
void withdraw(double amount);
void calculateInterest();
double getBalance();
void displayAccountDetails();
}
class SavingsAccount implements Account {
private double balance;
private final double interestRate = 0.04; // 4% interest rate for savings
public SavingsAccount(double initialDeposit) {
this.balance = initialDeposit;
}
@Override
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrew: " + amount);
} else {
System.out.println("Insufficient balance.");
}
}
@Override
public void calculateInterest() {
double interest = balance * interestRate;
balance += interest;
System.out.println("Interest added: " + interest);
}
@Override
public double getBalance() {
return balance;
}
@Override
public void displayAccountDetails() {
System.out.println("Savings Account - Balance: " + balance);
}
}
class CurrentAccount implements Account {
private double balance;
private final double overdraftLimit = 5000; // Overdraft limit
public CurrentAccount(double initialDeposit) {
this.balance = initialDeposit;
}
@Override
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
@Override
public void withdraw(double amount) {
if (balance - amount >= -overdraftLimit) {
balance -= amount;
System.out.println("Withdrew: " + amount);
} else {
System.out.println("Exceeded overdraft limit.");
}
}
@Override
public void calculateInterest() {
// No interest for current account
System.out.println("No interest for current account.");
}
@Override
public double getBalance() {
return balance;
}
@Override
public void displayAccountDetails() {
System.out.println("Current Account - Balance: " + balance);
}
}
class Bank {
private List<Account> accounts;
public Bank() {
accounts = new ArrayList<>();
}
public void addAccount(Account account) {
accounts.add(account);
System.out.println("Account added.");
}
public void showAccountDetails() {
for (Account account : accounts) {
account.displayAccountDetails();
}
}
public void calculateAllInterest() {
for (Account account : accounts) {
account.calculateInterest();
}
}
}
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();
SavingsAccount savingsAccount = new SavingsAccount(1000);
savingsAccount.deposit(500);
savingsAccount.withdraw(200);
savingsAccount.calculateInterest();
CurrentAccount currentAccount = new CurrentAccount(2000);
currentAccount.deposit(1000);
currentAccount.withdraw(2500);
bank.addAccount(savingsAccount);
bank.addAccount(currentAccount);
System.out.println("\nAccount details after transactions:");
bank.showAccountDetails();
System.out.println("\nCalculating interest for all accounts:");
bank.calculateAllInterest();
System.out.println("\nAccount details after interest calculation:");
bank.showAccountDetails();
}
}
51. Write a Java program to create a method that takes an integer as a parameter and
throws an exception if the number is odd.
Sol.
class OddNumberException extends Exception {
public OddNumberException(String message) {
super(message);
}
}
public class Main {
public static void checkEvenNumber(int number) throws OddNumberException {
if (number % 2 != 0) {
throw new OddNumberException("The number " + number + " is odd. Exception thrown.");
} else {
System.out.println("The number " + number + " is even.");
}
}
public static void main(String[] args) {
try {
checkEvenNumber(10); // Even number
checkEvenNumber(7); // Odd number
} catch (OddNumberException e) {
System.out.println(e.getMessage());
}
}
}
52. Create a user defined exception “UnderageforVoting” exception and throw it when
voter’s age is below 18.
Sol.
class UnderageForVoting extends Exception {
public UnderageForVoting(String message) {
super(message);
}
}
public class Main {
public static void checkVotingEligibility(int age) throws UnderageForVoting {
if (age < 18) {
throw new UnderageForVoting("Age is below 18. You are not eligible to vote.");
} else {
System.out.println("You are eligible to vote.");
}
}
public static void main(String[] args) {
int voterAge = 16;
try {
checkVotingEligibility(voterAge);
} catch (UnderageForVoting e) {
System.out.println(e.getMessage());
}
}
}
53. Write a Java program that creates a bank account with concurrent deposits and
withdrawals using threads.
Sol.
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public synchronized void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount + ", New Balance: " + balance);
}
public synchronized void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrew: " + amount + ", New Balance: " + balance);
} else {
System.out.println("Insufficient funds for withdrawal of: " + amount);
}
}
public double getBalance() {
return balance;
}
}
class DepositThread extends Thread {
private BankAccount account;
private double amount;
public DepositThread(BankAccount account, double amount) {
this.account = account;
this.amount = amount;
}
@Override
public void run() {
account.deposit(amount);
}
}
class WithdrawThread extends Thread {
private BankAccount account;
private double amount;
public WithdrawThread(BankAccount account, double amount) {
this.account = account;
this.amount = amount;
}
@Override
public void run() {
account.withdraw(amount);
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000); // Initial balance 1000
DepositThread deposit1 = new DepositThread(account, 500);
DepositThread deposit2 = new DepositThread(account, 300);
WithdrawThread withdraw1 = new WithdrawThread(account, 200);
WithdrawThread withdraw2 = new WithdrawThread(account, 1000);
deposit1.start();
deposit2.start();
withdraw1.start();
withdraw2.start();
try {
deposit1.join();
deposit2.join();
withdraw1.join();
withdraw2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final Balance: " + account.getBalance());
}
}
54. Write a Java program using Anonymous class and override method in anonymous
class.
Sol.
interface Greeting {
void greet(String name);
}
public class Main {
public static void main(String[] args) {
Greeting greeting = new Greeting() {
@Override
public void greet(String name) {
System.out.println("Hello, " + name + "! Welcome to the Java world.");
}
};
greeting.greet("John");
greeting.greet("Alice");
}
}
56. You are developing a banking application that requires a BankAccount class. This class
should include a static variable interestRate, which is the same for all accounts, and a final
variable accountNumber, which is unique for each account and cannot be changed after
the account is created.
Tasks:
Implement the BankAccount class with the interestRate as a static variable and
accountNumber as a final variable.
Write a method calculateInterest() that calculates the interest based on the balance
and interestRate. This method should be accessible to all instances but must refer
to the shared static interestRate.
Analyze the significance of using final and static in this context. Explain how these
modifiers impact the behavior of the BankAccount class, focusing on immutability,
shared resources, and performance.
Sol.
class BankAccount {
private static double interestRate;
private final String accountNumber;
private double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public static void setInterestRate(double rate) {
interestRate = rate;
}
public double calculateInterest() {
return balance * interestRate;
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient balance.");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount.setInterestRate(0.05);
BankAccount account1 = new BankAccount("A12345", 1000);
BankAccount account2 = new BankAccount("B98765", 2000);
account1.deposit(500);
account2.withdraw(1000);
System.out.println("Interest for Account 1: " + account1.calculateInterest());
System.out.println("Interest for Account 2: " + account2.calculateInterest());
System.out.println("Account 1 Number: " + account1.getAccountNumber() + ", Balance: " +
account1.getBalance());
System.out.println("Account 2 Number: " + account2.getAccountNumber() + ", Balance: " +
account2.getBalance());
}
}
57. Consider a scenario where you need to implement a utility class MathUtils that
provides common mathematical operations such as finding the maximum of two
numbers, the power of a number, and calculating factorials. This class should be designed
in such a way that it cannot be inherited, and all the methods should be static since they
belong to the class rather than any specific instance.
Tasks:
a. Design the MathUtils class, making sure it cannot be subclassed and all its methods
(e.g., max, power, factorial) are static.
b. Explain why making the methods static is appropriate for this utility class. Discuss
the advantages and any potential limitations.
c. Analyze the implications of marking the class as final. How does this decision affect
the design and future extensibility of the class?
Sol.
a. Design the MathUtils class, making sure it cannot be subclassed and all its methods (e.g., max, power,
factorial) are static.
b. Explain why making the methods static is appropriate for this utility class. Discuss the advantages and any
potential limitations.
No Object Instantiation: Static methods do not require object creation, making them easy to call directly
on the class (e.g., MathUtils.max()).
Efficiency: Static methods improve performance by eliminating unnecessary object creation.
Utility Nature: The methods perform operations independent of instance data, which is ideal for a utility
class.
Advantages:
Convenience: Easier to use without needing an object.
Efficiency: Saves memory by not needing object instances.
Direct Access: Methods can be accessed globally via the class.
Limitations:
No Access to Instance Variables: Static methods can’t access instance variables.
No Polymorphism: Cannot be overridden in subclasses.
c. Analyze the implications of marking the class as final. How does this decision affect the design and future
extensibility of the class?
Prevents Inheritance: Ensures that no one can extend the MathUtils class, preserving its fixed behavior.
Limitations:
Reduced Extensibility: Future extensions or customizations via inheritance are not possible.
58. You are tasked with developing a software for a university's course registration
system. The system includes a Student class and a Course class. The Student class has
attributes like name, studentID, and registeredCourses. The Course class has attributes
like courseName, courseID, and maxCapacity.
Public Method:registerForCourse(Course course) in the Student class that allows a
student to register for a course if they meet the criteria.
Protected Method:checkEligibility(Course course) in the Student class that checks
whether the student is eligible to register for a course (e.g., they haven’t exceeded
their credit limit).
Private Method:addCourseToStudentRecord(Course course) in the Student class
that adds the course to the student's record and is only accessible internally.
Sol.
import java.util.ArrayList;
import java.util.List;
public class Course {
private String courseName;
private String courseID;
private int maxCapacity;
private int enrolledStudents;
public Course(String courseName, String courseID, int maxCapacity) {
this.courseName = courseName;
this.courseID = courseID;
this.maxCapacity = maxCapacity;
this.enrolledStudents = 0;
}
public String getCourseName() {
return courseName;
}
public String getCourseID() {
return courseID;
}
public int getMaxCapacity() {
return maxCapacity;
}
public int getEnrolledStudents() {
return enrolledStudents;
}
public boolean enrollStudent() {
if (enrolledStudents < maxCapacity) {
enrolledStudents++;
return true;
}
return false;
}
}
public class Student {
private String name;
private String studentID;
private List<Course> registeredCourses;
private final int MAX_CREDITS = 18;
private int currentCredits;
public Student(String name, String studentID) {
this.name = name;
this.studentID = studentID;
this.registeredCourses = new ArrayList<>();
this.currentCredits = 0;
}
public String registerForCourse(Course course) {
if (checkEligibility(course)) {
if (course.enrollStudent()) {
addCourseToStudentRecord(course);
return "Course registered successfully!";
} else {
return "Course is full!";
}
} else {
return "You are not eligible to register for this course!";
}
}
protected boolean checkEligibility(Course course) {
for (Course c : registeredCourses) {
if (c.getCourseID().equals(course.getCourseID())) {
return false;
}
}
if (currentCredits + 3 > MAX_CREDITS) {
return false;
}
return true;
}
private void addCourseToStudentRecord(Course course) {
registeredCourses.add(course);
currentCredits += 3;
}
public String getName() {
return name;
}
public String getStudentID() {
return studentID;
}
public List<Course> getRegisteredCourses() {
return registeredCourses;
}
}
59. Develop a Java program to create and manage a thread that performs file I/O
operations (e.g., reading data from one file and writing it to another). Handle exceptions
appropriately and ensure the program supports multithreading.
Sol.
import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FileIOThread implements Runnable {
private String inputFile;
private String outputFile;
public FileIOThread(String inputFile, String outputFile) {
this.inputFile = inputFile;
this.outputFile = outputFile;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
System.out.println("File copy completed for: " + inputFile);
} catch (IOException e) {
System.err.println("Error handling file: " + e.getMessage());
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
FileIOThread task1 = new FileIOThread("input1.txt", "output1.txt");
FileIOThread task2 = new FileIOThread("input2.txt", "output2.txt");
executor.execute(task1);
executor.execute(task2);
executor.shutdown();
}
}