1.
Class Cat with default constructor
class Cat {
String name;
int age;
Cat() {
name = "Unknown";
age = 0;
public static void main(String[] args) {
Cat cat = new Cat();
System.out.println("Name: " + cat.name + ", Age: " + cat.age);
Output:
Name: Unknown, Age: 0
2. Class Dog with parameterized constructor
class Dog {
String name, colour;
Dog(String name, String colour) {
this.name = name;
this.colour = colour;
public static void main(String[] args) {
Dog dog = new Dog("Buddy", "Brown");
System.out.println("Name: " + dog.name + ", Colour: " + dog.colour);
}
}
Output:
Name: Buddy, Colour: Brown
3. Class Book with multiple constructors
class Book {
String title, author;
double price;
Book() {}
Book(String title, String author) {
this.title = title;
this.author = author;
Book(String title, String author, double price) {
this(title, author);
this.price = price;
public static void main(String[] args) {
Book b1 = new Book("Book1", "Author1");
Book b2 = new Book("Book2", "Author2", 299.99);
System.out.println(b1.title + ", " + b1.author);
System.out.println(b2.title + ", " + b2.author + ", " + b2.price);
Output:
Book1, Author1
Book2, Author2, 299.99
4. Class Student with constructors
class Student {
int studentId;
String studentName;
char grade;
Student() {}
Student(int studentId, String studentName, char grade) {
this.studentId = studentId;
this.studentName = studentName;
this.grade = grade;
public static void main(String[] args) {
Student s = new Student(101, "John", 'A');
System.out.println(s.studentId + ", " + s.studentName + ", " + s.grade);
Output:
101, John, A
5. Class Book with add/remove methods
import java.util.ArrayList;
class Book {
String title, author, ISBN;
static ArrayList<Book> collection = new ArrayList<>();
Book(String title, String author, String ISBN) {
this.title = title;
this.author = author;
this.ISBN = ISBN;
}
static void addBook(Book book) {
collection.add(book);
static void removeBook(Book book) {
collection.remove(book);
public static void main(String[] args) {
Book b1 = new Book("Book1", "Author1", "123");
addBook(b1);
System.out.println("Collection: " + collection.size());
removeBook(b1);
System.out.println("Collection: " + collection.size());
Output:
Collection: 1
Collection: 0
6. Class Account with validation
class Account {
String accountNumber;
double balance;
Account(String accountNumber, double balance) {
if (accountNumber == null || accountNumber.isEmpty() || balance < 0) {
System.out.println("Error in account initialization.");
} else {
this.accountNumber = accountNumber;
this.balance = balance;
public static void main(String[] args) {
Account acc = new Account("", -100);
Account validAcc = new Account("12345", 1000);
System.out.println("Account: " + validAcc.accountNumber + ", Balance: " + validAcc.balance);
Output:
Error in account initialization.
Account: 12345, Balance: 1000.0
7. Class Car with default values
java
Copy code
class Car {
String make, model;
int year;
Car(String make, String model, int year) {
this.make = make != null ? make : "Unknown";
this.model = model != null ? model : "Unknown";
this.year = year > 0 ? year : 2000;
public static void main(String[] args) {
Car car = new Car(null, null, -1);
System.out.println(car.make + ", " + car.model + ", " + car.year);
}
}
Output:
sql
Copy code
Unknown, Unknown, 2000
8. Class Point with overloaded constructors
java
Copy code
class Point {
double x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
Point(double x, double y) {
this.x = x;
this.y = y;
public static void main(String[] args) {
Point p1 = new Point(1, 2);
Point p2 = new Point(1.5, 2.5);
System.out.println("Point1: " + p1.x + ", " + p1.y);
System.out.println("Point2: " + p2.x + ", " + p2.y);
Output:
makefile
Copy code
Point1: 1.0, 2.0
Point2: 1.5, 2.5
9. Class Constants with PI
java
Copy code
class Constants {
static final double PI = 3.14159;
static double areaOfCircle(double radius) {
return PI * radius * radius;
public static void main(String[] args) {
System.out.printf("Area: %.2f\n", areaOfCircle(5));
Output:
makefile
Copy code
Area: 78.54
10. Class Animal with overridden method
java
Copy code
class Animal {
void makeSound() {
System.out.println("Some sound");
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
public static void main(String[] args) {
Animal animal = new Cat();
animal.makeSound();
Output:
Copy code
Meow
11. Class Vehicle with overridden method in Car
java
Copy code
class Vehicle {
void drive() {
System.out.println("Driving a vehicle");
class Car extends Vehicle {
@Override
void drive() {
System.out.println("Repairing a car");
public static void main(String[] args) {
Vehicle v = new Car();
v.drive();
Output:
css
Copy code
Repairing a car
12. Class Shape with overridden method in Rectangle
java
Copy code
class Shape {
double getArea() {
return 0;
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
@Override
double getArea() {
return length * width;
}
public static void main(String[] args) {
Rectangle rect = new Rectangle(5, 3);
System.out.println("Area: " + rect.getArea());
Output:
makefile
Copy code
Area: 15.0
13. Class Employee with overridden and new methods in HRManager
java
Copy code
class Employee {
void work() {
System.out.println("Working...");
double getSalary() {
return 50000;
class HRManager extends Employee {
@Override
void work() {
System.out.println("Managing HR tasks");
void addEmployee() {
System.out.println("Employee added");
}
public static void main(String[] args) {
HRManager hr = new HRManager();
hr.work();
hr.addEmployee();
Output:
Copy code
Managing HR tasks
Employee added
14. Class BankAccount with overridden method in SavingsAccount
java
Copy code
class BankAccount {
double balance;
void deposit(double amount) {
balance += amount;
void withdraw(double amount) {
balance -= amount;
class SavingsAccount extends BankAccount {
@Override
void withdraw(double amount) {
if (balance - amount < 100) {
System.out.println("Withdrawal denied: Balance too low");
} else {
super.withdraw(amount);
System.out.println("Withdrawal successful");
public static void main(String[] args) {
SavingsAccount acc = new SavingsAccount();
acc.deposit(200);
acc.withdraw(150);
acc.withdraw(50);
Output:
yaml
Copy code
Withdrawal successful
Withdrawal denied: Balance too low
15. Class Animal with overridden method in Cheetah
java
Copy code
class Animal {
void move() {
System.out.println("Animal is moving");
class Cheetah extends Animal {
@Override
void move() {
System.out.println("Cheetah is running fast");
public static void main(String[] args) {
Animal a = new Cheetah();
a.move();
Output:
arduino
Copy code
Cheetah is running fast
16. Class Person with overridden and new methods in Employee
java
Copy code
class Person {
String getFirstName() {
return "John";
String getLastName() {
return "Doe";
class Employee extends Person {
int getEmployeeId() {
return 123;
}
@Override
String getLastName() {
return "Doe (Manager)";
public static void main(String[] args) {
Employee emp = new Employee();
System.out.println(emp.getFirstName() + " " + emp.getLastName() + ", ID: " +
emp.getEmployeeId());
Output:
java
Copy code
John Doe (Manager), ID: 123
17. Class Shape with overridden methods in Circle
java
Copy code
class Shape {
double getPerimeter() {
return 0;
double getArea() {
return 0;
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
@Override
double getPerimeter() {
return 2 * Math.PI * radius;
@Override
double getArea() {
return Math.PI * radius * radius;
public static void main(String[] args) {
Circle c = new Circle(5);
System.out.printf("Perimeter: %.2f, Area: %.2f\n", c.getPerimeter(), c.getArea());
Output:
mathematica
Copy code
Perimeter: 31.42, Area: 78.54
18. Vehicle class hierarchy
java
Copy code
class Vehicle {
String make, model;
int year;
double fuelEfficiency() {
return 0;
class Car extends Vehicle {
@Override
double fuelEfficiency() {
return 15; // km/l
class Truck extends Vehicle {
@Override
double fuelEfficiency() {
return 8;
public static void main(String[] args) {
Car car = new Car();
Truck truck = new Truck();
System.out.println("Car fuel efficiency: " + car.fuelEfficiency());
System.out.println("Truck fuel efficiency: " + truck.fuelEfficiency());
Output:
yaml
Copy code
Car fuel efficiency: 15.0
Truck fuel efficiency: 8.0
19. Employee class hierarchy
java
Copy code
class Employee {
String name, jobTitle;
double salary;
double calculateBonus() {
return salary * 0.1;
class Manager extends Employee {
@Override
double calculateBonus() {
return salary * 0.2;
public static void main(String[] args) {
Manager m = new Manager();
m.salary = 100000;
System.out.println("Manager bonus: " + m.calculateBonus());
Output:
yaml
Copy code
Manager bonus: 20000.0
20. Abstract class Animal with subclasses
abstract class Animal {
abstract void sound();
class Lion extends Animal {
@Override
void sound() {
System.out.println("Roar");
class Tiger extends Animal {
@Override
void sound() {
System.out.println("Growl");
public static void main(String[] args) {
Animal lion = new Lion();
Animal tiger = new Tiger();
lion.sound();
tiger.sound();
Output:
Roar
Growl
4o
21. Abstract class Shape with subclasses Circle and Triangle
java
Copy code
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
@Override
double calculateArea() {
return Math.PI * radius * radius;
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
class Triangle extends Shape {
double base, height, sideA, sideB, sideC;
Triangle(double base, double height, double sideA, double sideB, double sideC) {
this.base = base;
this.height = height;
this.sideA = sideA;
this.sideB = sideB;
this.sideC = sideC;
@Override
double calculateArea() {
return 0.5 * base * height;
@Override
double calculatePerimeter() {
return sideA + sideB + sideC;
public class Main {
public static void main(String[] args) {
Circle c = new Circle(5);
System.out.printf("Circle Area: %.2f, Perimeter: %.2f\n", c.calculateArea(),
c.calculatePerimeter());
Triangle t = new Triangle(3, 4, 3, 4, 5);
System.out.printf("Triangle Area: %.2f, Perimeter: %.2f\n", t.calculateArea(),
t.calculatePerimeter());
Output:
mathematica
Copy code
Circle Area: 78.54, Perimeter: 31.42
Triangle Area: 6.00, Perimeter: 12.00
22. Abstract class Animal with subclasses
java
Copy code
abstract class Animal {
abstract void eat();
abstract void sleep();
class Lion extends Animal {
@Override
void eat() {
System.out.println("Lion eats meat");
@Override
void sleep() {
System.out.println("Lion sleeps in the den");
class Tiger extends Animal {
@Override
void eat() {
System.out.println("Tiger hunts prey");
@Override
void sleep() {
System.out.println("Tiger sleeps in the forest");
}
class Deer extends Animal {
@Override
void eat() {
System.out.println("Deer eats grass");
@Override
void sleep() {
System.out.println("Deer sleeps under trees");
public static void main(String[] args) {
Animal lion = new Lion();
Animal tiger = new Tiger();
Animal deer = new Deer();
lion.eat();
lion.sleep();
tiger.eat();
tiger.sleep();
deer.eat();
deer.sleep();
Output:
Copy code
Lion eats meat
Lion sleeps in the den
Tiger hunts prey
Tiger sleeps in the forest
Deer eats grass
Deer sleeps under trees
23. Abstract class Vehicle with subclasses
java
Copy code
abstract class Vehicle {
abstract void startEngine();
abstract void stopEngine();
class Car extends Vehicle {
@Override
void startEngine() {
System.out.println("Car engine started");
@Override
void stopEngine() {
System.out.println("Car engine stopped");
class Motorcycle extends Vehicle {
@Override
void startEngine() {
System.out.println("Motorcycle engine started");
@Override
void stopEngine() {
System.out.println("Motorcycle engine stopped");
public static void main(String[] args) {
Vehicle car = new Car();
Vehicle bike = new Motorcycle();
car.startEngine();
car.stopEngine();
bike.startEngine();
bike.stopEngine();
Output:
Copy code
Car engine started
Car engine stopped
Motorcycle engine started
Motorcycle engine stopped
24. Interface Shape with implementing classes
java
Copy code
interface Shape {
double getArea();
class Rectangle implements Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
@Override
public double getArea() {
return length * width;
class Circle implements Shape {
double radius;
Circle(double radius) {
this.radius = radius;
@Override
public double getArea() {
return Math.PI * radius * radius;
class Triangle implements Shape {
double base, height;
Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
public static void main(String[] args) {
Shape rect = new Rectangle(4, 5);
Shape circle = new Circle(3);
Shape triangle = new Triangle(4, 3);
System.out.printf("Rectangle Area: %.2f\n", rect.getArea());
System.out.printf("Circle Area: %.2f\n", circle.getArea());
System.out.printf("Triangle Area: %.2f\n", triangle.getArea());
Output:
mathematica
Copy code
Rectangle Area: 20.00
Circle Area: 28.27
Triangle Area: 6.00
25. Interface Animal with class Dog
java
Copy code
interface Animal {
void bark();
class Dog implements Animal {
@Override
public void bark() {
System.out.println("Dog is barking");
public static void main(String[] args) {
Dog dog = new Dog();
dog.bark();
Output:
csharp
Copy code
Dog is barking
26. Exception Handling
java
Copy code
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
Output:
csharp
Copy code
Exception caught: / by zero
27. File Reading with Exception Handling
java
Copy code
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
try {
File file = new File("test.txt");
if (file.length() == 0) {
throw new Exception("File is empty");
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
Output:
php
Copy code
Exception: File is empty
28. Basic Java Thread
java
Copy code
class HelloThread extends Thread {
public void run() {
System.out.println("Hello, IT B!");
}
public static void main(String[] args) {
HelloThread thread = new HelloThread();
thread.start();
Output:
css
Copy code
Hello, IT B!
29. Even and Odd Numbers using Threads
java
Copy code
class EvenThread extends Thread {
public void run() {
for (int i = 2; i <= 20; i += 2) {
System.out.println("Even: " + i);
class OddThread extends Thread {
public void run() {
for (int i = 1; i <= 19; i += 2) {
System.out.println("Odd: " + i);
public static void main(String[] args) {
new EvenThread().start();
new OddThread().start();
}
Output:
makefile
Copy code
Even: 2
Odd: 1
...
30. Multiplication using Threads
java
Copy code
class MultiplyThread extends Thread {
private int num;
MultiplyThread(int num) {
this.num = num;
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.printf("%d x %d = %d\n", num, i, num * i);
public static void main(String[] args) {
new MultiplyThread(5).start();
Output:
python
Copy code
5x1=5
5 x 2 = 10
...
31. Multiple Threads Incrementing a Shared Counter
java
Copy code
class Counter {
private int count = 0;
synchronized void increment() {
count++;
synchronized int getCount() {
return count;
class IncrementThread extends Thread {
private Counter counter;
IncrementThread(Counter counter) {
this.counter = counter;
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new IncrementThread(counter);
Thread t2 = new IncrementThread(counter);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Final Counter Value: " + counter.getCount());
Output:
yaml
Copy code
Final Counter Value: 2000
32. Read File Content Line by Line
java
Copy code
import java.io.*;
public class FileReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
Output (Assuming test.txt contains Hello World and Java Programming):
Copy code
Hello World
Java Programming
33. Read File Line by Line into a Variable
java
Copy code
import java.io.*;
public class FileToVariable {
public static void main(String[] args) {
StringBuilder fileContent = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line;
while ((line = br.readLine()) != null) {
fileContent.append(line).append("\n");
} catch (IOException e) {
e.printStackTrace();
System.out.println(fileContent.toString());
}
}
Output:
Copy code
Hello World
Java Programming
34. Write and Read Plain Text File
java
Copy code
import java.io.*;
public class FileWriteRead {
public static void main(String[] args) {
String data = "Hello, Java!";
try (FileWriter writer = new FileWriter("example.txt")) {
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
System.out.println("File Content: " + br.readLine());
} catch (IOException e) {
e.printStackTrace();
Output:
arduino
Copy code
File Content: Hello, Java!
35. JavaFX "Hello, IT B!"
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class HelloITB extends Application {
@Override
public void start(Stage stage) {
Label label = new Label("Hello, IT B!");
Scene scene = new Scene(label, 200, 100);
stage.setTitle("Greeting");
stage.setScene(scene);
stage.show();
public static void main(String[] args) {
launch(args);
Output: Displays a window with "Hello, IT B!" message.
36. JavaFX Input and Button
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class InputDisplayApp extends Application {
@Override
public void start(Stage stage) {
TextField textField = new TextField();
Button button = new Button("Display");
Label label = new Label();
button.setOnAction(e -> label.setText(textField.getText()));
VBox vbox = new VBox(10, textField, button, label);
Scene scene = new Scene(vbox, 300, 200);
stage.setTitle("Text Display");
stage.setScene(scene);
stage.show();
public static void main(String[] args) {
launch(args);
Output: Displays a window where text input updates a label upon button click.
37. JavaFX Basic Calculator
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CalculatorApp extends Application {
@Override
public void start(Stage stage) {
TextField num1 = new TextField();
TextField num2 = new TextField();
Button addButton = new Button("Add");
Label result = new Label();
addButton.setOnAction(e -> {
double number1 = Double.parseDouble(num1.getText());
double number2 = Double.parseDouble(num2.getText());
result.setText("Sum: " + (number1 + number2));
});
VBox vbox = new VBox(10, num1, num2, addButton, result);
Scene scene = new Scene(vbox, 300, 200);
stage.setTitle("Basic Calculator");
stage.setScene(scene);
stage.show();
public static void main(String[] args) {
launch(args);
Output: Performs addition and displays the result.
38. Electricity Bill Generator
java
Copy code
class ElectricityBill {
String consumerName, connectionType;
int previousReading, currentReading;
ElectricityBill(String name, String type, int prev, int curr) {
consumerName = name;
connectionType = type;
previousReading = prev;
currentReading = curr;
double calculateBill() {
int units = currentReading - previousReading;
double bill = 0;
if ("domestic".equalsIgnoreCase(connectionType)) {
bill = units <= 100 ? units :
units <= 200 ? 100 + (units - 100) * 2.5 :
units <= 500 ? 350 + (units - 200) * 4 :
1550 + (units - 500) * 6;
} else if ("commercial".equalsIgnoreCase(connectionType)) {
bill = units <= 100 ? units * 2 :
units <= 200 ? 200 + (units - 100) * 4.5 :
units <= 500 ? 650 + (units - 200) * 6 :
2450 + (units - 500) * 7;
return bill;
public static void main(String[] args) {
ElectricityBill bill = new ElectricityBill("John", "domestic", 120, 620);
System.out.printf("Bill Amount: Rs. %.2f\n", bill.calculateBill());
Output:
yaml
Copy code
Bill Amount: Rs. 2450.00
Let me know if you'd like more detailed explanations or solutions!
4o
You said:
from 39 to 43
ChatGPT said:
ChatGPT
Here are concise Java programs with their outputs for the requested questions:
39. Employee Class with Subclasses and Pay Slip Generation
java
Copy code
class Employee {
String empName, empId, address, mailId;
long mobileNo;
Employee(String name, String id, String addr, String mail, long mobile) {
empName = name;
empId = id;
address = addr;
mailId = mail;
mobileNo = mobile;
}
class Programmer extends Employee {
double basicPay;
Programmer(String name, String id, String addr, String mail, long mobile, double pay) {
super(name, id, addr, mail, mobile);
basicPay = pay;
void generatePaySlip() {
double da = 0.97 * basicPay;
double hra = 0.10 * basicPay;
double pf = 0.12 * basicPay;
double staffClub = 0.001 * basicPay;
double grossSalary = basicPay + da + hra;
double netSalary = grossSalary - pf - staffClub;
System.out.printf("Gross Salary: %.2f, Net Salary: %.2f\n", grossSalary, netSalary);
public static void main(String[] args) {
Programmer p = new Programmer("Alice", "P123", "Chennai", "alice@mail.com", 9876543210L,
50000);
p.generatePaySlip();
Output:
yaml
Copy code
Gross Salary: 107000.00, Net Salary: 101940.00
40. Implementing Java Packages
File: mypackage/MyClass.java
java
Copy code
package mypackage;
public class MyClass {
public void displayMessage() {
System.out.println("Hello from MyClass in mypackage!");
File: Main.java
java
Copy code
import mypackage.MyClass;
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.displayMessage();
Output:
vbnet
Copy code
Hello from MyClass in mypackage!
41. Abstract Class Shape with Subclasses
java
Copy code
abstract class Shape {
int a, b;
Shape(int a, int b) {
this.a = a;
this.b = b;
abstract void printArea();
class Rectangle extends Shape {
Rectangle(int length, int breadth) {
super(length, breadth);
void printArea() {
System.out.println("Rectangle Area: " + (a * b));
class Circle extends Shape {
Circle(int radius, int unused) {
super(radius, unused);
void printArea() {
System.out.println("Circle Area: " + (3.14 * a * a));
class Triangle extends Shape {
Triangle(int base, int height) {
super(base, height);
void printArea() {
System.out.println("Triangle Area: " + (0.5 * a * b));
public class ShapeTest {
public static void main(String[] args) {
Shape rectangle = new Rectangle(10, 20);
Shape circle = new Circle(7, 0);
Shape triangle = new Triangle(5, 10);
rectangle.printArea();
circle.printArea();
triangle.printArea();
Output:
mathematica
Copy code
Rectangle Area: 200
Circle Area: 153.86
Triangle Area: 25.0
42. Multi-Threaded Application with Random Integers
java
Copy code
import java.util.Random;
class RandomThread extends Thread {
public void run() {
Random random = new Random();
while (true) {
int num = random.nextInt(100);
System.out.println("Generated: " + num);
if (num % 2 == 0) {
new SquareThread(num).start();
} else {
new CubeThread(num).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
class SquareThread extends Thread {
int num;
SquareThread(int num) {
this.num = num;
public void run() {
System.out.println("Square of " + num + ": " + (num * num));
}
class CubeThread extends Thread {
int num;
CubeThread(int num) {
this.num = num;
public void run() {
System.out.println("Cube of " + num + ": " + (num * num * num));
public class MultiThreadExample {
public static void main(String[] args) {
new RandomThread().start();
Output (Example Output as Numbers Are Random):
yaml
Copy code
Generated: 25
Cube of 25: 15625
Generated: 10
Square of 10: 100
43. Write and Read File Handling
java
Copy code
import java.io.*;
public class FileWriteRead {
public static void main(String[] args) {
String fileName = "data.txt";
String content = "Hello, File Handling in Java!";
// Writing to the file
try (FileWriter writer = new FileWriter(fileName)) {
writer.write(content);
System.out.println("Data written to file successfully.");
} catch (IOException e) {
e.printStackTrace();
// Reading from the file
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Read from file: " + line);
} catch (IOException e) {
e.printStackTrace();
Output:
css
Copy code
Data written to file successfully.
Read from file: Hello, File Handling in Java!