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

j1 java (1)

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

j1 java (1)

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

1.

Explain the key features of Object-Oriented Programming (OOP) and how


they are implemented in Java. Provide examples for at least two features.
2. Differentiate between JDK, JVM, and JRE. Illustrate their roles in Java
program execution.
3. Describe the concept of type casting in Java. Differentiate between
implicit and explicit type casting with examples.
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.
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.
Certainly! Below are explanations and examples related to your questions:

### 1. Key Features of Object-Oriented Programming (OOP) in Java

Object-Oriented Programming (OOP) is a programming paradigm that uses


"objects" to design applications and computer programs. The four key
features of OOP include:

- **Encapsulation**: Bundling the data (attributes) and methods (functions)


that operate on the data into a single unit (class). Access to the data is
restricted to the methods of the class.

*Example in Java*:
```java
class Person {
private String name; // private field

public void setName(String name) { // setter method


this.name = name;
}

public String getName() { // getter method


return this.name;
}
}
```

- **Inheritance**: A mechanism where one class can inherit fields and


methods from another class. This promotes code reuse.

*Example in Java*:
```java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}
```

### 2. Differentiating JDK, JVM, and JRE

- **Java Development Kit (JDK)**: This is a complete software development


kit that provides tools to develop, compile, and run Java applications. It
includes the JRE and development tools (like `javac`, the Java compiler).

- **Java Runtime Environment (JRE)**: This is a subset of the JDK that


includes all the components required to run Java applications. It comprises
the JVM, core libraries, and other components necessary for running Java
programs.

- **Java Virtual Machine (JVM)**: This is an abstract machine that enables


Java bytecode to be executed on any platform. It provides a runtime
environment to execute Java applications, handling memory management
and garbage collection.

*Illustration of Roles*:
1. Code written in Java (`.java`) is compiled into bytecode (`.class`) using the
JDK (`javac`).
2. The bytecode can then run on any machine with a JRE installed.
3. The JVM interprets the bytecode and executes it, enabling platform
independence.

### 3. Concept of Type Casting in Java


Type casting is the process of converting a variable from one type to
another. In Java, casting can happen in two ways:

- **Implicit Type Casting** (Widening): This occurs when a smaller type is


converted to a larger type without explicit casting.

*Example*:
```java
int num = 10;
double doubleNum = num; // Implicit casting: int to double
```

- **Explicit Type Casting** (Narrowing): This occurs when a larger type is


converted to a smaller type, which requires explicit casting.

*Example*:
```java
double doubleNum = 10.5;
int num = (int) doubleNum; // Explicit casting: double to int
```

### 4. Java Program to Demonstrate Access Specifiers

```java
class AccessSpecifiersExample {
// Different access specifiers
public String publicField = "Public Field";
protected String protectedField = "Protected Field";
private String privateField = "Private Field";
String defaultField = "Default Field"; // default access

public void publicMethod() {


System.out.println("Public Method Accessed!");
}

protected void protectedMethod() {


System.out.println("Protected Method Accessed!");
}

private void privateMethod() {


System.out.println("Private Method Accessed!");
}

void defaultMethod() { // default access


System.out.println("Default Method Accessed!");
}
}

public class TestAccess {


public static void main(String[] args) {
AccessSpecifiersExample obj = new AccessSpecifiersExample();

// Accessing fields
System.out.println(obj.publicField); // Accessible
System.out.println(obj.protectedField); // Accessible
// System.out.println(obj.privateField); // Not accessible
System.out.println(obj.defaultField); // Accessible

// Accessing methods
obj.publicMethod(); // Accessible
obj.protectedMethod(); // Accessible
// obj.privateMethod(); // Not accessible
obj.defaultMethod(); // Accessible
}
}
```

**Explanation of Access Specifiers**:


- `public`: Accessed from any other class.
- `protected`: Accessed within its own package and by subclasses.
- `private`: Accessed only within the declared class.
- Package-private (default): Accessible only within its own package.

### 5. Java Program to Showcase Method Overloading

```java
class Calculator {

// Overloaded methods with different parameter lists


int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

public class TestOverloading {


public static void main(String[] args) {
Calculator calc = new Calculator();

// Calling different overloaded methods


System.out.println("Sum of 2 integers: " + calc.add(10, 20));
System.out.println("Sum of 2 doubles: " + calc.add(10.5, 20.5));
System.out.println("Sum of 3 integers: " + calc.add(10, 20, 30));
}
}
```
In this example, the `Calculator` class has three `add` methods with various
parameter lists. The Java compiler differentiates these methods based on
the number and types of parameters, showcasing method overloading.

This static polymorphism allows methods to be called with different types or


numbers of arguments, providing flexibility in how operations can be
performed.

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.
7. Design a Java program that accepts a string as a command-line
argument and checks whether it is a palindrome. Use StringBuffer or
StringBuilder in your solution.
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.
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.
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.
Here are the responses to your questions with explanations and code
examples:

### 6. Java Class with Static and Non-Static Members

```java
class MemberExample {
static int staticVariable = 5; // static member
int nonStaticVariable; // non-static member

// Constructor
MemberExample(int value) {
this.nonStaticVariable = value;
}

static void staticMethod() {


System.out.println("Static Method called! Static Variable: " +
staticVariable);
}

void nonStaticMethod() {
System.out.println("Non-Static Method called! Non-Static Variable: " +
nonStaticVariable);
}
}

public class TestMemberExample {


public static void main(String[] args) {
// Calling static method and variable
MemberExample.staticMethod();

// Creating instance to call non-static members


MemberExample example = new MemberExample(10);
example.nonStaticMethod();

// Accessing static variable using instance (not recommended)


System.out.println("Accessing Static Variable from Instance: " +
example.staticVariable);
}
}
```

**Explanation**:
- **Static Members**: Belong to the class and can be accessed without
creating an instance of the class. They are shared among all instances of
the class.
- **Non-Static Members**: Belong to the instance of the class. Each object
has its own copy of non-static variables, and they must be accessed
through an instance of the class.

### 7. Palindrome Checker Using Command-Line Arguments

```java
public class PalindromeChecker {
public static void main(String[] args) {
if(args.length != 1) {
System.out.println("Please provide a single string as a command-
line argument.");
return;
}
String original = args[0];
StringBuilder reversed = new StringBuilder(original).reverse();

if(original.equals(reversed.toString())) {
System.out.println(original + " is a palindrome.");
} else {
System.out.println(original + " is not a palindrome.");
}
}
}
```

In this program, we check if the input string (from command-line


arguments) is a palindrome by reversing it using `StringBuilder` and
comparing it to the original string.

### 8. User-Defined Exception for Age Validation

```java
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class AgeValidator {


public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older for
voting.");
} else {
System.out.println("Valid age for voting: " + age);
}
}

public static void main(String[] args) {


int age = 16; // Example input

try {
validateAge(age);
} catch (InvalidAgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
```

In this example, we create a user-defined exception `InvalidAgeException`.


The `validateAge` method throws this exception if the age provided is
below 18. We handle this exception using a `try-catch` block.

### 9. Difference Between Abstract Classes and Interfaces


- **Abstract Classes**: Can have implemented methods (with code) and
can contain constructors. A class can extend only one abstract class (single
inheritance).
- **Interfaces**: Only contain abstract methods (until Java 7) and can
implement multiple interfaces (multiple inheritance). From Java 8
onwards, they can have default methods with implementations.

*Example of an interface*:

```java
interface Animal {
void sound();
}

interface Pet {
void play();
}

class Dog implements Animal, Pet {


public void sound() {
System.out.println("Dog barks");
}

public void play() {


System.out.println("Dog plays fetch");
}
}
public class TestInterfaces {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
dog.play();
}
}
```

In this program, the `Dog` class implements two interfaces (`Animal` and
`Pet`), providing implementations for their methods from both interfaces.

### 10. Demonstrating Use of ArrayList and HashMap

```java
import java.util.ArrayList;
import java.util.HashMap;

public class CollectionDemo {


public static void main(String[] args) {
// ArrayList demonstration
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println("ArrayList Elements:");
for (String name : names) {
System.out.println(name);
}

names.remove("Bob");
System.out.println("After removing Bob: " + names);

// HashMap demonstration
HashMap<String, Integer> ageMap = new HashMap<>();
ageMap.put("Alice", 30);
ageMap.put("Bob", 25);
ageMap.put("Charlie", 22);

System.out.println("HashMap Elements:");
for (String key : ageMap.keySet()) {
System.out.println(key + ": " + ageMap.get(key));
}

ageMap.remove("Charlie");
System.out.println("After removing Charlie: " + ageMap);
}
}
```
In this program:
- We create an `ArrayList` of names, demonstrating how to add, iterate,
and remove elements.
- We create a `HashMap` to hold names as keys and ages as values,
demonstrating how to add, retrieve, and remove elements.

These examples should give you a good understanding of various concepts


in Java! If you have any more questions, feel free to ask!

11. . Write a Java program to read data from a file using `BufferedReader`
and write the processed output to another file using `BufferedWriter`.
Include exception handling mechanisms to manage possible I/O errors.
12. . Implement a Java program that demonstrates the difference between
byte streams and character streams by reading and writing a text file using
both approaches.
13. Explain how object serialization works in Java.
14. . Design a Java program to demonstrate linked structures by
implementing a simple singly linked list with operations like add, delete,
and display.
15. 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.
Certainly! Let's go through each of your questions one by one, providing
Java code examples and explanations for each.

### 11. Reading from a File and Writing to Another File

Here’s a Java program that reads data from one file using `BufferedReader`
and writes the processed output to another file using `BufferedWriter`.
```java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReadWriteExample {


public static void main(String[] args) {
String inputFile = "input.txt"; // Input file path
String outputFile = "output.txt"; // Output file path

try (BufferedReader reader = new BufferedReader(new


FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new
FileWriter(outputFile))) {

String line;
// Read from input file and write to output file
while ((line = reader.readLine()) != null) {
// Process the line if needed (here, we're just writing it as-is)
writer.write(line);
writer.newLine(); // Write a newline for each line read
}
System.out.println("Data has been processed and written to " +
outputFile);
} catch (IOException e) {
System.err.println("An I/O error occurred: " + e.getMessage());
}
}
}
```

**Explanation**:
- The program uses `BufferedReader` to read data from a specified input
file and `BufferedWriter` to write to an output file.
- A try-with-resources statement ensures that the `BufferedReader` and
`BufferedWriter` are closed automatically, reducing resource leaks.
- Exception handling is included to catch any `IOException` that may occur
during file operations.

### 12. Difference Between Byte Streams and Character Streams

Here’s a program that demonstrates reading and writing a text file using
byte streams and character streams.

```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ByteCharStreamDemo {
public static void main(String[] args) {
// File names
String byteInputFile = "byteInput.txt";
String byteOutputFile = "byteOutput.txt";
String charInputFile = "charInput.txt";
String charOutputFile = "charOutput.txt";

// Byte Stream
try (FileInputStream fis = new FileInputStream(byteInputFile);
FileOutputStream fos = new FileOutputStream(byteOutputFile)) {
int byteData;
while ((byteData = fis.read()) != -1) {
fos.write(byteData);
}
System.out.println("Byte stream data written to " + byteOutputFile);
} catch (IOException e) {
System.err.println("Error with byte stream: " + e.getMessage());
}

// Character Stream
try (FileReader fr = new FileReader(charInputFile);
FileWriter fw = new FileWriter(charOutputFile)) {
int charData;
while ((charData = fr.read()) != -1) {
fw.write(charData);
}
System.out.println("Character stream data written to " +
charOutputFile);
} catch (IOException e) {
System.err.println("Error with character stream: " +
e.getMessage());
}
}
}
```

**Explanation**:
- The first part of the program uses `FileInputStream` and
`FileOutputStream`, which are byte streams that read and write raw binary
data (including text as bytes).
- The second part uses `FileReader` and `FileWriter`, which are character
streams designed for reading and writing text data.
- Both approaches manage exceptions gracefully and demonstrate the
difference in data handling.

### 13. How Object Serialization Works in Java

Object serialization in Java is the process of converting an object into a


byte stream so that it can be easily saved to a file or transmitted over a
network. The reverse process (converting a byte stream back to an object)
is called deserialization.
- **Serializable Interface**: To serialize an object, the object's class must
implement the `Serializable` interface. This interface is a marker interface
and does not contain any methods.
- **Serialization Process**: Java converts the object into a format suitable
for storage or transmission.
- **Transient Keyword**: Fields that are marked as `transient` are ignored
during serialization. This is useful for sensitive data or fields that should
not be persisted.

### 14. Singly Linked List Implementation

Here’s a simple implementation of a singly linked list with basic


operations.

```java
class Node {
int data;
Node next;

Node(int data) {
this.data = data;
this.next = null;
}
}

class SinglyLinkedList {
private Node head;
// Method to add a new node
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}

// Method to delete a node


public void delete(int data) {
if (head == null) return;

if (head.data == data) {
head = head.next; // Move head if the node to be deleted is head
return;
}

Node current = head;


while (current.next != null) {
if (current.next.data == data) {
current.next = current.next.next; // Bypass the node to delete it
return;
}
current = current.next;
}
}

// Method to display the list


public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}

public class LinkedListDemo {


public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();
list.add(10);
list.add(20);
list.add(30);

System.out.println("List after adding elements:");


list.display();

list.delete(20);
System.out.println("List after deleting element 20:");
list.display();
}
}
```

**Explanation**:
- `Node` class represents each element of the list, containing data and a
reference to the next node.
- `SinglyLinkedList` class contains methods to add, delete, and display
nodes.
- The `main` method demonstrates adding and deleting elements within
the linked list.

### 15. Exception Handling with `try-catch-finally` and `throws`

Here’s an example demonstrating exception handling using `try-catch-


finally` and `throws`.

```java
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
int result = divide(10, 0); // This will throw an exception
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " +
e.getMessage());
} finally {
System.out.println("Execution of try-catch block completed.");
}
}

static int divide(int a, int b) throws ArithmeticException {


return a / b; // Throws ArithmeticException if b is zero
}
}
```

**Explanation**:
- The `divide` method is defined to throw an `ArithmeticException` if
division by zero occurs.
- In the `main` method, the `divide` method is called inside a `try` block. If
an exception occurs, it is caught in the `catch` block.
- Finally, the `finally` block executes regardless of whether an exception
was thrown or not, making it useful for cleanup operations.

These examples should give you a solid understanding of the various


concepts in Java related to file handling, streams, serialization, linked lists,
and exception handling! If you have any further questions or need
additional explanations, feel free to ask!
16. Develop a Java program to simulate a queue using the `LinkedList` class
from the Collections Framework. Include operations like enqueue,
dequeue, and display.
17. . 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.
18. 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.
19. What is method overriding in Java? What is basic Difference between
Overriding and Overloading?
20. 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.
Sure! Below are explanations and Java code examples for each of the given
tasks.

### 16. Simulating a Queue Using LinkedList

```java
import java.util.LinkedList;

class QueueUsingLinkedList {
private LinkedList<Integer> queue = new LinkedList<>();

// Enqueue: Add an element to the end of the queue


public void enqueue(int data) {
queue.addLast(data);
System.out.println("Enqueued: " + data);
}

// Dequeue: Remove and return the front element of the queue


public int dequeue() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
return queue.removeFirst();
}

// Display the elements in the queue


public void display() {
System.out.println("Queue Elements: " + queue);
}

// Check if the queue is empty


public boolean isEmpty() {
return queue.isEmpty();
}
}

public class QueueDemo {


public static void main(String[] args) {
QueueUsingLinkedList queue = new QueueUsingLinkedList();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);

queue.display();

int dequeuedElement = queue.dequeue();


System.out.println("Dequeued: " + dequeuedElement);

queue.display();
}
}
```

**Explanation**:
- The `QueueUsingLinkedList` class uses a `LinkedList` to simulate a queue.
- Operations include `enqueue` (add to the end), `dequeue` (remove from
the front), and `display` (show current elements).
- The `isEmpty` method checks if the queue has any elements.

### 17. Creating Multiple Threads with Different Priorities

```java
class PriorityThread extends Thread {
private String threadName;
public PriorityThread(String name) {
this.threadName = name;
}

@Override
public void run() {
System.out.println(threadName + " with priority " + getPriority() + " is
running.");
try {
// Simulate work
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
System.out.println(threadName + " has finished executing.");
}
}

public class ThreadPriorityDemo {


public static void main(String[] args) {
// Creating threads with different priorities
PriorityThread lowPriorityThread = new PriorityThread("Low Priority
Thread");
PriorityThread normalPriorityThread = new PriorityThread("Normal
Priority Thread");
PriorityThread highPriorityThread = new PriorityThread("High Priority
Thread");
lowPriorityThread.setPriority(Thread.MIN_PRIORITY); // 1
normalPriorityThread.setPriority(Thread.NORM_PRIORITY); // 5
highPriorityThread.setPriority(Thread.MAX_PRIORITY); // 10

lowPriorityThread.start();
normalPriorityThread.start();
highPriorityThread.start();
}
}
```

**Explanation**:
- This program creates three threads with different priorities. The priorities
range from `MIN_PRIORITY` (1) to `MAX_PRIORITY` (10).
- The execution order observed may show that threads with higher priority
might finish before those with lower priority.
- Thread scheduling depends on the JVM and operating system, so results
can vary.

### 18. Demonstrating Generic Collections with HashMap

```java
import java.util.HashMap;
import java.util.Map;

class Student {
String rollNumber;
String name;

Student(String rollNumber, String name) {


this.rollNumber = rollNumber;
this.name = name;
}

@Override
public String toString() {
return "Roll Number: " + rollNumber + ", Name: " + name;
}
}

public class StudentDetails {


private HashMap<String, Student> studentMap = new HashMap<>();

// Add student
public void addStudent(String rollNumber, String name) {
studentMap.put(rollNumber, new Student(rollNumber, name));
System.out.println("Added student: " + name);
}

// Remove student
public void removeStudent(String rollNumber) {
studentMap.remove(rollNumber);
System.out.println("Removed student with Roll Number: " +
rollNumber);
}

// Search for a student


public void findStudent(String rollNumber) {
Student student = studentMap.get(rollNumber);
if (student != null) {
System.out.println("Found: " + student);
} else {
System.out.println("No student found with Roll Number: " +
rollNumber);
}
}

// Display all students


public void displayStudents() {
System.out.println("Students List:");
for (Map.Entry<String, Student> entry : studentMap.entrySet()) {
System.out.println(entry.getValue());
}
}

public static void main(String[] args) {


StudentDetails studentDetails = new StudentDetails();

studentDetails.addStudent("101", "Alice");
studentDetails.addStudent("102", "Bob");
studentDetails.displayStudents();

studentDetails.findStudent("101");
studentDetails.removeStudent("102");
studentDetails.displayStudents();
}
}
```

**Explanation**:
- The `Student` class holds student details.
- The `StudentDetails` class uses a `HashMap` to manage students,
enabling adding, removing, searching, and displaying students.
- Operations are performed in the `main` method to demonstrate
functionality.

### 19. Method Overriding vs. Overloading

- **Method Overriding**: This occurs when a subclass provides a specific


implementation of a method that is already defined in its superclass. The
method signature (name and parameters) must be the same.

- **Method Overloading**: This occurs when two or more methods in the


same class have the same name but different parameters (different types
or numbers of parameters).

**Key Differences**:
- Overriding is related to inheritance, while overloading is related to the
same class.
- Overriding helps achieve runtime polymorphism; overloading is a form of
compile-time polymorphism.

### 20. Creating and Using a User-Defined Exception

```java
// Custom Exception Class
class InvalidTransactionException extends Exception {
public InvalidTransactionException(String message) {
super(message);
}
}

// Bank Account Class


class BankAccount {
private double balance;

public BankAccount(double initialBalance) {


this.balance = initialBalance;
}

public void withdraw(double amount) throws


InvalidTransactionException {
if (amount > balance) {
throw new InvalidTransactionException("Insufficient funds for
withdrawal.");
}
balance -= amount;
System.out.println("Withdrawal successful! New balance: " +
balance);
}
}

public class CustomExceptionDemo {


public static void main(String[] args) {
BankAccount account = new BankAccount(1000.0);
try {
account.withdraw(1500.0); // Attempting to withdraw more than
current balance
} catch (InvalidTransactionException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
```

**Explanation**:
- The `InvalidTransactionException` class is a custom exception that
extends `Exception`.
- The `BankAccount` class contains methods for basic banking functionality
such as withdrawals, raising a custom exception for insufficient funds.
- In the `main` method, an attempt is made to withdraw an amount
exceeding the account balance, and the exception is caught and handled
appropriately.

These examples illustrate various aspects of Java programming, including


queue data structures, threading, generic collections, exception handling,
and more. If you have further questions or need clarifications on any topic,
feel free to ask!

21. Differentiate between `Set` and `List` in the Java Collections


Framework. Write a program to demonstrate their usage by storing and
iterating over elements.
22. . Explain the concept of object serialization in Java. Write a program to
serialize and deserialize an object of a custom class that stores employee
details.
23. Create a menu based calculator to perform various operations
Certainly! Below are detailed explanations and Java code examples for
each of your requests.

### 21. Difference Between `Set` and `List` in the Java Collections
Framework

- **Set**:
- A collection that does not allow duplicate elements.
- Orders elements based on the implementation: `HashSet` (unordered),
`TreeSet` (sorted), and `LinkedHashSet` (insertion order).
- Ideal for storing unique values.

- **List**:
- An ordered collection that allows duplicate elements.
- Elements can be accessed by their integer index.
- Common implementations include `ArrayList` (dynamic array) and
`LinkedList` (doubly linked list).
- Ideal for maintaining sequences and allowing duplicates.

**Program to Demonstrate Usage**:


```java
import java.util.*;

public class SetListDemo {


public static void main(String[] args) {
// Using List (ArrayList)
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
list.add("Banana"); // Duplicate is allowed in List

System.out.println("Elements in List:");
for (String fruit : list) {
System.out.println(fruit);
}

// Using Set (HashSet)


Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Banana"); // Duplicate will be ignored

System.out.println("\nElements in Set:");
for (String fruit : set) {
System.out.println(fruit);
}
}
}
```

**Explanation**:
- In this program, we create both a `List` using `ArrayList` and a `Set` using
`HashSet`, demonstrating how duplicates are handled differently.

### 22. Object Serialization in Java

Object serialization is the process of converting an object into a byte


stream so that it can be easily saved to a file or sent over a network. The
reverse process is deserialization, which reconstructs the object from the
byte stream.

**Program to Serialize and Deserialize an Employee Class**:


```java
import java.io.*;
class Employee implements Serializable {
private String name;
private int id;

public Employee(String name, int id) {


this.name = name;
this.id = id;
}

public String getName() {


return name;
}

public int getId() {


return id;
}
}

public class SerializationDemo {


public static void main(String[] args) {
// Serialize
Employee employee = new Employee("John Doe", 1234);
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("employee.ser"))) {
oos.writeObject(employee);
System.out.println("Employee object serialized.");
} catch (IOException e) {
e.printStackTrace();
}

// Deserialize
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("employee.ser"))) {
Employee deserializedEmployee = (Employee) ois.readObject();
System.out.println("Deserialized Employee: " +
deserializedEmployee.getName() + ", ID: " + deserializedEmployee.getId());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```

**Explanation**:
- The `Employee` class implements `Serializable`.
- The program serializes an `Employee` object to a file and then deserializes
it, reconstructing the object from the byte stream.

### 23. Menu-Based Calculator

Here’s a simple menu-based calculator that performs basic arithmetic


operations:
```java
import java.util.Scanner;

public class Calculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
double num1, num2;

do {
System.out.println("Menu:");
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 >= 1 && choice <= 4) {


System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
} else {
num1 = num2 = 0; // Prevents uninitialized data for invalid choices
}

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!");
}
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please enter again.");
}
System.out.println();
} while (choice != 5);

scanner.close();
}
}
```

**Explanation**:
- This menu-based calculator uses a `do-while` loop to repeatedly display a
menu until the user chooses to exit.
- It performs addition, subtraction, multiplication, and division based on
user inputs, and immediately displays the result.

These examples should help you understand the concepts related to the
Java Collections Framework, object serialization, and how to create a
simple menu-based calculator in Java. If you have any more questions or
need further assistance, feel free to ask!

25. Write a java program to take temperature at command line in Celsius


and convert in Fahrenheit.
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.
27. Write a Java program to insert an element (specific position) into an
array.
28. Write a Java program to remove duplicate elements from an array.
29. Write a Java program to find the second largest element in a 2D array.
30. Write a Java recursive method to check if a given array is sorted in
ascending order.
Certainly! Below are Java programs that address each of your
programming tasks.

### 25. Convert Temperature from Celsius to Fahrenheit

```java
public class TemperatureConverter {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Please provide the temperature in Celsius.");
return;
}

try {
double celsius = Double.parseDouble(args[0]);
double fahrenheit = (celsius * 9/5) + 32;
System.out.printf("Temperature in Fahrenheit: %.2f%n",
fahrenheit);
} catch (NumberFormatException e) {
System.out.println("Invalid temperature value. Please provide a
valid number.");
}
}
}
```
**Explanation**:
- This program takes one command-line argument representing
temperature in Celsius and converts it to Fahrenheit. It also handles invalid
input gracefully.

### 26. Find Number and Sum of Prime Numbers Between 50 and 100

```java
public class PrimeNumbers {
public static void main(String[] args) {
int count = 0;
int sum = 0;

for (int i = 51; i < 100; i++) {


if (isPrime(i)) {
count++;
sum += i;
}
}

System.out.println("Count of prime numbers between 50 and 100: " +


count);
System.out.println("Sum of prime numbers between 50 and 100: " +
sum);
}
public static boolean isPrime(int num) {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return num > 1; // A prime number is greater than 1
}
}
```

**Explanation**:
- This program iterates from 51 to 99, checks if each number is prime, and
counts the primes while summing them up.

### 27. Insert an Element into an Array at a Specific Position

```java
import java.util.Arrays;

public class InsertElement {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int elementToInsert = 10;
int position = 2; // Position where to insert the element (0-indexed)
if (position < 0 || position > arr.length) {
System.out.println("Invalid position!");
return;
}

int[] newArr = new int[arr.length + 1];


for (int i = 0; i < newArr.length; i++) {
if (i < position) {
newArr[i] = arr[i];
} else if (i == position) {
newArr[i] = elementToInsert;
} else {
newArr[i] = arr[i - 1];
}
}

System.out.println("Array after insertion: " + Arrays.toString(newArr));


}
}
```

**Explanation**:
- The program creates a new array that accommodates the new element
and copies over the old array elements, inserting the new element at the
specified position.

### 28. Remove Duplicate Elements from an Array


```java
import java.util.Arrays;

public class RemoveDuplicates {


public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 4, 5}; // Input array (with duplicates)
int[] uniqueArr = Arrays.stream(arr).distinct().toArray();

System.out.println("Array without duplicates: " +


Arrays.toString(uniqueArr));
}
}
```

**Explanation**:
- This program uses streams to remove duplicates from an array and
converts it back into an array of unique elements.

### 29. Find the Second Largest Element in a 2D Array

```java
public class SecondLargestIn2DArray {
public static void main(String[] args) {
int[][] arr = {
{12, 34, 1},
{45, 2, 34},
{23, 56, 89}
};

System.out.println("Second largest element: " +


findSecondLargest(arr));
}

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;
}
}
```
**Explanation**:
- The program iterates through a 2D array to find the largest and second
largest elements. It keeps track of both values as it goes.

### 30. Recursive Method to Check if an Array is Sorted in Ascending Order

```java
public class CheckSortedArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5}; // Sorted array for example
System.out.println("Is the array sorted? " + isSorted(arr, arr.length));

int[] arr2 = {5, 3, 2, 1}; // Unsorted array for example


System.out.println("Is the array sorted? " + isSorted(arr2,
arr2.length));
}

public static boolean isSorted(int[] arr, int n) {


if (n == 1 || n == 0) {
return true; // An array with 0 or 1 element is sorted
}
return (arr[n - 1] >= arr[n - 2]) && isSorted(arr, n - 1);
}
}
```

**Explanation**:
- This recursive method checks if the array is sorted by comparing the last
element with the second last and recursively calling itself until it reaches
the base case.

These programs cover a range of basic tasks in Java, demonstrating


fundamental concepts and operations. If you have any questions or need
further clarifications, feel free to ask!

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

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.

34. Write a Java program that creates a bank account with concurrent
deposits and withdrawals using threads.
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.
Sure! Below are detailed Java programs corresponding to each of your
requests.
### 31. Class Circle with Radius, Area, and Perimeter Methods

```java
class Circle {
// Private instance variable
private double radius;

// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Getter method for radius


public double getRadius() {
return radius;
}

// Setter method for radius


public void setRadius(double radius) {
if (radius >= 0) {
this.radius = radius;
} else {
System.out.println("Radius cannot be negative.");
}
}
// Method to calculate area
public double calculateArea() {
return Math.PI * radius * radius;
}

// Method to calculate perimeter (circumference)


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

public class CircleDemo {


public static void main(String[] args) {
Circle circle = new Circle(5.0);
System.out.println("Radius: " + circle.getRadius());
System.out.println("Area: " + circle.calculateArea());
System.out.println("Perimeter: " + circle.calculatePerimeter());

// Modifying the radius


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

### 32. Compare Two Strings Lexicographically

```java
import java.util.Scanner;

public class StringComparison {


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

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


String str1 = scanner.nextLine();

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


String str2 = scanner.nextLine();

if (str1.equals(str2)) {
System.out.println("The strings are lexicographically equal.");
} else {
System.out.println("The strings are NOT lexicographically equal.");
}
}
}
```
### 33. Tokenizing a String to Find a Specific Word

```java
import java.util.Scanner;
import java.util.StringTokenizer;

public class TokenizerExample {


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

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


String input = scanner.nextLine();
StringTokenizer tokenizer = new StringTokenizer(input, " ");

boolean foundIndia = false;


while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.equalsIgnoreCase("India")) {
foundIndia = true;
break;
}
}

if (foundIndia) {
System.out.println("The word 'India' is present in the input.");
} else {
System.out.println("The word 'India' is NOT present in the input.");
}
}
}
```

### 34. Concurrent Deposits and Withdrawals in a Bank Account Using


Threads

```java
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 (amount <= balance) {
balance -= amount;
System.out.println("Withdrew: " + amount + ", New Balance: " +
balance);
} else {
System.out.println("Insufficient balance for withdrawal of: " +
amount);
}
}

public double getBalance() {


return balance;
}
}

class DepositThread extends Thread {


private final BankAccount account;
private final 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 final BankAccount account;
private final 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) {
BankAccount account = new BankAccount(1000);

DepositThread d1 = new DepositThread(account, 500);


WithdrawThread w1 = new WithdrawThread(account, 200);
WithdrawThread w2 = new WithdrawThread(account, 900); // This
should fail

d1.start();
w1.start();
w2.start();

// Wait for threads to finish


try {
d1.join();
w1.join();
w2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

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


}
}
```

### 35. Circle Class with Default Constructor and Area Calculation

```java
class Circle {
private double radius;

// No-arg constructor with default radius


public Circle() {
this.radius = 1.0;
}

// Constructor with radius parameter


public Circle(double radius) {
this.radius = radius;
}

// Method to get the area


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

// Method to get radius


public double getRadius() {
return radius;
}
}

public class CircleDemo {


public static void main(String[] args) {
Circle circle1 = new Circle(3.0);
Circle circle2 = new Circle(3.2);
Circle circle3 = new Circle(4.1);

System.out.printf("Circle 1: Radius = %.1f, Area = %.2f%n",


circle1.getRadius(), circle1.getArea());
System.out.printf("Circle 2: Radius = %.1f, Area = %.2f%n",
circle2.getRadius(), circle2.getArea());
System.out.printf("Circle 3: Radius = %.1f, Area = %.2f%n",
circle3.getRadius(), circle3.getArea());
}
}
```

In these solutions, I have implemented a variety of fundamental concepts


of Java, including class design, string input handling, multi-threading, and
object-oriented principles. Each program also includes comments for
better understanding. If you have any more questions or need further
modifications, feel free to ask!

36. Write a Java program to create a class with methods to search for
flights and hotels, and to book and cancel reservations.
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.
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.
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.
40. Write a JAVA Program to demonstrate Constructor overloading and
Method overloading. Also access parent class constructor in child class
Sure! Below are the Java programs for each of the requirements you
specified:

### 36. Flight and Hotel Reservation System

```java
import java.util.ArrayList;
import java.util.List;

class Flight {
String flightNumber;
String destination;

public Flight(String flightNumber, String destination) {


this.flightNumber = flightNumber;
this.destination = destination;
}

@Override
public String toString() {
return flightNumber + " to " + destination;
}
}

class Hotel {
String hotelName;
int availableRooms;

public Hotel(String hotelName, int availableRooms) {


this.hotelName = hotelName;
this.availableRooms = availableRooms;
}

@Override
public String toString() {
return hotelName + " with rooms available: " + availableRooms;
}
}

class TravelAgency {
List<Flight> flights;
List<Hotel> hotels;

public TravelAgency() {
flights = new ArrayList<>();
hotels = new ArrayList<>();
}

public void addFlight(Flight flight) {


flights.add(flight);
}
public void addHotel(Hotel hotel) {
hotels.add(hotel);
}

public void searchFlights() {


System.out.println("Available flights:");
for (Flight flight : flights) {
System.out.println(flight);
}
}

public void searchHotels() {


System.out.println("Available hotels:");
for (Hotel hotel : hotels) {
System.out.println(hotel);
}
}

public void bookFlight(Flight flight) {


System.out.println("Booking flight: " + flight);
}

public void bookHotel(Hotel hotel) {


System.out.println("Booking hotel: " + hotel);
}
public void cancelFlight(Flight flight) {
System.out.println("Cancelled flight: " + flight);
}

public void cancelHotel(Hotel hotel) {


System.out.println("Cancelled hotel: " + hotel);
}
}

public class TravelSystem {


public static void main(String[] args) {
TravelAgency agency = new TravelAgency();
agency.addFlight(new Flight("AA123", "New York"));
agency.addHotel(new Hotel("Luxury Hotel", 5));

agency.searchFlights();
agency.searchHotels();

Flight flight = new Flight("AA123", "New York");


Hotel hotel = new Hotel("Luxury Hotel", 5);

agency.bookFlight(flight);
agency.bookHotel(hotel);

agency.cancelFlight(flight);
agency.cancelHotel(hotel);
}
}
```

### 37. Banking System with Interface

```java
import java.util.ArrayList;
import java.util.List;

interface Account {
void deposit(double amount);
void withdraw(double amount);
double calculateInterest();
double viewBalance();
}

class SavingsAccount implements Account {


private double balance;
private double interestRate;

public SavingsAccount(double initialBalance, double interestRate) {


this.balance = initialBalance;
this.interestRate = interestRate;
}
public void deposit(double amount) {
balance += amount;
}

public void withdraw(double amount) {


if(amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds!");
}
}

public double calculateInterest() {


return balance * interestRate;
}

public double viewBalance() {


return balance;
}
}

class CurrentAccount implements Account {


private double balance;

public CurrentAccount(double initialBalance) {


this.balance = initialBalance;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds!");
}
}

public double calculateInterest() {


return 0; // Current accounts typically do not earn interest
}

public double viewBalance() {


return balance;
}
}

class Bank {
private List<Account> accounts;
public Bank() {
accounts = new ArrayList<>();
}

public void addAccount(Account account) {


accounts.add(account);
}

public void displayBalances() {


for (Account account : accounts) {
System.out.println("Balance: " + account.viewBalance());
}
}
}

public class BankingSystem {


public static void main(String[] args) {
Bank bank = new Bank();

SavingsAccount savAcc = new SavingsAccount(1000.00, 0.05);


CurrentAccount curAcc = new CurrentAccount(1500.00);

bank.addAccount(savAcc);
bank.addAccount(curAcc);

savAcc.deposit(500);
curAcc.withdraw(200);

bank.displayBalances();
System.out.println("Savings Account Interest: " +
savAcc.calculateInterest());
}
}
```

### 38. Employee Management System with Abstract Class

```java
abstract class Employee {
String name;

Employee(String name) {
this.name = name;
}

abstract double calculateSalary();

abstract void displayInfo();


}

class Manager extends Employee {


private double baseSalary;
Manager(String name, double baseSalary) {
super(name);
this.baseSalary = baseSalary;
}

public double calculateSalary() {


return baseSalary + (baseSalary * 0.1); // 10% bonus for manager
}

public void displayInfo() {


System.out.println("Manager Name: " + name + ", Salary: " +
calculateSalary());
}
}

class Programmer extends Employee {


private double baseSalary;

Programmer(String name, double baseSalary) {


super(name);
this.baseSalary = baseSalary;
}

public double calculateSalary() {


return baseSalary; // Programmer's salary is just baseSalary without
bonus
}
public void displayInfo() {
System.out.println("Programmer Name: " + name + ", Salary: " +
calculateSalary());
}
}

public class EmployeeSystem {


public static void main(String[] args) {
Employee manager = new Manager("Alice", 70000);
Employee programmer = new Programmer("Bob", 50000);

manager.displayInfo();
programmer.displayInfo();
}
}
```

### 39. Exception for Odd Numbers

```java
class OddNumberException extends Exception {
public OddNumberException(String message) {
super(message);
}
}
public class OddNumberChecker {
public static void checkEven(int number) throws OddNumberException {
if (number % 2 != 0) {
throw new OddNumberException("The number " + number + " is
odd.");
} else {
System.out.println("The number " + number + " is even.");
}
}

public static void main(String[] args) {


try {
checkEven(3);
} catch (OddNumberException ex) {
System.out.println(ex.getMessage());
}
try {
checkEven(4);
} catch (OddNumberException ex) {
System.out.println(ex.getMessage());
}
}
}
```
### 40. Constructor and Method Overloading

```java
class Parent {
Parent() {
System.out.println("Parent class default constructor.");
}

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

class Child extends Parent {


Child() {
super(); // Calls default constructor of Parent
System.out.println("Child class default constructor.");
}

Child(String message) {
super(message); // Calls constructor of Parent with message
System.out.println("Child class constructor with message.");
}

void display(int number) {


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

void display(String text) {


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

public class ConstructorMethodOverloading {


public static void main(String[] args) {
Child child1 = new Child();
Child child2 = new Child("Hello");

child1.display(5);
child1.display("Hello");
}
}
```

Each program fulfills its respective requirement, allowing you to explore


various features of Java, including classes, inheritance, interfaces, abstract
classes, exception handling, constructor overloading, and method
overloading.

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

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.
46. Write a Java program to get a substring of a given string at two
specified positions.
Sure! Below you’ll find Java programs for each of the tasks you specified:

### 41. Account and Exception Handling

```java
class LessBalanceException extends Exception {
public LessBalanceException(String message) {
super(message);
}
}

class Account {
private double balance;

public Account() {
this.balance = 500.0; // Minimum balance
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposited: Rs " + amount);
} else {
System.out.println("Deposit amount must be positive.");
}
}

public void withdraw(double amount) throws LessBalanceException {


if (balance - amount < 500) {
throw new LessBalanceException("Withdrawal amount (Rs " +
amount + ") is not valid; minimum balance should be Rs 500.");
} else {
balance -= amount;
System.out.println("Withdrawn: Rs " + amount);
}
}

public double getBalance() {


return balance;
}
}

public class AccountTest {


public static void main(String[] args) {
Account account1 = new Account();
Account account2 = new Account();

account1.deposit(1000);
account2.deposit(2000);

try {
account1.withdraw(800); // Valid withdrawal
System.out.println("Account 1 Balance: Rs " +
account1.getBalance());

account2.withdraw(1500); // This will throw LessBalanceException


System.out.println("Account 2 Balance: Rs " +
account2.getBalance());
} catch (LessBalanceException ex) {
System.out.println(ex.getMessage());
}
}
}
```

### 42. Check if All Characters are Vowels

```java
public class VowelChecker {
public static boolean areAllVowels(String str) {
return str.chars().allMatch(c -> "aeiouAEIOU".indexOf(c) != -1);
}

public static void main(String[] args) {


String testStr = "aeiou";
System.out.println("Are all characters vowels? " +
areAllVowels(testStr)); // true

String testStr2 = "hello";


System.out.println("Are all characters vowels? " +
areAllVowels(testStr2)); // false
}
}
```
### 43. Abstract Class and Interfaces

```java
interface InterfaceA {
default void defaultMethod() {
System.out.println("Default Method from Interface A");
}

static void staticMethod() {


System.out.println("Static Method from Interface A");
}
}

interface InterfaceB {
void methodFromB();
}

interface InterfaceC {
void methodFromC();
}

abstract class AbstractClass {


abstract void abstractMethod();
}
class ConcreteClass extends AbstractClass implements InterfaceA,
InterfaceB, InterfaceC {
@Override
void abstractMethod() {
System.out.println("Implemented abstract method from
AbstractClass");
}

@Override
public void methodFromB() {
System.out.println("Implemented method from InterfaceB");
}

@Override
public void methodFromC() {
System.out.println("Implemented method from InterfaceC");
}
}

public class InterfaceTest {


public static void main(String[] args) {
ConcreteClass obj = new ConcreteClass();
obj.abstractMethod();
obj.methodFromB();
obj.methodFromC();
obj.defaultMethod();
InterfaceA.staticMethod();
}
}
```

### 44. Student Class with Various Initialization

```java
class Student {
String name;
int roll_no;
int marks;

// Constructor
Student(String name, int roll_no, int marks) {
this.name = name;
this.roll_no = roll_no;
this.marks = marks;
}

// Method to initialize
void initialize(String name, int roll_no, int marks) {
this.name = name;
this.roll_no = roll_no;
this.marks = marks;
}
void show() {
System.out.println("Name: " + name + ", Roll No: " + roll_no + ",
Marks: " + marks);
}
}

public class StudentTest {


public static void main(String[] args) {
// 1. Using Constructor
Student student1 = new Student("Alice", 101, 85);
student1.show();

// 2. Using Method
Student student2 = new Student("", 0, 0);
student2.initialize("Bob", 102, 90);
student2.show();

// 3. Using Direct Reference


Student student3 = new Student("Charlie", 103, 95);
student3.show();
}
}
```

### 45. Access Specifiers in Java with Packages


**Package Structure:**
- Package P1: `Student.java`, `BTech.java`
- Package P2: `OtherClass.java`

1. **P1/Student.java**
```java
package P1;

public class Student {


public void publicMethod() {
System.out.println("Public Method");
}

protected void protectedMethod() {


System.out.println("Protected Method");
}

void defaultMethod() {
System.out.println("Default Method");
}

private void privateMethod() {


System.out.println("Private Method");
}
}
```
2. **P1/BTech.java**
```java
package P1;

public class BTech {


public void testAccessor() {
Student student = new Student();
student.publicMethod(); // Accessible
student.protectedMethod(); // Accessible (same package)
student.defaultMethod(); // Accessible (same package)
// student.privateMethod(); // Not accessible
}
}
```

3. **P2/OtherClass.java**
```java
package P2;

import P1.Student;

public class OtherClass {


public void testAccessor() {
Student student = new Student();
student.publicMethod(); // Accessible
// student.protectedMethod(); // Not accessible (different package)
// student.defaultMethod(); // Not accessible (different package)
// student.privateMethod(); // Not accessible (different class)
}
}
```

### 46. Substring of Given String

```java
public class SubstringExample {

public static String getSubstring(String str, int start, int end) {


if (start < 0 || end > str.length() || start >= end) {
throw new IllegalArgumentException("Invalid start or end
position.");
}
return str.substring(start, end);
}

public static void main(String[] args) {


String original = "Hello, World!";
int start = 7;
int end = 12;

String substring = getSubstring(original, start, end);


System.out.println("Substring: " + substring); // Output: "World"
}
}
```

These programs cover your specified requirements, demonstrating various


Java features including class creation, exception handling, interface
implementation, method definitions, package usage, and string
manipulation. Let me know if you have any questions or need further
modifications!

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.

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.
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.
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.
52. Create a user defined exception “UnderageforVoting” exception and
throw it when voter’s age is below 18.
53. Write a Java program that creates a bank account with concurrent
deposits and withdrawals using threads.
54. Write a Java program using Anonymous class and override method in
anonymous class.
Sure! Below are the Java programs that fulfill each of the requirements you
specified.

### 48. Employee Abstract Class Example

```java
abstract class Employee {
String name;
double baseSalary;

Employee(String name, double baseSalary) {


this.name = name;
this.baseSalary = baseSalary;
}

abstract double calculateSalary();


abstract void displayInfo();
}

class Manager extends Employee {


private double bonus;
Manager(String name, double baseSalary, double bonus) {
super(name, baseSalary);
this.bonus = bonus;
}

@Override
double calculateSalary() {
return baseSalary + bonus;
}

@Override
void displayInfo() {
System.out.println("Manager's Name: " + name + ", Salary: " +
calculateSalary());
}
}

class Programmer extends Employee {


private double overtimePay;

Programmer(String name, double baseSalary, double overtimePay) {


super(name, baseSalary);
this.overtimePay = overtimePay;
}
@Override
double calculateSalary() {
return baseSalary + overtimePay;
}

@Override
void displayInfo() {
System.out.println("Programmer's Name: " + name + ", Salary: " +
calculateSalary());
}
}

public class EmployeeTest {


public static void main(String[] args) {
Employee manager = new Manager("Alice", 90000, 15000);
Employee programmer = new Programmer("Bob", 70000, 5000);

manager.displayInfo();
programmer.displayInfo();
}
}
```

### 49. Shape Interface Example

```java
interface Shape {
double getArea();
}

class Rectangle implements Shape {


private double width, height;

Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
public double getArea() {
return width * height;
}
}

class Circle implements Shape {


private double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
public double getArea() {
return Math.PI * radius * radius;
}
}

class Triangle implements Shape {


private double base, height;

Triangle(double base, double height) {


this.base = base;
this.height = height;
}

@Override
public double getArea() {
return 0.5 * base * height;
}
}

public class ShapeTest {


public static void main(String[] args) {
Shape rectangle = new Rectangle(5, 10);
Shape circle = new Circle(7);
Shape triangle = new Triangle(4, 8);

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


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

### 50. Banking System Example

```java
import java.util.ArrayList;
import java.util.List;

interface Account {
void deposit(double amount);
void withdraw(double amount);
double calculateInterest(); // Assuming it's only for SavingsAccount
double viewBalance();
}

class SavingsAccount implements Account {


private double balance;
private double interestRate;

public SavingsAccount(double initialBalance, double interestRate) {


this.balance = initialBalance;
this.interestRate = interestRate;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) {


if (balance - amount >= 500) {
balance -= amount;
} else {
System.out.println("Cannot withdraw: Insufficient funds. Minimum
balance must be Rs 500.");
}
}

public double calculateInterest() {


return balance * interestRate;
}

public double viewBalance() {


return balance;
}
}

class CurrentAccount implements Account {


private double balance;
public CurrentAccount(double initialBalance) {
this.balance = initialBalance;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Cannot withdraw: Insufficient funds.");
}
}

public double calculateInterest() {


return 0; // Current accounts typically do not earn interest
}

public double viewBalance() {


return balance;
}
}
class Bank {
private List<Account> accounts;

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

public void addAccount(Account account) {


accounts.add(account);
}

public void showBalances() {


for (Account account : accounts) {
System.out.println("Balance: Rs " + account.viewBalance());
}
}
}

public class BankingSystem {


public static void main(String[] args) {
Bank bank = new Bank();

SavingsAccount savAcc = new SavingsAccount(1000.00, 0.05);


CurrentAccount curAcc = new CurrentAccount(1500.00);
bank.addAccount(savAcc);
bank.addAccount(curAcc);

savAcc.deposit(200);
curAcc.withdraw(100);

bank.showBalances();
System.out.println("Savings Account Interest: " +
savAcc.calculateInterest());
}
}
```

### 51. Odd Number Exception

```java
class OddNumberException extends Exception {
public OddNumberException(String message) {
super(message);
}
}

public class OddNumberChecker {


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

public static void main(String[] args) {


try {
checkEven(3);
} catch (OddNumberException ex) {
System.out.println(ex.getMessage());
}
try {
checkEven(4);
} catch (OddNumberException ex) {
System.out.println(ex.getMessage());
}
}
}
```

### 52. Underage Voting Exception

```java
class UnderageForVotingException extends Exception {
public UnderageForVotingException(String message) {
super(message);
}
}

public class VotingEligibility {


public static void checkVotingEligibility(int age) throws
UnderageForVotingException {
if (age < 18) {
throw new UnderageForVotingException("Voter's age is below 18:
Age " + age);
} else {
System.out.println("Voter is eligible to vote.");
}
}

public static void main(String[] args) {


try {
checkVotingEligibility(16);
} catch (UnderageForVotingException ex) {
System.out.println(ex.getMessage());
}
try {
checkVotingEligibility(20);
} catch (UnderageForVotingException ex) {
System.out.println(ex.getMessage());
}
}
}
```

### 53. Concurrent Bank Account Operations

```java
class BankAccount {
private double balance;

public synchronized void deposit(double amount) {


balance += amount;
System.out.println("Deposited: Rs " + amount + ", Current Balance: Rs
" + balance);
}

public synchronized void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
System.out.println("Withdrew: Rs " + amount + ", Current Balance:
Rs " + balance);
} else {
System.out.println("Insufficient funds for withdrawal of Rs " +
amount);
}
}

public double getBalance() {


return balance;
}
}

class DepositThread extends Thread {


private BankAccount account;
private double amount;

DepositThread(BankAccount account, double amount) {


this.account = account;
this.amount = amount;
}

public void run() {


account.deposit(amount);
}
}

class WithdrawThread extends Thread {


private BankAccount account;
private double amount;

WithdrawThread(BankAccount account, double amount) {


this.account = account;
this.amount = amount;
}
public void run() {
account.withdraw(amount);
}
}

public class ConcurrentBankingSystem {


public static void main(String[] args) {
BankAccount account = new BankAccount();

DepositThread deposit1 = new DepositThread(account, 1000);


WithdrawThread withdraw1 = new WithdrawThread(account, 500);

deposit1.start();
withdraw1.start();

try {
deposit1.join();
withdraw1.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}

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


}
}
```
### 54. Anonymous Class Example

```java
abstract class AbstractClass {
abstract void display();
}

public class AnonymousClassExample {


public static void main(String[] args) {
AbstractClass obj = new AbstractClass() {
@Override
void display() {
System.out.println("Display method overridden in anonymous
class.");
}
};

obj.display();
}
}
```

These Java programs cover the requirements you've listed, demonstrating


the use of abstract classes, interfaces, user-defined exceptions,
multithreading, and anonymous classes among other concepts. Let me
know if you have any questions or need further modifications!
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.
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?
Here’s the implementation and analysis for both tasks:

---

Task 56: BankAccount Class

Implementation:

public class BankAccount {


// Static variable shared across all instances
private static double interestRate = 0.03;

// Final variable unique to each account, set at initialization


private final String accountNumber;

// Balance for the account


private double balance;

// Constructor to initialize account number and initial balance


public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}

// Getter for accountNumber


public String getAccountNumber() {
return accountNumber;
}

// Getter for balance


public double getBalance() {
return balance;
}

// Static getter for interestRate


public static double getInterestRate() {
return interestRate;
}

// Static setter for interestRate


public static void setInterestRate(double newRate) {
interestRate = newRate;
}

// Method to deposit money


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
// Method to withdraw money
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}

// Method to calculate interest based on the balance and shared


interestRate
public double calculateInterest() {
return balance * interestRate;
}
}

---

Significance of final and static:

1. final:

The final keyword ensures immutability of the accountNumber. Once


assigned during object creation, it cannot be changed.

This is essential for security and integrity, as account numbers should not
be altered after the account is created.
2. static:

The static keyword indicates that interestRate is shared among all


instances of the class.

It avoids duplication and ensures consistency of the interest rate across all
accounts.

Performance is enhanced as the memory for the static variable is allocated


only once at the class level.

---

Task 57: MathUtils Class

Implementation:

public final class MathUtils {

// Private constructor to prevent instantiation


private MathUtils() {
throw new UnsupportedOperationException("This is a utility class and
cannot be instantiated.");
}

// Static method to find the maximum of two numbers


public static int max(int a, int b) {
return (a > b) ? a : b;
}

// Static method to calculate the power of a number


public static double power(double base, int exponent) {
return Math.pow(base, exponent);
}

// Static method to calculate factorial


public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Factorial is not defined for
negative numbers.");
}
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
---

Key Points:

1. final Class:

Declaring the class as final prevents it from being subclassed, ensuring the
utility methods are not overridden or extended.

This maintains the integrity and predictability of the utility methods.

2. Static Methods:

Utility methods are designed to be independent of object state and belong


to the class itself.

static ensures no instantiation is required, improving memory efficiency


and usability.

3. Private Constructor:
Prevents instantiation of the class, as it serves purely as a container for
utility methods.

---

Both classes leverage static and final to achieve immutability, resource


sharing, and optimized performance, aligning with their specific design
requirements.
Explanation for Making Methods Static (Part b):

Why Static Methods Are Appropriate:

1. Class-Level Behavior:

Static methods belong to the class rather than any specific instance.

For utility classes like MathUtils, the operations (e.g., max, power,
factorial) are general-purpose and do not depend on instance-specific
data.

2. Direct Accessibility:
Static methods can be called directly using the class name (e.g.,
MathUtils.max(5, 10)), which makes the code cleaner and avoids the need
to create unnecessary objects.

3. Improved Performance:

Since no objects are created for using the methods, there is a reduction in
memory overhead and faster method invocation.

4. Immutability:

Static methods inherently do not alter the state of any instance, promoting
immutability and thread safety for stateless operations.

Advantages:

1. Ease of Use:

Methods are accessible directly without requiring an object.


Ideal for utility operations that are independent of object state.

2. Memory Efficiency:

No need to create objects, saving memory.

3. Thread Safety:

Since static methods don’t rely on instance-specific data, they are thread-
safe for stateless operations.

Limitations:

1. No Polymorphism:

Static methods cannot be overridden, which limits their flexibility in


scenarios where behavior might need to vary.
2. Hard to Mock:

In testing, static methods are harder to mock compared to instance


methods, making testing less flexible.

3. Overuse:

Overusing static methods might lead to procedural-style coding, reducing


the advantages of object-oriented design.

---

Implications of Marking the Class as Final (Part c):

Why Marking the Class as Final Is Useful:

1. Prevents Subclassing:

By marking the class as final, it cannot be extended. This ensures that the
core utility logic remains unaltered and consistent.
2. Design Intent:

Declaring the class final communicates to developers that this class is


complete and is not meant to be extended.

3. Security:

Prevents malicious or accidental overriding of methods that could alter the


behavior of utility operations.

Advantages:

1. Predictability:

Ensures the behavior of the class methods remains unchanged, making it


reliable across the codebase.
2. Code Stability:

Eliminates the risk of breaking changes from subclasses that might modify
core functionality.

3. Simplified Maintenance:

Reduces complexity by avoiding inheritance hierarchies for a utility class.

Limitations:

1. Reduced Extensibility:

Developers cannot extend the class to add custom behaviors. For instance,
if additional mathematical operations are needed, they must be
implemented in a new class.

2. Future Changes:
If the utility class needs significant modifications or extensions in the
future, the lack of extensibility could lead to code duplication or less
elegant solutions.

Impact on Design:

Marking the class final simplifies the design by preventing misuse but
requires careful foresight to ensure the class covers all anticipated use
cases. It is a trade-off between long-term stability and flexibility.

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.
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.
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
Task 58: Course Registration System

Implementation

Student Class:

import java.util.ArrayList;
import java.util.List;

public class Student {


private String name;
private String studentID;
private List<Course> registeredCourses;
private int maxCredits = 18; // Example maximum credits limit
private int currentCredits = 0;

// Constructor
public Student(String name, String studentID) {
this.name = name;
this.studentID = studentID;
this.registeredCourses = new ArrayList<>();
}
// Public method to register for a course
public void registerForCourse(Course course) {
if (checkEligibility(course)) {
addCourseToStudentRecord(course);
System.out.println(name + " successfully registered for " +
course.getCourseName());
} else {
System.out.println("Registration failed for " +
course.getCourseName());
}
}

// Protected method to check eligibility


protected boolean checkEligibility(Course course) {
if (currentCredits + course.getCredits() > maxCredits) {
System.out.println("Cannot register: Exceeds maximum credits.");
return false;
}
if (registeredCourses.contains(course)) {
System.out.println("Cannot register: Already registered for the
course.");
return false;
}
return true;
}

// Private method to add course to the student record


private void addCourseToStudentRecord(Course course) {
registeredCourses.add(course);
currentCredits += course.getCredits();
}
}

Course Class:

public class Course {


private String courseName;
private String courseID;
private int maxCapacity;
private int enrolledStudents = 0;
private int credits;

// Constructor
public Course(String courseName, String courseID, int maxCapacity, int
credits) {
this.courseName = courseName;
this.courseID = courseID;
this.maxCapacity = maxCapacity;
this.credits = credits;
}

// Getters
public String getCourseName() {
return courseName;
}

public int getCredits() {


return credits;
}

// Method to enroll a student


public boolean enrollStudent() {
if (enrolledStudents < maxCapacity) {
enrolledStudents++;
return true;
}
System.out.println("Course " + courseName + " is full.");
return false;
}
}

---

Task 59: Multithreaded File I/O Operations

Implementation

import java.io.*;
public class FileIOThread extends Thread {
private String sourceFile;
private String destinationFile;

// Constructor
public FileIOThread(String sourceFile, String destinationFile) {
this.sourceFile = sourceFile;
this.destinationFile = destinationFile;
}

@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new
FileReader(sourceFile));
BufferedWriter writer = new BufferedWriter(new
FileWriter(destinationFile))) {

String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
System.out.println("File copy operation completed.");
} catch (IOException e) {
System.out.println("Error during file I/O: " + e.getMessage());
}
}

public static void main(String[] args) {


FileIOThread thread = new FileIOThread("source.txt",
"destination.txt");
thread.start();
}
}

---

Task 60: Thread Synchronization Using synchronized

Implementation

class SharedResource {
private int counter = 0;

// Synchronized method to increment the counter


public synchronized void increment() {
counter++;
System.out.println(Thread.currentThread().getName() + "
incremented counter to " + counter);
}

// Getter for counter


public synchronized int getCounter() {
return counter;
}
}

public class ThreadSynchronization {


public static void main(String[] args) {
SharedResource resource = new SharedResource();

// Thread 1
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.increment();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}, "Thread-1");

// Thread 2
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.increment();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}, "Thread-2");

// Start threads
thread1.start();
thread2.start();
}
}

---

Explanation:

Task 58: Encapsulation is achieved using private, protected, and public


access modifiers to segregate responsibilities.

Task 59: The program uses multithreading to copy files efficiently while
handling exceptions to ensure robust error handling.

Task 60: Synchronization ensures consistent access to the shared resource


(counter) by multiple threads, preventing data inconsistency.

You might also like