j1 java (1)
j1 java (1)
*Example in Java*:
```java
class Person {
private String name; // private field
*Example in Java*:
```java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
*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.
*Example*:
```java
int num = 10;
double doubleNum = num; // Implicit casting: int to double
```
*Example*:
```java
double doubleNum = 10.5;
int num = (int) doubleNum; // Explicit casting: double to int
```
```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
// 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
}
}
```
```java
class Calculator {
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:
```java
class MemberExample {
static int staticVariable = 5; // static member
int nonStaticVariable; // non-static member
// Constructor
MemberExample(int value) {
this.nonStaticVariable = value;
}
void nonStaticMethod() {
System.out.println("Non-Static Method called! Non-Static Variable: " +
nonStaticVariable);
}
}
**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.
```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.");
}
}
}
```
```java
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
try {
validateAge(age);
} catch (InvalidAgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
```
*Example of an interface*:
```java
interface Animal {
void sound();
}
interface Pet {
void play();
}
In this program, the `Dog` class implements two interfaces (`Animal` and
`Pet`), providing implementations for their methods from both interfaces.
```java
import java.util.ArrayList;
import java.util.HashMap;
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.
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.
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;
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.
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.
```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;
}
}
if (head.data == data) {
head = head.next; // Move head if the node to be deleted is head
return;
}
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.
```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.");
}
}
**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.
```java
import java.util.LinkedList;
class QueueUsingLinkedList {
private LinkedList<Integer> queue = new LinkedList<>();
queue.display();
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.
```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.");
}
}
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.
```java
import java.util.HashMap;
import java.util.Map;
class Student {
String rollNumber;
String name;
@Override
public String toString() {
return "Roll Number: " + rollNumber + ", Name: " + name;
}
}
// 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);
}
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.
**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.
```java
// Custom Exception Class
class InvalidTransactionException extends Exception {
public InvalidTransactionException(String message) {
super(message);
}
}
**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.
### 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.
System.out.println("Elements in List:");
for (String fruit : list) {
System.out.println(fruit);
}
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.
// 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.
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();
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!
```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;
**Explanation**:
- This program iterates from 51 to 99, checks if each number is prime, and
counts the primes while summing them up.
```java
import java.util.Arrays;
**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.
**Explanation**:
- This program uses streams to remove duplicates from an array and
converts it back into an array of unique elements.
```java
public class SecondLargestIn2DArray {
public static void main(String[] args) {
int[][] arr = {
{12, 34, 1},
{45, 2, 34},
{23, 56, 89}
};
```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));
**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.
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;
}
```java
import java.util.Scanner;
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;
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.");
}
}
}
```
```java
class BankAccount {
private double balance;
@Override
public void run() {
account.deposit(amount);
}
}
class WithdrawThread extends Thread {
private final BankAccount account;
private final double amount;
@Override
public void run() {
account.withdraw(amount);
}
}
d1.start();
w1.start();
w2.start();
### 35. Circle Class with Default Constructor and Area Calculation
```java
class Circle {
private double radius;
36. Write a Java program to create a class with methods to search for
flights and hotels, and to book and cancel reservations.
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:
```java
import java.util.ArrayList;
import java.util.List;
class Flight {
String flightNumber;
String destination;
@Override
public String toString() {
return flightNumber + " to " + destination;
}
}
class Hotel {
String hotelName;
int 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<>();
}
agency.searchFlights();
agency.searchHotels();
agency.bookFlight(flight);
agency.bookHotel(hotel);
agency.cancelFlight(flight);
agency.cancelHotel(hotel);
}
}
```
```java
import java.util.ArrayList;
import java.util.List;
interface Account {
void deposit(double amount);
void withdraw(double amount);
double calculateInterest();
double viewBalance();
}
class Bank {
private List<Account> accounts;
public Bank() {
accounts = new ArrayList<>();
}
bank.addAccount(savAcc);
bank.addAccount(curAcc);
savAcc.deposit(500);
curAcc.withdraw(200);
bank.displayBalances();
System.out.println("Savings Account Interest: " +
savAcc.calculateInterest());
}
}
```
```java
abstract class Employee {
String name;
Employee(String name) {
this.name = name;
}
manager.displayInfo();
programmer.displayInfo();
}
}
```
```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.");
}
}
```java
class Parent {
Parent() {
System.out.println("Parent class default constructor.");
}
Parent(String message) {
System.out.println("Parent class constructor with message: " +
message);
}
}
Child(String message) {
super(message); // Calls constructor of Parent with message
System.out.println("Child class constructor with message.");
}
child1.display(5);
child1.display("Hello");
}
}
```
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:
```java
class LessBalanceException extends Exception {
public LessBalanceException(String message) {
super(message);
}
}
class Account {
private double balance;
public Account() {
this.balance = 500.0; // Minimum balance
}
account1.deposit(1000);
account2.deposit(2000);
try {
account1.withdraw(800); // Valid withdrawal
System.out.println("Account 1 Balance: Rs " +
account1.getBalance());
```java
public class VowelChecker {
public static boolean areAllVowels(String str) {
return str.chars().allMatch(c -> "aeiouAEIOU".indexOf(c) != -1);
}
```java
interface InterfaceA {
default void defaultMethod() {
System.out.println("Default Method from Interface A");
}
interface InterfaceB {
void methodFromB();
}
interface InterfaceC {
void methodFromC();
}
@Override
public void methodFromB() {
System.out.println("Implemented method from InterfaceB");
}
@Override
public void methodFromC() {
System.out.println("Implemented method from InterfaceC");
}
}
```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);
}
}
// 2. Using Method
Student student2 = new Student("", 0, 0);
student2.initialize("Bob", 102, 90);
student2.show();
1. **P1/Student.java**
```java
package P1;
void defaultMethod() {
System.out.println("Default Method");
}
3. **P2/OtherClass.java**
```java
package P2;
import P1.Student;
```java
public class SubstringExample {
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.
```java
abstract class Employee {
String name;
double baseSalary;
@Override
double calculateSalary() {
return baseSalary + bonus;
}
@Override
void displayInfo() {
System.out.println("Manager's Name: " + name + ", Salary: " +
calculateSalary());
}
}
@Override
void displayInfo() {
System.out.println("Programmer's Name: " + name + ", Salary: " +
calculateSalary());
}
}
manager.displayInfo();
programmer.displayInfo();
}
}
```
```java
interface Shape {
double getArea();
}
@Override
public double getArea() {
return width * height;
}
}
Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
```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();
}
public Bank() {
accounts = new ArrayList<>();
}
savAcc.deposit(200);
curAcc.withdraw(100);
bank.showBalances();
System.out.println("Savings Account Interest: " +
savAcc.calculateInterest());
}
}
```
```java
class OddNumberException extends Exception {
public OddNumberException(String message) {
super(message);
}
}
```java
class UnderageForVotingException extends Exception {
public UnderageForVotingException(String message) {
super(message);
}
}
```java
class BankAccount {
private double balance;
deposit1.start();
withdraw1.start();
try {
deposit1.join();
withdraw1.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
```java
abstract class AbstractClass {
abstract void display();
}
obj.display();
}
}
```
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:
---
Implementation:
---
1. final:
This is essential for security and integrity, as account numbers should not
be altered after the account is created.
2. static:
It avoids duplication and ensures consistency of the interest rate across all
accounts.
---
Implementation:
Key Points:
1. final Class:
Declaring the class as final prevents it from being subclassed, ensuring the
utility methods are not overridden or extended.
2. Static Methods:
3. Private Constructor:
Prevents instantiation of the class, as it serves purely as a container for
utility methods.
---
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:
2. Memory Efficiency:
3. Thread Safety:
Since static methods don’t rely on instance-specific data, they are thread-
safe for stateless operations.
Limitations:
1. No Polymorphism:
3. Overuse:
---
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:
3. Security:
Advantages:
1. Predictability:
Eliminates the risk of breaking changes from subclasses that might modify
core functionality.
3. Simplified Maintenance:
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;
// 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());
}
}
Course Class:
// 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;
}
---
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());
}
}
---
Implementation
class SharedResource {
private int counter = 0;
// 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 59: The program uses multithreading to copy files efficiently while
handling exceptions to ensure robust error handling.