0% found this document useful (0 votes)
16 views

Java MTE Solutions 1to60

Uploaded by

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

Java MTE Solutions 1to60

Uploaded by

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

1.

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.

Roles in Java program execution.


3.Describe the concept of type casting in Java. Differentiate between implicit and explicit type
casting with examples.
Type casting is a concept in programming where you change the data type of a variable from one
type to another.
Implicit Type Casting Explicit Type Casting
The conversion of a smaller data type to a larger data The conversion of a larger data type to a smaller
type is performed automatically by the Java compiler. data type is performed manually by the
programmer using a cast operator
public class main {
public static void main(String[] args) { public class main{
int num = 100; // Integer type public static void main(String[] args) {
double result = num; // Implicitly cast to double double num = 123.45; // Double type
System.out.println("Integer value: " + num); int result = (int) num; // Explicitly cast to int
System.out.println("Double value (after casting): " + result); System.out.println("Double value: " + num);
} System.out.println("Integer value (after casting): " + result);
} }
}
Output: Output:-
Integer value: 100 Double value: 123.45
Double value (after casting): 100.0 Integer value (after casting): 123
4.Write a Java program to demonstrate the use of access specifiers by creating a class with
fields and methods having different access levels. Explain the behavior of each access specifier.
class AccessSpecifiersDemo { void defaultMethod() {
// Fields with different access specifiers System.out.println("This is a default (package-private)
public String publicField = "I am public"; method.");

protected String protectedField = "I am protected"; }

String defaultField = "I am default (package-private)"; private void privateMethod() {

private String privateField = "I am private"; System.out.println("This is a private method.");


}

// Methods with different access specifiers


public void publicMethod() { // Method to access private field and method

System.out.println("This is a public method."); public void accessPrivateMembers() {

} System.out.println("Accessing private field: " +


privateField);
privateMethod();
protected void protectedMethod() {
}
System.out.println("This is a protected method.");
}
}
// Main class in the same package // obj.privateMethod(); // Error: privateMethod is not
public class Main { accessible outside the class
public static void main(String[] args) {
AccessSpecifiersDemo obj = new AccessSpecifiersDemo(); // Accessing private members through a public method
obj.accessPrivateMembers();
// Accessing fields }
System.out.println(obj.publicField); // Accessible }
System.out.println(obj.protectedField); // Accessible (same Output:
package) I am public
System.out.println(obj.defaultField); // Accessible (same I am protected
package)
I am default (package-private)
// System.out.println(obj.privateField); // Error:
privateField is not accessible outside the class This is a public method.
This is a protected method.

// Accessing methods This is a default (package-private) method.

obj.publicMethod(); // Accessible Accessing private field: I am private

obj.protectedMethod(); // Accessible (same package) This is a private method.

obj.defaultMethod(); // Accessible (same package)


Behavior of each access specifier
5.Develop a Java program to showcase method overloading by creating methods with the
same name but different parameter lists. Include at least three overloaded methods.
public class Main {
class OverloadingDemo {

// Overloaded method 1: Adds two integers public static void main(String[] args) {

public int add(int a, int b) { OverloadingDemo demo = new OverloadingDemo();

return a + b; // Calling the method to add two integers

} int sum1 = demo.add(10, 20);

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

return a + b + c; int sum2 = demo.add(10, 20, 30);

} System.out.println("Sum of three integers: " + sum2);

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

StaticNonStaticDemo obj2 = new StaticNonStaticDemo();

obj2.incrementInstanceCounter();

// Access static member again to show it's shared

System.out.println("Final Static Counter: " + staticCounter);

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

} public class Main {

interface Colorable { public static void main(String[] args) {

void color(String color); Circle circle = new Circle();

} circle.draw();

class Circle implements Shape, Colorable { circle.color("Red");

@Override }

public void draw() { }

System.out.println("Drawing a circle"); Output:


Drawing a circle
}
Coloring the circle with Red
@Override

public void color(String color) {

System.out.println("Coloring the circle with " + color);


10. Create a Java program to demonstrate the use of `ArrayList` and `HashMap` from the Collections Framework. Perform basic
operations such as adding, removing, and iterating over elements.
import java.util.ArrayList; // Demonstrating HashMap
import java.util.HashMap; System.out.println("\nHashMap Demonstration:");
HashMap<Integer, String> employees = new HashMap<>();
public class CollectionsDemo {
public static void main(String[] args) { // Adding key-value pairs
// Demonstrating ArrayList employees.put(101, "Alice");
System.out.println("ArrayList Demonstration:"); employees.put(102, "Bob");
ArrayList<String> fruits = new ArrayList<>(); employees.put(103, "Charlie");
System.out.println("Employees: " + employees);
// Adding elements
fruits.add("Apple"); // Removing an entry
fruits.add("Banana"); employees.remove(102);
fruits.add("Cherry"); System.out.println("After removing employee with ID 102: " +
System.out.println("Fruits: " + fruits); employees);

// Removing an element // Iterating over key-value pairs


fruits.remove("Banana"); System.out.println("Iterating over HashMap:");
System.out.println("After removing 'Banana': " + fruits); for (Integer id : employees.keySet()) {
System.out.println("ID: " + id + ", Name: " + employees.get(id));
// Iterating over elements }
System.out.println("Iterating over ArrayList:"); }
for (String fruit : fruits) { }
System.out.println(fruit);
}
Output:
ArrayList Demonstration:
Fruits: [Apple, Banana, Cherry]
After removing 'Banana': [Apple, Cherry]
Iterating over ArrayList:
Apple
Cherry

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.

public class DivisionExample {

// 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;
}

public static void main(String[] args) {


int numerator = 10;
Vivek
int denominator = 0; // Change this to a non-zero value to test successful division

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.");
}

// Additional test with a valid denominator


denominator = 2; // Change to a valid value for further testing

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.

class PriorityThread extends Thread {


private int threadNumber;

public PriorityThread(int threadNumber) {


this.threadNumber = threadNumber;
}

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

1.Class Priority Thread:


•This class extends Thread and overrides the run method. Each thread simulates some work
by sleeping for 1 second and then prints a message indicating its start and finish.
2.Setting Thread Priorities:
•The threads are created with different priorities using set Priority().
•The priorities range from Thread.MIN_PRIORITY to Thread.MAX_PRIORITY (
• The default priority is Thread.NORM_PRIORITY
3.Starting Threads:
•All threads are started almost simultaneously.
4.Joining Threads:
•The main thread waits for all the created threads to finish using join().

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

// Method to search for a student


public void searchStudent(String rollNumber) {
if (studentMap.containsKey(rollNumber)) {
Student student = studentMap.get(rollNumber);
System.out.println("Found student: " + student);
} else {
System.out.println("No student found with roll number: " + rollNumber);
}
}

public static void main(String[] args) {


StudentManagement management = new StudentManagement();
Scanner scanner = new Scanner(System.in);
int choice;

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?

In Java, method overloading cannot be


performed by changing return type of
the method only. Return type can be Return type must be same or
5)
same or different in method covariant in method overriding.
overloading. But you must have to
Method overloading is used to Method overriding is used to provide the change the parameter.
1) increase the readability of the specific implementation of the method that
program. is already provided by its super class.

6) It uses static binding. It uses dynamic binding.

It provides specific implementation


Method overriding occurs in two 7) It enhances code readability. of the method that is provided by
Method overloading is the parent class.
2) classes that have IS-A (inheritance)
performed within class.
relationship.

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.

10) It is called early binding. It is called late binding.


Method overloading is the example Method overriding is the example of run
4)
of compile time polymorphism. time polymorphism.
11) Static method can be overloaded. Static method cannot be overridden.

Vivek 12) Implemented in single class. Implemented in two classes.


Example of Method Overloading
Example of Method Overriding class MathOperations {
// Method to add two integers
class Animal { int add(int a, int b) {
void sound() { return a + b;
System.out.println("Animal makes a sound"); }
} // Method to add three integers
} int add(int a, int b, int c) {
return a + b + c;
class Dog extends Animal { }
@Override // Method to add two doubles
void sound() { double add(double a, double b) {
System.out.println("Dog barks"); return a + b;
} }
} }
public class Main {
public class Main { public static void main(String[] args) {
public static void main(String[] args) { MathOperations math = new MathOperations();
Animal myDog = new Dog(); System.out.println(math.add(5, 10)); // Output: 15
myDog.sound(); // Output: Dog barks System.out.println(math.add(5, 10, 15)); // Output: 30
} System.out.println(math.add(5.5, 10.5)); // Output: 16.0
} }
Vivek
}
Q.Describe the steps involved in creating and using a user-defined exception in Java. Write a Java program to
handle an invalid bank transaction using a custom exception class.

Steps to Create and Use a User-Defined Exception

1.Define the Custom Exception Class:


•Create a new class that extends the Exception class (or RuntimeException if you want an unchecked exception).
•Define constructors to initialize the exception with a custom message and/or cause.
2.Throw the Custom Exception:
•In the relevant part of your code (e.g., in a method that performs operations like banking transactions),
use the throw statement to throw the custom exception when a specific condition is met (e.g., invalid transaction).
3.Handle the Custom Exception:
•Use a try-catch block to handle the custom exception where the method that can throw it is called.
•Provide appropriate logic in the catch block to deal with the exception (e.g., logging, user notification).

Vivek
// Step 1: Define the custom exception class
class InvalidTransactionException extends Exception {
public InvalidTransactionException(String message) {
super(message);
}
}

// Bank class to perform transactions


class Bank {
private double balance;

public Bank(double initialBalance) {


this.balance = initialBalance;
}

// Method to perform a transaction


public void withdraw(double amount) throws InvalidTransactionException {
if (amount <= 0) {
throw new InvalidTransactionException("Withdrawal amount must be positive.");
}
if (amount > balance) {
throw new InvalidTransactionException("Insufficient funds for withdrawal.");
} Vivek
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + balance);
}

public double getBalance() {


return balance;
System.out.println("Final balance: " + bank.getBalance());
}
}
}
}
// Main class to demonstrate the exception handling
public class BankTransactionDemo { Output:
public static void main(String[] args) { Withdrawal successful. New balance: 800.0
Bank bank = new Bank(1000.00); // Initial balance Transaction failed: Insufficient funds for withdrawal.
Transaction failed: Withdrawal amount must be positive.
try { Final balance: 800.0
bank.withdraw(200.00); // Valid transaction
bank.withdraw(1500.00); // Invalid transaction (insufficient funds)
} catch (InvalidTransactionException e) {
System.out.println("Transaction failed: " + e.getMessage());
}

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.

import java.util.ArrayList; // Using Set


import java.util.HashSet; Set<String> set = new HashSet<>();
import java.util.List; set.add("Apple");
import java.util.Set; set.add("Banana");
set.add("Orange");
public class CollectionDemo { set.add("Banana"); // Duplicates not allowed
public static void main(String[] args) {
// Using List System.out.println("\nSet elements:");
List<String> list = new ArrayList<>(); for (String fruit : set) {
list.add("Apple"); System.out.println(fruit);
list.add("Banana"); }
list.add("Orange"); }
list.add("Banana"); // Duplicates allowed }

System.out.println("List elements:"); OUTPUT:


for (String fruit : list) {
List elements: Set elements:
System.out.println(fruit);
Apple Apple
}
Banana Banana
Orange Orange
Vivek Banana
S.N. List Set S.N. List Set
The set
The list
implementation It allows positional It does not support
implementation allows 8.
1. doesn't allow us to add access via index. positional access.
us to add the same or
the same or duplicate
duplicate elements.
elements. Implements an ordered It implements an
9.
collection. unordered collection
It doesn't maintain the
The insertion order is
2. insertion order of It allows for efficient
maintained by the List. Its retrieval is based on
elements. 10. element retrieval by
element equality.
List allows us to add Set allows us to add at index
3. any number of null least one null value in
values. it. It supports operations
like add, remove, and It does not support
The List The Set 11.
replace at specific such operations.
implementation classes implementation classes indices.
4.
are LinkedList and are TreeSet, HashSet
ArrayList. and LinkedHashSet.
It typically uses a It utilizes hashing or
We cannot find the 12. dynamic array or linked tree-based data
We can get the element from the Set list data structures. structures.
element of a specified based on the index
5.
index from the list because it doesn't
using the get() method. provide any get It allows for resizing Its size is typically fixed
13.
method(). and dynamic growth. or limited.

It is used when we It is used when we ListIterator allows


want to frequently want to design a Iterator provides
6. bidirectional traversal
access the elements by collection of distinct 14. sequential traversal
and modification
using the index. elements. without modification.
during iteration.

The method of List The iterator is used


interface listiterator() is when we need to It commonly used in
7. It is ideal for scenarios
used to iterate the List iterate the Set scenarios requiring
15. requiring uniqueness
elements. elements. ordered collections
and set operations
Vivek with duplicates.
import java.util.Scanner;
// Perform operations based on user choice
if (choice >= 1 && choice <= 4) {
public class MenuBasedCalculator {
System.out.print("Enter first number: ");
public static void main(String[] args) {
num1 = scanner.nextDouble();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter second number: ");
int choice;
num2 = scanner.nextDouble();
double num1, num2, result;
}
do {
switch (choice) {
// Display menu options
case 1: // Addition
System.out.println("Menu:");
result = num1 + num2;
System.out.println("1. Addition");
System.out.println("Result: " + num1 + " + " + num2 + " =
System.out.println("2. Subtraction");
break;
System.out.println("3. Multiplication");
case 2: // Subtraction
System.out.println("4. Division");
result = num1 - num2;
System.out.println("5. Exit");
System.out.println("Result: " + num1 + " - " + num2 + " =
System.out.print("Enter your choice (1-5): ");
break;
case 3: // Multiplication
// Read user choice
Vivek result = num1 * num2;
choice = scanner.nextInt();
System.out.println("Result: " + num1 + " * " + num2 + " = " + result);
Menu: Output:
1. Addition
break;
2. Subtraction
case 4: // Division
3. Multiplication
if (num2 != 0) {
4. Division
result = num1 / num2;
5. Exit
System.out.println("Result: " + num1 + " / " + num2 + " = " + result);
Enter your choice (1-5): 1
} else {
Enter first number: 10
System.out.println("Error: Division by zero is not allowed.");
Enter second number: 5
}
Result: 10.0 + 5.0 = 15.0
break;
case 5: // Exit
Menu:
System.out.println("Exiting the calculator. Goodbye!");
1. Addition
break;
2. Subtraction
default:
3. Multiplication
System.out.println("Invalid choice. Please select a valid option.");
4. Division
}
5. Exit
Enter your choice (1-5): 4
System.out.println(); // Print a new line for better readability
Enter first number: 10
} while (choice != 5); // Continue until the user chooses to exit
Enter second number: 0
Error: Division by zero is not allowed.
scanner.close(); // Close the scanner
}
Enter your choice (1-5): 5
} Vivek
Exiting the calculator. Goodbye!
Q. Write a Java program to design the patterns

class Main { class Main {


public static void main(String[] args) { public static void main(String[] args) {
int n = 5; int n = 5;
for (int i = 1; i <= n; i++) {
// Outer loop for each row
// Inner loop for printing '*' in each row for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*"); // Inner loop for printing numbers in each row
} for (int j = 1; j <= i; j++) {
System.out.println(); System.out.print(j);
} }
} System.out.println();
} }
}
Vivek
}
class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= 5; i++) {
// Outer loop for each row // Inner loop for printing the characters
for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) {
System.out.print((char) (i + 64)); // Prints the ASCII
// Inner loop for printing numbers in each row //character corresponding to 'A' + i
for (int j = 1; j <= i; j++) { }
System.out.print(i);
} System.out.println();
}
System.out.println(); } }
} }
}
class Main {
public class Main { public static void main(String[] args) {
public static void main(String[] args) { int n = 5; int a = 0, b = 1;
// Outer loop for rows
for (int i = 1; i <= 5; i++) { for (int i = 1; i <= n; i++) {
// Inner loop for printing the characters // Inner loop for columns
for (int j = 1; j <= i; j++) { for (int j = 1; j <= i; j++) {
System.out.print((char) (j + 64)); // Prints the ASCII System.out.print(b + " "); // To Print the Fibonacci number
//character corresponding to 'A' + i
} // To Generate the next Fibonacci number
System.out.println(); int next = a + b;
} a = b;
} b = next;
} }
System.out.println();
}
}
}
public class Main {
public static void main(String[] args) { class Main {
int n=5; public static void main(String[] args) { class Main {
int n = 4; int num = 1; public static void main(String[] args) {
int temp; for (int i = 1; i <= n; i++) { int n = 5;
for(int i=1;i<=n;i++){ for (int j = 1; j <= i; j++) { int num = 1;
int a=0; System.out.print(num);
int b=1; // Print the current number for (int i = 1; i <= n; i++) {
for(int j=1; j<=i;j++){ num++; } for (int j = 1; j <= i; j++) {
System.out.print(a+" "); System.out.println(); System.out.print(num
temp=a+b; // Move to the next row num += 2; // Increment by 2
a=b; } }
b=temp; } System.out.println();
} }
} }
System.out.println(); }
}
}
}
class Main {
public static void main(String[] args) {
int n = 4;
class Main {
int num = 1; // Starting number
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int i = 1; i <= n; i++) {
int start = num + i - 1;
int num = (i % 2 == 1) ? 1 : 2;
// Calculate the starting number for the row
// Odd rows start with 1, even rows with 2
for (int j = 1; j <= i; j++) {
for (int j = 1; j <= i; j++) {
System.out.print(start--);
System.out.print(num);
// Print numbers in descending order
num += 2; // Increment by 2
}
}
System.out.println();
num += i;
}
// Update the starting number for the next row
}
System.out.println();
}
}
}
}
class Main {
public static void main(String[] args) {
int n = 3;
int num = 1; // Starting number for the first row

// Loop to control rows


for (int i = 1; i <= n; i++) {
// Print leading spaces to create the right alignment
for (int j = i; j < n; j++) {
System.out.print(" "); // Add space before numbers
}

// Print numbers in the current row


for (int j = 1; j <= i * 2 - 1; j++) {
System.out.print(num + " "); // Print the current
number
num += (j % 2 == 0) ? 3 : 5; // Increment by 3 or 5
alternately
}

System.out.println(); // Move to the next row


}
}
21. Differentiate between `Set` and `List` in the Java Collections Framework. Write a
program to demonstrate their usage by storing and iterating over elements.
Sol.
Set:
A Set in Java is a collection that does not allow duplicate elements. It represents a mathematical set abstraction,
where each element is unique. Sets may or may not maintain the order of elements depending on the
implementation:
 HashSet: Does not maintain any order.
 LinkedHashSet: Maintains the insertion order.
List:
A List in Java is an ordered collection that allows duplicate elements. Lists maintain the sequence of insertion, which
makes them suitable for tasks where order matters. You can access elements by their index, starting from 0. Common
implementations include:
 ArrayList: Provides dynamic arrays with fast access times.
 LinkedList: Provides sequential storage with efficient insertions and deletions.
Use a List when maintaining the order of elements or allowing duplicates is essential, such as managing a
collection of tasks or items in a specific sequence.

FEATURE SET LIST


DEFINITION A collection that does not An ordered collection that
allow duplicate elements. allows duplicate elements.
ORDER May or may not maintain Maintains insertion order.
insertion order (HashSet does
not, but LinkedHashSet does).
DUPLICATES Does not allow duplicates. Allows duplicates.
IMPLEMENTATION Common implementations Common implementations
include HashSet, TreeSet, and include ArrayList and
LinkedHashSet. LinkedList.
PERFORMANCE Generally faster for search Can be slower for searching
operations due to hash-based due to linear traversal in most
structure (HashSet). implementations.

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

28. Write a Java program to remove duplicate elements from an array.


Sol.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 20, 30, 40, 50, 40, 60, 70, 70};
System.out.println("Original array:");
printArray(arr);
arr = removeDuplicates(arr);
System.out.println("Array after removing duplicates:");
printArray(arr);
}
public static int[] removeDuplicates(int[] arr) {
int[] uniqueArr = Arrays.stream(arr) // Convert array to stream
.distinct() // Remove duplicates
.toArray(); // Convert stream back to array
return uniqueArr;
}
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:

public class Circle {


private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
if (radius > 0) {
this.radius = radius; // Only set radius if it is positive
} else {
System.out.println("Radius must be positive.");
}
}
public double calculateArea() {
return Math.PI * radius * radius;
}

// Method to calculate the perimeter (circumference) of the circle


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

// Main method to demonstrate the functionality


public static void main(String[] args) {
// Create a Circle object with radius 5.0
Circle circle = new Circle(5.0);

// Display the radius, area, and perimeter


System.out.println("Radius: " + circle.getRadius());
System.out.println("Area: " + circle.calculateArea());
System.out.println("Perimeter: " + circle.calculatePerimeter());

// Modify the radius using the setter method


circle.setRadius(7.0);

// Display the updated values


System.out.println("\nUpdated Radius: " + circle.getRadius());
System.out.println("Updated Area: " + circle.calculateArea());
System.out.println("Updated Perimeter: " + circle.calculatePerimeter());
}
}

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;

public class LexicographicalComparison {


public static void main(String[] args) {
// Create a scanner to read input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter two strings


System.out.print("Enter the first string: ");
String string1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String string2 = scanner.nextLine();

// Compare the two strings lexicographically using compareTo()


int result = string1.compareTo(string2);

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.");
}

// Close the scanner


scanner.close();
}
}

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;

public class WordTokenizer {


public static void main(String[] args) {
// Create a scanner to read user input
Scanner scanner = new Scanner(System.in);

// Prompt the user for input


System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();

// Create a StringTokenizer to split the sentence into tokens using space as a delimiter
StringTokenizer tokenizer = new StringTokenizer(sentence);

// Flag to check if "India" is found


boolean foundIndia = false;

// Iterate through all tokens


while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();

// Check if the token is "India"


if (token.equalsIgnoreCase("India")) {
foundIndia = true;
break; // If found, exit the loop early
}
}

// Output result
if (foundIndia) {
System.out.println("\"India\" is present in the sentence.");
} else {
System.out.println("\"India\" is not present in the sentence.");
}

// Close the scanner


scanner.close();
}
}

34.Write a Java program that creates a bank account with concurrent deposits and withdrawals using threads.
Solution:
class BankAccount {
private double balance;

// Constructor to initialize the balance


public BankAccount(double initialBalance) {
balance = initialBalance;
}

// Synchronized method for depositing money to ensure thread safety


public synchronized void deposit(double amount) {
balance += amount;
System.out.println(Thread.currentThread().getName() + " deposited: " + amount + ", Current Balance: " +
balance);
}

// Synchronized method for withdrawing money to ensure thread safety


public synchronized void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println(Thread.currentThread().getName() + " withdrew: " + amount + ", Current Balance: " +
balance);
} else {
System.out.println(Thread.currentThread().getName() + " attempted to withdraw: " + amount + " but
insufficient funds. Current Balance: " + balance);
}
}

// Method to get the current balance


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


public static void main(String[] args) {
// Create a BankAccount with an initial balance
BankAccount account = new BankAccount(1000.0);

// Create threads for depositing and withdrawing money


DepositThread deposit1 = new DepositThread(account, 200.0);
WithdrawThread withdraw1 = new WithdrawThread(account, 150.0);
DepositThread deposit2 = new DepositThread(account, 100.0);
WithdrawThread withdraw2 = new WithdrawThread(account, 500.0);

// Start the threads


deposit1.start();
withdraw1.start();
deposit2.start();
withdraw2.start();

try {
// Wait for all threads to finish
deposit1.join();
withdraw1.join();
deposit2.join();
withdraw2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

// Final balance after all operations


System.out.println("Final Balance: " + account.getBalance());
}
}

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;

// No-argument constructor, sets default radius to 1.0


public Circle() {
radius = 1.0;
}

// Constructor with a parameter to set custom radius


public Circle(double radius) {
this.radius = radius;
}
// Method to calculate and return the area of the circle
public double getArea() {
return Math.PI * radius * radius; // Area = π * radius^2
}

// Getter for radius (if needed)


public double getRadius() {
return radius;
}

// Setter for radius (if needed)


public void setRadius(double radius) {
this.radius = radius;
}

// Main method to test the Circle class


public static void main(String[] args) {
// Create Circle objects with different radii
Circle circle1 = new Circle(3.0); // radius 3.0
Circle circle2 = new Circle(3.2); // radius 3.2
Circle circle3 = new Circle(4.1); // radius 4.1

// Display radius and area of each circle


System.out.println("Circle 1 - Radius: " + circle1.getRadius() + ", Area: " + circle1.getArea());
System.out.println("Circle 2 - Radius: " + circle2.getRadius() + ", Area: " + circle2.getArea());
System.out.println("Circle 3 - Radius: " + circle3.getRadius() + ", Area: " + circle3.getArea());
}
}

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;

public Flight(String flightNumber, String departure, String destination, double price) {


this.flightNumber = flightNumber;
this.departure = departure;
this.destination = destination;
this.price = price;
}

public String getFlightNumber() {


return flightNumber;
}

public String getDeparture() {


return departure;
}
public String getDestination() {
return destination;
}

public double getPrice() {


return 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;

public Hotel(String name, String city, double pricePerNight) {


this.name = name;
this.city = city;
this.pricePerNight = pricePerNight;
}

public String getName() {


return name;
}

public String getCity() {


return city;
}

public double getPricePerNight() {


return 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<>();

// Adding some sample data


flights.add(new Flight("AA123", "New York", "London", 500.0));
flights.add(new Flight("BA456", "Los Angeles", "Paris", 750.0));
flights.add(new Flight("UA789", "Chicago", "Tokyo", 800.0));

hotels.add(new Hotel("Hotel Luxe", "London", 150.0));


hotels.add(new Hotel("Paris Inn", "Paris", 200.0));
hotels.add(new Hotel("Tokyo Bay Hotel", "Tokyo", 180.0));
}

// 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.");
}

// Cancel Flight Booking


public void cancelFlight(String flightNumber) {
if (bookedFlights.remove(flightNumber)) {
System.out.println("\nFlight " + flightNumber + " reservation canceled.");
} else {
System.out.println("\nNo reservation found for flight " + flightNumber);
}
}

// 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.");
}

// Cancel Hotel Booking


public void cancelHotel(String hotelName) {
if (bookedHotels.remove(hotelName)) {
System.out.println("\nHotel " + hotelName + " reservation canceled.");
} else {
System.out.println("\nNo reservation found for hotel " + hotelName);
}
}
}

public class TravelAgencySystem {


public static void main(String[] args) {
TravelAgency agency = new TravelAgency();

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

// Cancel a flight reservation


agency.cancelFlight("AA123");
agency.cancelFlight("AA123"); // Attempt to cancel again

// Cancel a hotel reservation


agency.cancelHotel("Hotel Luxe");
agency.cancelHotel("Hotel Luxe"); // Attempt to cancel 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();
}

// SavingsAccount class implementing Account interface


class SavingsAccount implements Account {
private double balance;
private double interestRate;
private String accountHolder;

// Constructor to initialize SavingsAccount


public SavingsAccount(String accountHolder, double initialBalance, double interestRate) {
this.accountHolder = accountHolder;
this.balance = initialBalance;
this.interestRate = interestRate;
}

// Deposit money into SavingsAccount


@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited $" + amount + " into Savings Account.");
} else {
System.out.println("Invalid deposit amount.");
}
}

// Withdraw money from SavingsAccount


@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrew $" + amount + " from Savings Account.");
} else {
System.out.println("Insufficient funds or invalid withdrawal amount.");
}
}

// Calculate interest for SavingsAccount


@Override
public double calculateInterest() {
return balance * interestRate / 100;
}

// View balance in SavingsAccount


@Override
public void viewBalance() {
System.out.println("Balance in Savings Account: $" + balance);
}
}

// CurrentAccount class implementing Account interface


class CurrentAccount implements Account {
private double balance;
private double overdraftLimit;
private String accountHolder;

// Constructor to initialize CurrentAccount


public CurrentAccount(String accountHolder, double initialBalance, double overdraftLimit) {
this.accountHolder = accountHolder;
this.balance = initialBalance;
this.overdraftLimit = overdraftLimit;
}

// Deposit money into CurrentAccount


@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited $" + amount + " into Current Account.");
} else {
System.out.println("Invalid deposit amount.");
}
}

// Withdraw money from CurrentAccount


@Override
public void withdraw(double amount) {
if (amount > 0 && (balance - amount) >= -overdraftLimit) {
balance -= amount;
System.out.println("Withdrew $" + amount + " from Current Account.");
} else {
System.out.println("Insufficient funds or overdraft limit exceeded.");
}
}

// Calculate interest for CurrentAccount (typically none, but can be customized)


@Override
public double calculateInterest() {
return 0; // No interest for CurrentAccount, can be customized
}

// View balance in CurrentAccount


@Override
public void viewBalance() {
System.out.println("Balance in Current Account: $" + balance);
}
}

// Bank class to manage a list of accounts


class Bank {
private List<Account> accounts;

public Bank() {
accounts = new ArrayList<>();
}

// Add an account to the bank


public void addAccount(Account account) {
accounts.add(account);
System.out.println("Account added to the bank.");
}

// Show account details for all accounts in the bank


public void displayAllAccounts() {
for (Account account : accounts) {
account.viewBalance();
System.out.println("Interest: $" + account.calculateInterest());
System.out.println("--------------------------");
}
}
}

// Main class to test the banking system


public class BankingSystem {
public static void main(String[] args) {
// Create a bank
Bank bank = new Bank();

// Create and add SavingsAccount


SavingsAccount savings = new SavingsAccount("Alice", 1000, 3.5);
bank.addAccount(savings);

// Create and add CurrentAccount


CurrentAccount current = new CurrentAccount("Bob", 500, 200);
bank.addAccount(current);

// Perform some transactions


savings.deposit(500); // Depositing into SavingsAccount
savings.withdraw(200); // Withdrawing from SavingsAccount

current.deposit(300); // Depositing into CurrentAccount


current.withdraw(600); // Withdrawing from CurrentAccount (should succeed)
current.withdraw(300); // Trying to withdraw more than allowed by overdraft limit

// Display all accounts and their balances


System.out.println("\nDisplaying all accounts in the bank:\n");
bank.displayAllAccounts();
}
}

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;

// Constructor to initialize employee details


public Employee(String name, int id) {
this.name = name;
this.id = id;
}

// Abstract method to calculate salary


public abstract void calculateSalary();

// Abstract method to display employee information


public abstract void displayInfo();
}

// Subclass Manager
class Manager extends Employee {
int numberOfTeamMembers;

// Constructor for Manager


public Manager(String name, int id, int numberOfTeamMembers) {
super(name, id); // Calling the parent constructor
this.numberOfTeamMembers = numberOfTeamMembers;
}

// Implementing calculateSalary method for Manager


@Override
public void calculateSalary() {
salary = 5000 + (numberOfTeamMembers * 200); // Base salary + bonus per team member
}

// Implementing displayInfo method for Manager


@Override
public void displayInfo() {
System.out.println("Manager Name: " + name);
System.out.println("Manager ID: " + id);
System.out.println("Number of Team Members: " + numberOfTeamMembers);
System.out.println("Manager Salary: $" + salary);
}
}

// Subclass Programmer
class Programmer extends Employee {
int hoursWorked;

// Constructor for Programmer


public Programmer(String name, int id, int hoursWorked) {
super(name, id); // Calling the parent constructor
this.hoursWorked = hoursWorked;
}

// Implementing calculateSalary method for Programmer


@Override
public void calculateSalary() {
salary = 40 * hoursWorked; // Base salary based on hours worked (assuming $40 per hour)
}

// Implementing displayInfo method for Programmer


@Override
public void displayInfo() {
System.out.println("Programmer Name: " + name);
System.out.println("Programmer ID: " + id);
System.out.println("Hours Worked: " + hoursWorked);
System.out.println("Programmer Salary: $" + salary);
}
}

// Main class to test the functionality


public class EmployeeTest {
public static void main(String[] args) {
// Creating Manager and Programmer objects
Manager manager = new Manager("Alice", 101, 5);
Programmer programmer = new Programmer("Bob", 102, 160);

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

public class OddNumberChecker {

// Method that checks if the number is odd and throws OddNumberException if it is


public static void checkEvenNumber(int number) throws OddNumberException {
if (number % 2 != 0) { // If the number is odd
throw new OddNumberException("Error: The number " + number + " is odd!");
} else {
System.out.println("The number " + number + " is even.");
}
}

public static void main(String[] args) {


// Test with different numbers
int[] numbers = {2, 3, 4, 5, 6};

for (int num : numbers) {


try {
checkEvenNumber(num); // Calling the method
} catch (OddNumberException e) {
System.out.println(e.getMessage()); // Catching and printing the exception message
}
}
}

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.");
}

// Parent class parameterized constructor


public Parent(String message) {
System.out.println("Parent class constructor with message: " + message);
}
}

// 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.");
}

public Child(int num) {


super("Integer passed: " + num); // Access parent class constructor with integer argument
System.out.println("Child class constructor with integer: " + num);
}

// Method overloading in child class


public void display() {
System.out.println("Display method with no parameters.");
}

public void display(String message) {


System.out.println("Display method with message: " + message);
}

public void display(int number) {


System.out.println("Display method with number: " + number);
}
}

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

System.out.println("\nCreating second child object with integer:");


Child child2 = new Child(10); // Calls parameterized constructor of Child class

// Demonstrating method overloading


System.out.println("\nDemonstrating Method Overloading:");
child1.display(); // Calls the display method with no parameters
child1.display("Hello World!"); // Calls the display method with String argument
child1.display(100); // Calls the display method with integer argument
}
}
41.Write a JAVA program which has
A Class called Account that creates account with 500Rs minimum balance, a deposit()
method to deposit amount, a withdraw() method to withdraw amount and also throws
LessBalanceException if an account holder tries to withdraw money which makes the
balance become less than 500Rs.
A Class called LessBalanceException which returns the statement that says withdraw
amount ( Rs) is not valid.
A Class which creates 2 accounts, both account deposit money and one account tries to
withdraw more money which generates a LessBalanceException take appropriate
action for the same.
Sol.
class LessBalanceException extends Exception {
public LessBalanceException(String message) {
super(message);
}
}
class Account {
private double balance;
public Account() {
this.balance = 500;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: Rs " + amount);
System.out.println("Current Balance: Rs " + balance);
}
public void withdraw(double amount) throws LessBalanceException {
if (balance - amount < 500) {
throw new LessBalanceException("Error: Withdrawal of Rs " + amount + " is not possible. Minimum balance of
Rs 500 must be maintained.");
} else {
balance -= amount;
System.out.println("Withdrew: Rs " + amount);
System.out.println("Updated Balance: Rs " + balance);
}
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
try {
Account account1 = new Account();
Account account2 = new Account();
System.out.println("Creating and depositing money into Account 1:");
account1.deposit(1000);
System.out.println("\nCreating and depositing money into Account 2:");
account2.deposit(2000);
System.out.println("\nAttempting to withdraw Rs 1200 from Account 1:");
account1.withdraw(1200);
System.out.println("\nAttempting to withdraw Rs 1500 from Account 2:");
account2.withdraw(1500);
} catch (LessBalanceException e) {
System.out.println("\n" + e.getMessage());
}
}
}

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

System.out.println("Area of Rectangle: " + rectangle.getArea());


System.out.println("Area of Circle: " + circle.getArea());
System.out.println("Area of Triangle: " + triangle.getArea());
}
}

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

55. What will be the output of the following code?


class MOClassD {
private int x= 1;
class MIClass {
public void seeOuter () {
System.out.println("Outer Value of x is :" + x);
}
}
public static void main(String args[]){
MOClassD.MIClass inner = new MOClassD().new MIClass();
inner. seeOuter();
}
}
Sol.
Outer Value of x is :1

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.

public final class MathUtils {


private MathUtils() {}
public static int max(int a, int b) {
return (a > b) ? a : b;
}
public static double power(double base, double exponent) {
return Math.pow(base, exponent);
}
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Number must be non-negative");
}
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}

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.

 Consistency: Guarantees the class’s behavior remains unaltered.

 Simplifies Design: Makes it clear the class is not meant to be subclassed.

Limitations:

 Reduced Extensibility: Future extensions or customizations via inheritance are not possible.

 Customization Restrictions: Can't modify behavior through subclassing.

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

60. Develop a Java program to demonstrate thread synchronization using the


`synchronized` keyword. Create a scenario where multiple threads access a shared
resource, and synchronize the access to prevent data inconsistency.
Sol.
class SharedResource {
private int counter = 0;
public synchronized void increment() {
counter++;
System.out.println(Thread.currentThread().getName() + " incremented counter to: " + counter);
}
public int getCounter() {
return counter;
}
}
class CounterThread extends Thread {
private SharedResource resource;
public CounterThread(SharedResource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
resource.increment();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
}
}
}
public class SynchronizedDemo {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
CounterThread thread1 = new CounterThread(resource);
CounterThread thread2 = new CounterThread(resource);
thread1.start();
thread2.start();
}
}

You might also like