Constructor Type Of Constructor With Ex
Q1 Create a class named Student with properties like name, age, and studentId.
Implement a constructor to initialize these properties when a Student object is created.
Add methods to display student information.
public class Student {
private String name;
private int age;
private String studentId;
public Student(String name, int age, String studentId) {
this.name = name;
this.age = age;
this.studentId = studentId;
public void displayInfo() {
System.out.println("Student Name: " + name);
System.out.println("Age: " + age);
System.out.println("Student ID: " + studentId);
public static void main(String[] args) {
Student student1 = new Student("Alice", 20, "S12345");
student1.displayInfo();
}
Write a program to print the area of a rectangle by creating a class named 'Area'
taking the values of its length and breadth as parameters of its constructor and
having a method named 'returnArea' which returns the area of the rectangle.
Length and breadth of rectangle are entered through keyboard.
import java.util.Scanner;
class Area {
private double length;
private double breadth;
public Area(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}
public double returnArea() {
return length * breadth;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the breadth of the rectangle: ");
double breadth = scanner.nextDouble();
Area rectangle = new Area(length, breadth);
System.out.println("Area of the rectangle: " + rectangle.returnArea());
scanner.close();
}
}
Write a program to store Student details such as name(String), roll no(int) and fees(float). Declare
two contructors, a default contructor with a print statement “System.out.println("Default");” and
a parameterized constructor to intialise all t\he three variables. Use this to execute the default
constructor from the parameterized constructor. Display the values using a display method.
public class Student {
private String name;
private int rollNo;
private float fees;
// Default constructor
public Student() {
System.out.println("Default");
}
// Parameterized constructor
public Student(String name, int rollNo, float fees) {
// Invoking the default constructor from the parameterized constructor
this();
this.name = name;
this.rollNo = rollNo;
this.fees = fees;
}
// Method to display student details
public void display() {
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
System.out.println("Fees: " + fees);
}
public static void main(String[] args) {
// Creating an instance using parameterized constructor
Student student1 = new Student("Alice", 123, 1000.0f);
student1.display();
}
}
Write a Java class named Person with member variables name and age. Implement a default
constructor that initializes name to "Unknown" and age to 0. Create a parameterized
constructor for the Person class that takes two parameters (name and age) and initializes the
member variables accordingly. Extend the Person class to create a subclass named Student.
Add a member variable studentId to the Student class. Implement a parameterized constructor
for the Student class that initializes name, age, and studentId.
// Person class
class Person {
protected String name;
protected int age;
// Default constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
// Student subclass extending Person
class Student extends Person {
private String studentId;
// Parameterized constructor
public Student(String name, int age, String studentId) {
super(name, age);
this.studentId = studentId;
}
// Getter method for studentId
public String getStudentId() {
return studentId;
}
}
public class Main {
public static void main(String[] args) {
// Creating a Person object using default constructor
Person person1 = new Person();
System.out.println("Person 1:");
System.out.println("Name: " + person1.getName());
System.out.println("Age: " + person1.getAge());
// Creating a Person object using parameterized constructor
Person person2 = new Person("Alice", 25);
System.out.println("\nPerson 2:");
System.out.println("Name: " + person2.getName());
System.out.println("Age: " + person2.getAge());
// Creating a Student object using parameterized constructor
Student student = new Student("Bob", 20, "S12345");
System.out.println("\nStudent:");
System.out.println("Name: " + student.getName());
System.out.println("Age: " + student.getAge());
System.out.println("Student ID: " + student.getStudentId());
}
}
INHERITANCE N IT'S TYPES WITH EXAMPLE
Create a superclass named Animal with a method sound(). Extend this class to create a
subclass named Dog with a method bark().
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
class Dog extends Animal {
public void bark() {
System.out.println("Dog barks");
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.sound();
Dog dog = new Dog();
dog.sound();
dog.bark();
}
Create a superclass named Vehicle with a method start(). Extend this class to create a
subclass named Car, and then further extend Car to create a subclass named
SportsCar, each with additional methods.
class Vehicle {
public void start() {
System.out.println("Vehicle starts");
}
}
class Car extends Vehicle {
public void stop() {
System.out.println("Car stops");
}
}
class SportsCar extends Car {
public void accelerate() {
System.out.println("SportsCar accelerates");
}
}
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.start();
Car car = new Car();
car.start();
car.stop();
SportsCar sportsCar = new SportsCar();
sportsCar.start();
sportsCar.stop();
sportsCar.accelerate();
}
}
Design a banking system with multiple account types: SavingsAccount,
CheckingAccount, and LoanAccount.
Implement inheritance to model these account types with common properties and
methods such as accountNumber, balance, deposit, and withdraw.
Consider how to handle interest calculations for savings accounts and overdraft
protection for checking accounts.
// Account superclass
class Account {
protected String accountNumber;
protected double balance;
public Account(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Insu icient funds");
}
}
public void displayBalance() {
System.out.println("Current Balance: $" + balance);
}
}
// SavingsAccount subclass extending Account
class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(String accountNumber, double balance, double interestRate) {
super(accountNumber, balance);
this.interestRate = interestRate;
}
public void calculateInterest() {
double interest = balance * (interestRate / 100);
balance += interest;
System.out.println("Interest added: $" + interest);
}
}
// CheckingAccount subclass extending Account
class CheckingAccount extends Account {
private double overdraftLimit;
public CheckingAccount(String accountNumber, double balance, double overdraftLimit) {
super(accountNumber, balance);
this.overdraftLimit = overdraftLimit;
}
@Override
public void withdraw(double amount) {
if (balance + overdraftLimit >= amount) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Exceeds overdraft limit");
}
}
}
// LoanAccount subclass extending Account
class LoanAccount extends Account {
private double interestRate;
public LoanAccount(String accountNumber, double balance, double interestRate) {
super(accountNumber, balance);
this.interestRate = interestRate;
}
public void applyInterest() {
double interest = balance * (interestRate / 100);
balance += interest;
System.out.println("Interest added: $" + interest);
}
}
public class Main {
public static void main(String[] args) {
// Testing SavingsAccount
SavingsAccount savingsAccount = new SavingsAccount("SA001", 1000.0, 2.5);
savingsAccount.displayBalance();
savingsAccount.calculateInterest();
savingsAccount.displayBalance();
// Testing CheckingAccount
CheckingAccount checkingAccount = new CheckingAccount("CA001", 500.0, 200.0);
checkingAccount.displayBalance();
checkingAccount.withdraw(700.0);
checkingAccount.displayBalance();
// Testing LoanAccount
LoanAccount loanAccount = new LoanAccount("LA001", 10000.0, 5.0);
loanAccount.displayBalance();
loanAccount.applyInterest();
loanAccount.displayBalance();
}
}
polymorphism and it's types with example
Write a program to demonstrate method overloading. A method which can add two numbers
should be overloaded: Once without parameters, once with two integer numbers and one with
two double numbers. Display the results in the methods.
public class MethodOverloadingDemo {
// Method to add two integers
public void add() {
int num1 = 5;
int num2 = 10;
int sum = num1 + num2;
System.out.println("Sum of two integers (5 and 10) is: " + sum);
}
// Method to add two integers provided as parameters
public void add(int num1, int num2) {
int sum = num1 + num2;
System.out.println("Sum of two integers is: " + sum);
}
// Method to add two double numbers provided as parameters
public void add(double num1, double num2) {
double sum = num1 + num2;
System.out.println("Sum of two double numbers is: " + sum);
}
public static void main(String[] args) {
MethodOverloadingDemo demo = new MethodOverloadingDemo();
// Calling the method without parameters
demo.add();
// Calling the method with two integer parameters
demo.add(20, 30);
// Calling the method with two double parameters
demo.add(3.5, 4.5);
}
}
Develop a program in Java which has a static method min2() that takes two int arguments and
returns the value of the smallest one. Add an overloaded function that does the same thing with
two double values and display the output.
public class MinValueDemo {
// Method to find the minimum of two integers
public static int min2(int num1, int num2) {
return Math.min(num1, num2);
// Overloaded method to find the minimum of two doubles
public static double min2(double num1, double num2) {
return Math.min(num1, num2);
public static void main(String[] args) {
// Test with integers
int intResult = min2(5, 10);
System.out.println("Minimum of 5 and 10 is: " + intResult);
// Test with doubles
double doubleResult = min2(3.5, 4.5);
System.out.println("Minimum of 3.5 and 4.5 is: " + doubleResult);
}
Consider a scenario where you have a base class Shape with a method calculateArea() to
calculate the area of a shape. Now, you want to create subclasses Rectangle and Circle that
inherit from the Shape class. Both Rectangle and Circle should have their own implementation
of the calculateArea() method to calculate the area specific to their shape. Design the class
hierarchy and implement the calculateArea() method in each subclass to override the method
from the Shape class. Also, create instances of Rectangle and Circle, and demonstrate how the
overridden methods work.
// Shape class
class Shape {
public double calculateArea() {
return 0.0; // Default implementation for unknown shape
}
}
// Rectangle subclass extending Shape
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculateArea() {
return length * width;
}
}
// Circle subclass extending Shape
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
// Create instances of Rectangle and Circle
Rectangle rectangle = new Rectangle(5.0, 4.0);
Circle circle = new Circle(3.0);
// Calculate and display the area of Rectangle
double rectangleArea = rectangle.calculateArea();
System.out.println("Area of Rectangle: " + rectangleArea);
// Calculate and display the area of Circle
double circleArea = circle.calculateArea();
System.out.println("Area of Circle: " + circleArea);
}
}
Data abstraction with example
You are tasked with creating a simple system to manage shapes. Design an abstract class
Shape with abstract methods calculateArea() and calculatePerimeter(). Then, create concrete
subclasses such as Rectangle and Circle that extend the Shape class and implement the
abstract methods.
// Abstract Shape class
abstract class Shape {
// Abstract methods to calculate area and perimeter
public abstract double calculateArea();
public abstract double calculatePerimeter();
}
// Rectangle subclass extending Shape
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculateArea() {
return length * width;
}
@Override
public double calculatePerimeter() {
return 2 * (length + width);
}
}
// Circle subclass extending Shape
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
public class Main {
public static void main(String[] args) {
// Create instances of Rectangle and Circle
Rectangle rectangle = new Rectangle(5.0, 4.0);
Circle circle = new Circle(3.0);
// Calculate and display the area and perimeter of Rectangle
System.out.println("Rectangle:");
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());
// Calculate and display the area and perimeter of Circle
System.out.println("\nCircle:");
System.out.println("Area: " + circle.calculateArea());
System.out.println("Perimeter: " + circle.calculatePerimeter());
}
}
You are tasked with designing a system for managing diAerent types of animals in a zoo.
Design an abstract class Animal with an abstract method makeSound(). Then, create concrete
subclasses such as Lion and Elephant that extend the Animal class and implement the
makeSound() method to represent the unique sound each animal makes.
// Abstract Animal class
abstract class Animal {
// Abstract method to make sound
public abstract void makeSound();
}
// Lion subclass extending Animal
class Lion extends Animal {
@Override
public void makeSound() {
System.out.println("Lion roars");
}
}
// Elephant subclass extending Animal
class Elephant extends Animal {
@Override
public void makeSound() {
System.out.println("Elephant trumpets");
}
}
public class Main {
public static void main(String[] args) {
// Create instances of Lion and Elephant
Lion lion = new Lion();
Elephant elephant = new Elephant();
// Make sound of Lion and Elephant
System.out.println("Lion:");
lion.makeSound();
System.out.println("\nElephant:");
elephant.makeSound();
}
}
INTERFACE
You are creating a sorting algorithm library. Design an interface SortAlgorithm with a method
sort(int[] array). Then, create classes such as BubbleSort and MergeSort that implement the
SortAlgorithm interface and provide their own implementation of the sort() method to perform
sorting using the respective algorithms.
Provide constructors for each class if necessary, and demonstrate how to use these classes by
creating instances of BubbleSort and MergeSort, and calling their sort() methods with a sample
array.
// SortAlgorithm interface
interface SortAlgorithm {
void sort(int[] array);
}
// BubbleSort class implementing SortAlgorithm interface
class BubbleSort implements SortAlgorithm {
@Override
public void sort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap array[j] and array[j+1]
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
// MergeSort class implementing SortAlgorithm interface
public class MergeSort implements SortAlgorithm {
public void sort(int[] array) {
// Merge sort algorithm
mergeSort(array, 0, array.length - 1);
}
private void mergeSort(int[] array, int left, int
right) {
if (left < right) {
// Find the middle point
int middle = (left + right) / 2;
// Sort first and second halves
mergeSort(array, left, middle);
mergeSort(array, middle + 1, right);
// Merge the sorted halves
merge(array, left, middle, right);
}
}
private void merge(int[] array, int left, int middle,
int right) {
// Sizes of two subarrays to be merged
int n1 = middle - left + 1;
int n2 = right - middle;
// Create temporary arrays
int[] L = new int[n1];
int[] R = new int[n2];
// Copy data to temporary arrays
for (int i = 0; i < n1; i++) {
L[i] = array[left + i];
}
for (int j = 0; j < n2; j++) {
R[j] = array[middle + 1 + j];
}
// Merge the temporary arrays
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
array[k] = L[i];
i++;
} else {
array[k] = R[j];
j++;
}
k++;
}
// Copy remaining elements of L[] if any
while (i < n1) {
array[k] = L[i];
i++;
k++;
}
// Copy remaining elements of R[] if any
while (j < n2) {
array[k] = R[j];
j++;
k++;
}
}
}
public class Main {
public static void main(String[] args) {
// Sample array
int[] array = {5, 2, 9, 1, 6};
// Sort using BubbleSort
SortAlgorithm bubbleSort = new BubbleSort();
bubbleSort.sort(array);
System.out.println("Sorted array using BubbleSort:");
printArray(array);
// Sample array for merge sort
int[] array2 = {5, 2, 9, 1, 6};
// Sort using MergeSort
SortAlgorithm mergeSort = new MergeSort();
mergeSort.sort(array2);
System.out.println("Sorted array using MergeSort:");
printArray(array2);
}
// Utility method to print an array
private static void printArray(int[] array) {
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
}
}
Encapsulation
Design a class Person to represent a person's name and age. Implement the Person class
with the following requirements:
It should have private instance variables name (String) and age (int).
Provide public methods getName() and getAge() to access the name and age variables,
respectively.
Implement a constructor that accepts parameters to initialize the name and age
variables.
Ensure that the age cannot be negative. If an attempt is made to set a negative age, set it
to 0
public class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
if (age < 0) {
this.age = 0; // Set age to 0 if negative
} else {
this.age = age;
}
}
// Public methods to access name and age variables
public String getName() {
return name;
}
public int getAge() {
return age;
}
// Setter method for age with validation
public void setAge(int age) {
if (age < 0) {
this.age = 0; // Set age to 0 if negative
} else {
this.age = age;
}
}
}
public class Main {
public static void main(String[] args) {
// Create a Person object with name "John" and
age 30
Person person1 = new Person("John", 30);
// Get and print the name and age of person1
System.out.println("Name: " + person1.getName());
System.out.println("Age: " + person1.getAge());
// Create another Person object with name "Alice"
and age -25
// Note: age -25 will be treated as 0 due to
validation in the constructor
Person person2 = new Person("Alice", -25);
// Get and print the name and age of person2
System.out.println("Name: " + person2.getName());
System.out.println("Age: " + person2.getAge());
// Update the age of person2 to 35
person2.setAge(35);
// Get and print the updated age of person2
System.out.println("Updated Age: " +
person2.getAge());
}
}
Exception Handaling: try catch throw throws and finally
Division Exception:
Write a Java program that takes two integers as input from the user and calculates their
division. Handle the ArithmeticException that may occur if the second number is zero.
import java.util.Scanner;
public class DivisionException {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the two integers
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Calculate division and handle ArithmeticException if num2 is zero
try {
int result = num1 / num2;
System.out.println("Division result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
scanner.close();
}
}
Array Index Out of Bounds:
Define an array of integers. Attempt to access an element at an index beyond the array's
bounds. Handle the ArrayIndexOutOfBoundsException that may occur.
public class ArrayIndexOutOfBounds {
public static void main(String[] args) {
// Define an array of integers
int[] numbers = {1, 2, 3, 4, 5};
// Attempt to access an element at an index beyond the array's bounds
try {
int index = 10;
int element = numbers[index];
System.out.println("Element at index " + index + ": " + element);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index is out of bounds.");
}
}
}
Access Modifier and Package Practice Question :
Create a Java class named Person with private instance variables for name, age, and
email. Provide public methods to set and get these variables.
Write another class to test the Person class by creating instances and
accessing/modifying the private variables using the public methods.
Package Practice:
package Practice;
public class Person {
private String name;
private int age;
private String email;
// Constructor
public Person(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
// Setter methods
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setEmail(String email) {
this.email = email;
}
}
package Practice;
public class PersonTest {
public static void main(String[] args) {
// Creating a Person object
Person person1 = new Person("Alice", 30, "alice@example.com");
// Accessing private variables using getter methods
System.out.println("Name: " + person1.getName());
System.out.println("Age: " + person1.getAge());
System.out.println("Email: " + person1.getEmail());
// Modifying private variables using setter methods
person1.setName("Bob");
person1.setAge(25);
person1.setEmail("bob@example.com");
// Accessing modified variables
System.out.println("\nModified Details:");
System.out.println("Name: " + person1.getName());
System.out.println("Age: " + person1.getAge());
System.out.println("Email: " + person1.getEmail());
}
}
Create a package named math and define a class called Calculator within it. Implement basic
arithmetic operations (addition, subtraction, multiplication, division).
Create another package named app and write a class called Main in it. Import the Calculator
class from the math package and use its methods to perform arithmetic operations
package math;
public class Calculator {
public int addition(int num1, int num2) {
return num1 + num2;
public int subtraction(int num1, int num2) {
return num1 - num2;
public int multiplication(int num1, int num2) {
return num1 * num2;
public double division(int num1, int num2) {
if (num2 == 0) {
throw new IllegalArgumentException("Cannot divide by zero");
return (double) num1 / num2;
}
package app;
import math.Calculator;
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
// Perform arithmetic operations
int sum = calculator.addition(10, 5);
System.out.println("Sum: " + sum);
int di erence = calculator.subtraction(10, 5);
System.out.println("Di erence: " + di erence);
int product = calculator.multiplication(10, 5);
System.out.println("Product: " + product);
double quotient = calculator.division(10, 5);
System.out.println("Quotient: " + quotient);
}
Static Nested Class (Static Inner Class):
Question:
You are designing a music player application. Create a static nested class Song within the
MusicPlayer class to represent individual songs. The Song class should have instance variables
title and artist. Implement a method play() in the Song class that prints "Now playing [title] by
[artist]".
public class MusicPlayer {
// Static nested class Song
static class Song {
private String title;
private String artist;
// Constructor
public Song(String title, String artist) {
this.title = title;
this.artist = artist;
}
// Method to play the song
public void play() {
System.out.println("Now playing " + title + " by " + artist);
}
}
public static void main(String[] args) {
// Create an instance of Song
Song song = new Song("Shape of You", "Ed Sheeran");
// Play the song
song.play();
}
}
Non-Static Nested Class (Inner Class):
Question:
You are developing a banking application. Create an inner class Transaction within the Account
class to represent individual transactions. The Transaction class should have instance variables
amount and timestamp. Implement a method printTransaction() in the Transaction class that
prints "Transaction of [amount] at [timestamp]".
import java.time.LocalDateTime;
public class Account {
// Inner class Transaction
class Transaction {
private double amount;
private LocalDateTime timestamp;
// Constructor
public Transaction(double amount) {
this.amount = amount;
this.timestamp = LocalDateTime.now();
}
// Method to print the transaction details
public void printTransaction() {
System.out.println("Transaction of " + amount + " at " + timestamp);
}
}
public static void main(String[] args) {
// Create an instance of Account
Account account = new Account();
// Create an instance of Transaction and print its details
Account.Transaction transaction = account.new Transaction(1000.0);
transaction.printTransaction();
}
}
Local Inner Class:
Question:
You are working on a game application. Create a method startGame() in the Game class. Inside
this method, define a local inner class Player representing a game player. The Player class should
have instance variables name and score. Implement a method displayScore() in the Player class
that prints "Player [name] scored [score]".
public class Game {
// Method to start the game
public void startGame() {
// Local inner class Player
class Player {
private String name;
private int score;
// Constructor
public Player(String name, int score) {
this.name = name;
this.score = score;
}
// Method to display player's score
public void displayScore() {
System.out.println("Player " + name + " scored " + score);
}
}
// Create an instance of Player and display score
Player player = new Player("John", 100);
player.displayScore();
}
public static void main(String[] args) {
// Create an instance of Game and start the game
Game game = new Game();
game.startGame();
}
}
Anonymous Inner Class:
Question: Write a Java program that creates a simple interface Animal with a method
sound(). Implement this interface using an anonymous inner class and print "Woof"
inside the sound() method.
public class Main {
interface Animal {
void sound();
}
public static void main(String[] args) {
// Implement the Animal interface using an anonymous inner class
Animal dog = new Animal() {
@Override
public void sound() {
System.out.println("Woof");
}
};
// Call the sound() method of the anonymous inner class
dog.sound();
}
}
Reading and Writing to Files:
Question:
You are creating a program to manage employee information. Write a method writeToFile(String
data) in the EmployeeManager class that writes the provided data to a text file named
employees.txt. Use FileWriter and Bu eredWriter for writing the data to the file.
import java.io.Bu eredWriter;
import java.io.FileWriter;
import java.io.IOException;
public class EmployeeManager {
public void writeToFile(String data) {
// Define the file name
String fileName = "employees.txt";
// Use try-with-resources to automatically close the FileWriter and Bu eredWriter
try (FileWriter fileWriter = new FileWriter(fileName);
Bu eredWriter bu eredWriter = new Bu eredWriter(fileWriter)) {
// Write the data to the file
bu eredWriter.write(data);
System.out.println("Data has been written to the file: " + fileName);
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
// Other methods for managing employee information can be added here