TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical List
Semester: 4th
Subject Name: Object Oriented Programming with java (4341602)
Name of faculty: Prof. Bina B. Sathavara
1. Install JDK and Setup a Java Programming development environment by using: 1)
Command Prompt (SET PATH command and using Environment Variable). 2) Any open
source IDE (Eclipse, Jcreater etc).
2. Test the java development environment setup by implementing a simple java program
(print: “OOP with JAVA”).
3. Develop a basic java program that demonstrates data types of JAVA.
4. Develop a Java program to swap two numbers without using a temporary variable and
with using a temporary variable (use command line argument to accept value from user).
5. Develop programs to demonstrate use of - 1) if statement and its different form 2) switch
case statement
6. Develop program to demonstrate use of1) for loop 2) ‘while’ and ‘do while’ loop
7. Develop a Java program to find maximum and minimum numbers from array elements.
8. Develop a basic java program that demonstrates the use of Class & Object.
9. Develop a java program to find the factorial of a given number using a recursive function.
10. Develop a java program that demonstrates method overloading.
11. Develop a program for implementation of different functions of String class.
12. Develop a program for implementation of Wrapper Class to convert primitive value into
object (Boxing) and object into primitive value (Un-boxing).
13. Develop a program with a static block and show that it will be executed before the main (
) method in a class.
14. Develop a program to demonstrate use of static functions
15. Develop a program to demonstrate use of ‘this’ keyword. Check whether ‘this’ can access
the private members of the class or not.
16. Develop a program with an overloaded constructor. Also develop the copy constructor to
create a new object with the state of the existing object.
17. Develop a program to demonstrate the use of private constructor and also write a method
which will count the number of instances created using default constructor only.
18. Develop a program to demonstrate single inheritance, multilevel inheritance, and
hierarchical inheritance.
19. Develop a program with one class named shape which has two member functions named
erase () and draw (). In the program we have three other subclasses: circle, triangle and
square. override methods of the superclass into subclasses.
20. Develop a program for implementation of Dynamic method dispatch
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 1
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
21. Develop a java program that demonstrates the use of Abstract class
22. Develop a java program that illustrates interface inheritance. Interface ‘A1’ and ‘A2’ are
extended from interface ‘A’. Interface ‘A12’ inherited from both ‘A1’ and ‘A2’. Each
interface declares one method and one constant. Class ‘Interface_Imple’ implements
‘A12’. Instantiate ‘Interface_Imple’ and invoke each of its methods. Each method
displays one of the constants.
23. Develop a program to create a Package and demonstrate how packages are used in java.
And use java access modifier to demonstrate the access rules in a package.
24. Develop a program to demonstrate the use of ‘super’ and ‘final’ keywords.
25. Develop programs to demonstrate the use of Exception Handling using predefined
Exception Classes.
26. Develop a program to handle multiple exceptions using multiple try blocks and multiple
catch blocks.
27. Develop a program to implement user defined exceptions.
28. Develop a program to demonstrate use of throw, throws, and finally keyword
29. Develop a program that executes two threads. One thread displays “Java Programming”
every 2 seconds, and the other displays “Semester - 4th” every 5 seconds.(Create the
threads by extending the Thread class)
30. Develop a program that executes two threads. One thread will print the even numbers and
the another thread will print odd numbers between 1 to 10.(Create the thread by
implementing runnable interface)
31. Develop a program to demonstrate use of synchronization of threads when multiple
threads are trying to update a common variable
32. Develop programs to create, write, modify, read operations on Text files.
HOD Prepared By:
I.T. DEPARTMENT Prof. Bina B. Sathavara
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 2
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-1
Aim : Install JDK and Setup a Java Programming development environment by using: 1)
Command Prompt (SET PATH command and using Environment Variable). 2) Any open source
IDE (Eclipse, Jcreater etc).
Step 1: Install JDK
1. Download JDK:
o Visit the official Oracle JDK or OpenJDK website:
Oracle JDK
OpenJDK
o Download the appropriate version based on your system (Windows, macOS,
Linux).
2. Install JDK:
o Run the downloaded installer and follow the setup instructions.
o Note the installation directory (e.g., C:\Program Files\Java\jdk-XX.X.X).
Step 2: Setup Java Environment using Command Prompt
Option 1: Using SET PATH Command (Temporary)
1. Open Command Prompt (cmd).
2. Find your JDK installation path (e.g., C:\Program Files\Java\jdk-XX.X.X\bin).
3. Run the following command:
pgsql
CopyEdit
set PATH=C:\Program Files\Java\jdk-XX.X.X\bin;%PATH%
4. Verify installation by typing:
nginx
CopyEdit
java -version
nginx
CopyEdit
javac -version
If Java is installed correctly, it will display the Java version.
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 3
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Option 2: Using Environment Variables (Permanent)
1. Open Environment Variables:
o Right-click This PC → Click Properties.
o Go to Advanced system settings → Click Environment Variables.
2. Set JAVA_HOME:
o Click New under System Variables.
o Variable name: JAVA_HOME
o Variable value: C:\Program Files\Java\jdk-XX.X.X
3. Update PATH Variable:
o Find Path under System Variables, select it, and click Edit.
o Click New and add: C:\Program Files\Java\jdk-XX.X.X\bin
4. Verify Installation:
o Open Command Prompt and run:
pgsql
CopyEdit
java -version
javac -version
Step 3: Install and Setup an IDE
Using an Integrated Development Environment (IDE) makes Java development easier.
Option 1: Eclipse IDE
1. Download from: https://www.eclipse.org/downloads/
2. Install and open Eclipse.
3. Select a workspace folder.
4. Create a new Java project:
o Go to File → New → Java Project.
o Enter a project name and click Finish.
o Create a new class and write Java code.
Option 2: JCreator IDE
1. Download from: http://www.jcreator.com/download.htm
2. Install and open JCreator.
3. Go to Configure → JDK Profiles and set the path to the installed JDK.
4. Create a new project and start coding.
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 4
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-2
Aim: Test the java development environment setup by implementing a simple java
program (print: “OOP with JAVA”).
Step 1: Create a Simple Java Program
Using Command Prompt (CMD)
1. Open Notepad (or any text editor) and write the following Java program:
java
CopyEdit
public class TestJava {
public static void main(String[] args) {
System.out.println("OOP with JAVA");
}
}
2. Save the file as TestJava.java in a known directory, e.g., C:\JavaProjects.
3. Open Command Prompt (CMD) and navigate to the directory where you saved the file:
bash
CopyEdit
cd C:\JavaProjects
4. Compile the Java program using:
nginx
CopyEdit
javac TestJava.java
5. Run the compiled Java program:
nginx
CopyEdit
java TestJava
6. Expected output:
csharp
CopyEdit
OOP with JAVA
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 5
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Using Eclipse IDE
1. Open Eclipse and create a new Java Project.
2. Inside the project, create a new Java Class named TestJava.
3. Copy and paste the Java code above.
4. Click Run (or press Ctrl + F11).
5. The output will be displayed in the console:
csharp
CopyEdit
OOP with JAVA
Using JCreator IDE
1. Open JCreator and create a new Java Project.
2. Create a new Java file named TestJava.java and paste the code.
3. Click Compile and then Run.
4. The output will be displayed as:
csharp
CopyEdit
OOP with JAVA
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 6
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-3
Aim: Develop a basic java program that demonstrates data types of JAVA.
public class DataTypesDemo {
public static void main(String[] args) {
// Integer data type
int age = 25;
// Floating-point data type
double height = 5.9;
// Character data type
char grade = 'A';
// Boolean data type
boolean isJavaFun = true;
// String (not a primitive data type)
String message = "Learning Java Data Types";
// Byte, Short, and Long
byte smallNumber = 10;
short shortNumber = 3000;
long largeNumber = 1000000000L;
// Float (use 'f' at the end)
float piValue = 3.1415f;
// Display values of different data types
System.out.println("Integer (int) Age: " + age);
System.out.println("Floating-point (double) Height: " + height);
System.out.println("Character (char) Grade: " + grade);
System.out.println("Boolean is Java Fun?: " + isJavaFun);
System.out.println("String Message: " + message);
System.out.println("Byte Value: " + smallNumber);
System.out.println("Short Value: " + shortNumber);
System.out.println("Long Value: " + largeNumber);
System.out.println("Float Value: " + piValue);
}
}
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 7
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Output:
Integer (int) Age: 25
Floating-point (double) Height: 5.9
Character (char) Grade: A
Boolean is Java Fun?: true
String Message: Learning Java Data Types
Byte Value: 10
Short Value: 3000
Long Value: 1000000000
Float Value: 3.1415
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 8
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-4
Aim: Develop a Java program to swap two numbers without using a temporary
variable and with using a temporary variable (use command line argument to
accept value from user).
public class SwapNumbers {
public static void main(String[] args) {
// Check if two arguments are provided
if (args.length < 2) {
System.out.println("Please provide two numbers as command-line arguments.");
return;
}
// Parse command-line arguments
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.println("Before Swapping:");
System.out.println("Number 1: " + num1);
System.out.println("Number 2: " + num2);
// Swap using a temporary variable
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("\nAfter Swapping (Using Temporary Variable):");
System.out.println("Number 1: " + num1);
System.out.println("Number 2: " + num2);
// Swap again without using a temporary variable
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("\nAfter Swapping Back (Without Using Temporary Variable):");
System.out.println("Number 1: " + num1);
System.out.println("Number 2: " + num2);
}
}
}
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 9
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Output:
Before Swapping:
Number 1: 10
Number 2: 20
After Swapping (Using Temporary Variable):
Number 1: 20
Number 2: 10
After Swapping Back (Without Using Temporary Variable):
Number 1: 10
Number 2: 20
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 10
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-5
Aim: Develop programs to demonstrate use of - 1) if statement and its different
form 2) switch case statement
import java.util.Scanner;
public class IfStatementDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input from user
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Simple if statement
if (number > 0) {
System.out.println("The number is positive.");
}
// if-else statement
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
// if-else-if ladder
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
scanner.close();
}
}
Output:
Enter a number: 5
The number is positive.
The number is odd.
The number is positive.
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 11
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-6
Aim: Develop program to demonstrate use of1) for loop 2) ‘while’ and ‘do while’
loop
For loop:
public class ForLoopDemo {
public static void main(String[] args) {
System.out.println("Numbers from 1 to 10 using for loop:");
// For loop to print numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
}
}
Output:
Numbers from 1 to 10 using for loop:
1 2 3 4 5 6 7 8 9 10
While loop:
public class WhileLoopDemo {
public static void main(String[] args) {
int i = 2; // Start from 2
System.out.println("Even numbers from 1 to 10 using while loop:");
// While loop to print even numbers
while (i <= 10) {
System.out.print(i + " ");
i += 2; // Increment by 2 to get the next even number
}
}
}
Output:
Even numbers from 1 to 10 using while loop:
2 4 6 8 10
Do..while :
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 12
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
import java.util.Scanner;
public class DoWhileLoopDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Do-while loop runs at least once
do {
System.out.print("Enter a number (enter 5 to stop): ");
num = scanner.nextInt();
} while (num != 5);
System.out.println("You entered 5, program terminated.");
scanner.close();
}
}
Output:
Enter a number (enter 5 to stop): 3
Enter a number (enter 5 to stop): 8
Enter a number (enter 5 to stop): 5
You entered 5, program terminated.
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 13
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-7
Aim: Develop a Java program to find maximum and minimum numbers from array
elements.
import java.util.Scanner;
public class MinMaxArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Array size
System.out.print("Enter the number of elements: ");
int size = scanner.nextInt();
int[] numbers = new int[size];
// Input: Array elements
System.out.println("Enter " + size + " numbers:");
for (int i = 0; i < size; i++) {
numbers[i] = scanner.nextInt();
}
// Initialize min and max with first element
int min = numbers[0];
int max = numbers[0];
// Loop through the array to fin
Output:
Enter the number of elements: 5
Enter 5 numbers:
38162
Minimum number: 1
Maximum number: 8
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 14
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-8
Aim: Develop a basic java program that demonstrates the use of Class & Object.
// Defining a class
class Car {
// Attributes (variables)
String brand;
int speed;
// Method to display car details
void displayCar() {
System.out.println("Car Brand: " + brand);
System.out.println("Car Speed: " + speed + " km/h");
}
}
public class CarDemo {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car();
// Assigning values to object properties
myCar.brand = "Toyota";
myCar.speed = 120;
// Calling method to display car details
myCar.displayCar();
}
}
Output:
Car Brand: Toyota
Car Speed: 120 km/h
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 15
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-9
Aim: Develop a java program to find the factorial of a given number using a
recursive function.
import java.util.Scanner;
public class FactorialRecursion {
// Recursive function to calculate factorial
static long factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive case
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking input from the user
System.out.print("Enter a number: ");
int num = scanner.nextInt();
// Calculating and displaying factorial
System.out.println("Factorial of " + num + " is: " + factorial(num));
scanner.close();
}
}
Output:
Enter a number: 5
Factorial of 5 is: 120
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 16
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-10
Aim: Develop a java program that demonstrates method overloading.
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double numbers
double add(double a, double b) {
return a + b;
}
}
public class MethodOverloadingDemo {
public static void main(String[] args) {
MathOperations obj = new MathOperations();
// Calling overloaded methods
System.out.println("Sum of 5 and 10: " + obj.add(5, 10));
System.out.println("Sum of 2, 3, and 4: " + obj.add(2, 3, 4));
System.out.println("Sum of 4.5 and 3.2: " + obj.add(4.5, 3.2));
}
}
Output:
Sum of 5 and 10: 15
Sum of 2, 3, and 4: 9
Sum of 4.5 and 3.2: 7.7
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 17
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-11
Aim: Develop a program for implementation of different functions of String class .
public class StringFunctionsDemo {
public static void main(String[] args) {
// Creating a string
String str = "Hello, Java Programming!";
// String Length
System.out.println("Length of the string: " + str.length());
// Convert to Uppercase
System.out.println("Uppercase: " + str.toUpperCase());
// Convert to Lowercase
System.out.println("Lowercase: " + str.toLowerCase());
// Check if String Contains a Substring
System.out.println("Contains 'Java': " + str.contains("Java"));
// Extract Substring
System.out.println("Substring (7 to 11): " + str.substring(7, 11));
// Replace a Word
System.out.println("Replace 'Java' with 'Python': " + str.replace("Java", "Python"));
// Find the Index of a Character
System.out.println("Index of 'J': " + str.indexOf('J'));
// Check if String Starts with "Hello"
System.out.println("Starts with 'Hello': " + str.startsWith("Hello"));
// Check if String Ends with "!"
System.out.println("Ends with '!': " + str.endsWith("!"));
// Trim Spaces
String spacedStr = " Hello World ";
System.out.println("Trimmed String: '" + spacedStr.trim() + "'");
}
}
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 18
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Output:
Length of the string: 24
Uppercase: HELLO, JAVA PROGRAMMING!
Lowercase: hello, java programming!
Contains 'Java': true
Substring (7 to 11): Java
Replace 'Java' with 'Python': Hello, Python Programming!
Index of 'J': 7
Starts with 'Hello': true
Ends with '!': true
Trimmed String: 'Hello World'
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 19
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-12
Aim: Develop a program for implementation of Wrapper Class to convert
primitive value into object (Boxing) and object into primitive value (Un-boxing).
public class WrapperClassDemo {
public static void main(String[] args) {
// Boxing (Primitive to Object)
int primitiveInt = 10;
Integer objectInt = Integer.valueOf(primitiveInt); // Explicit Boxing
Integer autoBoxedInt = primitiveInt; // Auto-Boxing
System.out.println("Primitive int: " + primitiveInt);
System.out.println("Boxed Integer object: " + objectInt);
System.out.println("Auto-Boxed Integer object: " + autoBoxedInt);
// Unboxing (Object to Primitive)
Integer objInteger = new Integer(20);
int unboxedInt = objInteger.intValue(); // Explicit Unboxing
int autoUnboxedInt = objInteger; // Auto-Unboxing
System.out.println("Integer Object: " + objInteger);
System.out.println("Unboxed primitive int: " + unboxedInt);
System.out.println("Auto-Unboxed primitive int: " + autoUnboxedInt);
}
}
Output:
Primitive int: 10
Boxed Integer object: 10
Auto-Boxed Integer object: 10
Integer Object: 20
Unboxed primitive int: 20
Auto-Unboxed primitive int: 20
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 20
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-13
Aim: Develop a program with a static block and show that it will be executed
before the main ( ) method in a class.
public class StaticBlockDemo {
// Static block - executes before main()
static {
System.out.println("Static block executed before main() method.");
}
public static void main(String[] args) {
System.out.println("Inside main() method.");
}
}
Output:
Static block executed before main() method.
Inside main() method.
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 21
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-14
Aim: Develop a program to demonstrate use of static functions
class MathOperations {
// Static method to calculate the square of a number
static int square(int num) {
return num * num;
}
// Static method to add two numbers
static int add(int a, int b) {
return a + b;
}
}
public class StaticFunctionDemo {
public static void main(String[] args) {
// Calling static methods without creating an object
System.out.println("Square of 5: " + MathOperations.square(5));
System.out.println("Sum of 10 and 20: " + MathOperations.add(10, 20));
}
}
Output:
Square of 5: 25
Sum of 10 and 20: 30
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 22
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-15
Aim: Develop a program to demonstrate use of ‘this’ keyword. Check whether
‘this’ can access the private members of the class or not.
class Student {
// Private variables (only accessible within the class)
private String name;
private int age;
// Constructor using 'this' to refer to instance variables
public Student(String name, int age) {
this.name = name; // 'this' refers to the current object's variable
this.age = age;
}
// Method to display student details
public void display() {
System.out.println("Name: " + this.name); // 'this' can access private members
System.out.println("Age: " + this.age);
}
}
public class ThisKeywordDemo {
public static void main(String[] args) {
// Creating an object of Student class
Student student1 = new Student("Alice", 20);
// Calling the display method
student1.display();
}
}
Output:
Name: Alice
Age: 20
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 23
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-16
Aim: Develop a program with an overloaded constructor. Also develop the copy
constructor to create a new object with the state of the existing object.
class Person {
String name;
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;
}
// Copy Constructor (creates a new object with the state of an existing object)
public Person(Person p) {
this.name = p.name;
this.age = p.age;
}
// Method to display details
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class ConstructorDemo {
public static void main(String[] args) {
// Using Default Constructor
Person person1 = new Person();
System.out.print("Person1: ");
person1.display();
// Using Parameterized Constructor
Person person2 = new Person("Alice", 25);
System.out.print("Person2: ");
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 24
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
person2.display();
// Using Copy Constructor
Person person3 = new Person(person2);
System.out.print("Person3 (Copy of Person2): ");
person3.display();
}
}
Output:
Person1: Name: Unknown, Age: 0
Person2: Name: Alice, Age: 25
Person3 (Copy of Person2): Name: Alice, Age: 25
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 25
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-17
Aim: Develop a program to demonstrate the use of private constructor and also
write a method which will count the number of instances created using default
constructor only.
class InstanceCounter {
private static int count = 0; // Static variable to count instances
// Private Constructor
private InstanceCounter() {
count++; // Increments count when an object is created
}
// Static method to create an object (since the constructor is private)
public static InstanceCounter createInstance() {
return new InstanceCounter();
}
// Method to get the instance count
public static int getInstanceCount() {
return count;
}
}
public class PrivateConstructorDemo {
public static void main(String[] args) {
// Creating objects using the static method
InstanceCounter obj1 = InstanceCounter.createInstance();
InstanceCounter obj2 = InstanceCounter.createInstance();
InstanceCounter obj3 = InstanceCounter.createInstance();
// Displaying the instance count
System.out.println("Total instances created: " + InstanceCounter.getInstanceCount());
}
}
Output:
Total instances created: 3
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 26
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-18
Aim: Develop a program to demonstrate single inheritance, multilevel inheritance,
and hierarchical inheritance.
// Single Inheritance: Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Single Inheritance: Derived class
class Dog extends Animal {
void bark() {
System.out.println("Dog barks.");
}
}
// Multilevel Inheritance: Another level of inheritance
class Puppy extends Dog {
void weep() {
System.out.println("Puppy weeps.");
}
}
// Hierarchical Inheritance: Another child class of Animal
class Cat extends Animal {
void meow() {
System.out.println("Cat meows.");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
// Single Inheritance Demonstration
Dog dog = new Dog();
System.out.println("Single Inheritance:");
dog.eat(); // Inherited from Animal
dog.bark();
// Multilevel Inheritance Demonstration
Puppy puppy = new Puppy();
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 27
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
System.out.println("\nMultilevel Inheritance:");
puppy.eat(); // Inherited from Animal
puppy.bark(); // Inherited from Dog
puppy.weep();
// Hierarchical Inheritance Demonstration
Cat cat = new Cat();
System.out.println("\nHierarchical Inheritance:");
cat.eat(); // Inherited from Animal
cat.meow();
}
}
Output:
Single Inheritance:
This animal eats food.
Dog barks.
Multilevel Inheritance:
This animal eats food.
Dog barks.
Puppy weeps.
Hierarchical Inheritance:
This animal eats food.
Cat meows.
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 28
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-19
Aim: Develop a program with one class named shape which has two member
functions named erase () and draw (). In the program we have three other
subclasses: circle, triangle and square. override methods of the superclass into
subclasses.
// Base class
class Shape {
// Method to be overridden
void draw() {
System.out.println("Drawing a shape.");
}
void erase() {
System.out.println("Erasing a shape.");
}
}
// Subclass 1: Circle
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Circle.");
}
@Override
void erase() {
System.out.println("Erasing a Circle.");
}
}
// Subclass 2: Triangle
class Triangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Triangle.");
}
@Override
void erase() {
System.out.println("Erasing a Triangle.");
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 29
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
}
}
// Subclass 3: Square
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a Square.");
}
void erase() {
System.out.println("Erasing a Square.");
}
}
public class ShapeDemo {
public static void main(String[] args) {
// Creating objects of subclasses
Shape shape1 = new Circle();
Shape shape2 = new Triangle();
Shape shape3 = new Square();
// Calling overridden methods
System.out.println("Circle:");
shape1.draw();
shape1.erase();
System.out.println("\nTriangle:");
shape2.draw();
shape2.erase();
System.out.println("\nSquare:");
shape3.draw();
shape3.erase();
}
}
Output:
Circle:
Drawing a Circle.
Erasing a Circle.
Triangle:
Drawing a Triangle.
Erasing a Triangle.
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 30
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Square:
Drawing a Square.
Erasing a Square.
Practical-20
Aim: Develop a program for implementation of Dynamic method dispatch.
// Superclass
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
// Subclass 1: Dog
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
// Subclass 2: Cat
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
public class DynamicDispatchDemo {
public static void main(String[] args) {
// Parent class reference
Animal animal;
// Parent reference pointing to Dog object
animal = new Dog();
animal.makeSound(); // Calls Dog's makeSound()
// Parent reference pointing to Cat object
animal = new Cat();
animal.makeSound(); // Calls Cat's makeSound()
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 31
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
}
}
Output:
Dog barks
Cat meows
Practical-21
Aim: Develop a java program that demonstrates the use of Abstract class.
// Abstract class
abstract class Shape {
// Abstract method (to be implemented by subclasses)
abstract void draw();
// Concrete method (common functionality)
void display() {
System.out.println("This is a shape.");
}
}
// Subclass 1: Circle
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Circle.");
}
}
// Subclass 2: Square
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a Square.");
}
}
public class AbstractClassDemo {
public static void main(String[] args) {
// Shape shape = new Shape(); // Not allowed (Cannot instantiate an abstract class)
// Creating objects of subclasses
Shape shape1 = new Circle();
Shape shape2 = new Square();
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 32
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
// Calling methods
shape1.display(); // Calls concrete method from Shape
shape1.draw(); // Calls overridden method in Circle
shape2.display();
shape2.draw(); // Calls overridden method in Square
}
}
Output:
This is a shape.
Drawing a Circle.
This is a shape.
Drawing a Square.
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 33
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-22
Aim: Develop a java program that illustrates interface inheritance. Interface ‘A1’
and ‘A2’ are extended from interface ‘A’. Interface ‘A12’ inherited from both
‘A1’and ‘A2’. Each interface declares one method and one constant. Class
‘Interface_Imple’ implements ‘A12’. Instantiate ‘Interface_Imple’ and invoke each
of its methods. Each method displays one of the constants.
// Base interface
interface A {
int CONST_A = 10; // Constant in A
void methodA(); // Abstract method in A
}
// Interface A1 extends A
interface A1 extends A {
int CONST_A1 = 20; // Constant in A1
void methodA1(); // Abstract method in A1
}
// Interface A2 extends A
interface A2 extends A {
int CONST_A2 = 30; // Constant in A2
void methodA2(); // Abstract method in A2
}
// Interface A12 extends A1 and A2 (Multiple inheritance)
interface A12 extends A1, A2 {
int CONST_A12 = 40; // Constant in A12
void methodA12(); // Abstract method in A12
}
// Class implementing A12
class Interface_Imple implements A12 {
@Override
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 34
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
public void methodA() {
System.out.println("Inside methodA, CONST_A: " + CONST_A);
}
@Override
public void methodA1() {
System.out.println("Inside methodA1, CONST_A1: " + CONST_A1);
}
@Override
public void methodA2() {
System.out.println("Inside methodA2, CONST_A2: " + CONST_A2);
}
@Override
public void methodA12() {
System.out.println("Inside methodA12, CONST_A12: " + CONST_A12);
}
}
// Main class to test the implementation
public class InterfaceInheritanceDemo {
public static void main(String[] args) {
// Instantiating the class
Interface_Imple obj = new Interface_Imple();
// Calling methods
obj.methodA();
obj.methodA1();
obj.methodA2();
obj.methodA12();
}
}
Output:
Inside methodA, CONST_A: 10
Inside methodA1, CONST_A1: 20
Inside methodA2, CONST_A2: 30
Inside methodA12, CONST_A12: 40
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 35
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-23
Aim: Develop a program to create a Package and demonstrate how packages are
used in java. And use java access modifier to demonstrate the access rules in a
package.
package mypackage; // Declaring the package
// Public class accessible outside the package
public class MyClass {
// Public variable - accessible everywhere
public String publicMessage = "Public: Accessible everywhere";
// Protected variable - accessible in the same package and subclasses
protected String protectedMessage = "Protected: Accessible within package & subclasses";
// Default variable - accessible only within the same package
String defaultMessage = "Default: Accessible within the package only";
// Private variable - accessible only within this class
private String privateMessage = "Private: Accessible only within this class";
// Method to access the private variable within the class
public void showPrivateMessage() {
System.out.println(privateMessage);
}
}
Output:
Public: Accessible everywhere
Private: Accessible only within this class
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 36
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-24
Aim: Develop a program to demonstrate the use of ‘super’ and ‘final’ keywords
// Final class cannot be inherited
final class ConstantValues {
public static final double PI = 3.14159; // Final variable (constant)
}
// Parent class
class Parent {
int num = 100;
// Final method to prevent overriding
public final void show() {
System.out.println("This is a final method in Parent class.");
}
// Constructor
Parent() {
System.out.println("Parent class constructor.");
}
}
// Child class extending Parent
class Child extends Parent {
int num = 200;
// Constructor using super to call parent class constructor
Child() {
super(); // Calls the Parent class constructor
System.out.println("Child class constructor.");
}
// Method to demonstrate 'super' usage
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 37
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
void display() {
System.out.println("Child class variable num: " + num);
System.out.println("Parent class variable num using super: " + super.num);
}
// Uncommenting below method will result in a compilation error
// because final methods cannot be overridden.
/*
@Override
public void show() {
System.out.println("Trying to override final method.");
}
*/
}
public class SuperFinalDemo {
public static void main(String[] args) {
Child obj = new Child(); // Calls constructors
obj.display();
obj.show(); // Calls final method from Parent class
// Accessing final variable from the final class
System.out.println("Value of PI: " + ConstantValues.PI);
}
}
Output:
Parent class constructor.
Child class constructor.
Child class variable num: 200
Parent class variable num using super: 100
This is a final method in Parent class.
Value of PI: 3.14159
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 38
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-25
Aim: Develop programs to demonstrate the use of Exception Handling using
predefined Exception Classes.
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// 1. ArithmeticException (Divide by Zero)
int a = 10, b = 0;
int result = a / b; // This will throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
try {
// 2. ArrayIndexOutOfBoundsException
int[] numbers = {1, 2, 3};
System.out.println("Fourth element: " + numbers[3]); // Out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
}
try {
// 3. NullPointerException
String str = null;
System.out.println("String length: " + str.length()); // This will throw
NullPointerException
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 39
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
}
// Finally block demonstration
finally {
System.out.println("Execution completed. Cleaning up resources...");
}
System.out.println("Program continues after handling exceptions.");
}
}
Output:
Caught ArithmeticException: / by zero
Caught ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Caught NullPointerException: Cannot invoke "String.length()" because "str" is null
Execution completed. Cleaning up resources...
Program continues after handling exceptions
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 40
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-26
Aim: Develop a program to handle multiple exceptions using multiple try blocks
and multiple catch blocks.
public class MultipleExceptionHandling {
public static void main(String[] args) {
try {
// First Try Block: ArithmeticException
int a = 10, b = 0;
int result = a / b; // This will throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
try {
// Second Try Block: ArrayIndexOutOfBoundsException
int[] numbers = {1, 2, 3};
System.out.println("Fourth element: " + numbers[3]); // Out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
}
try {
// Third Try Block: NullPointerException
String str = null;
System.out.println("String length: " + str.length()); // This will throw
NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 41
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
// Finally block executes after all try-catch blocks
finally {
System.out.println("Execution completed. Cleaning up resources...");
}
System.out.println("Program continues after handling exceptions.");
}
}
Output:
Caught ArithmeticException: / by zero
Caught ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Caught NullPointerException: Cannot invoke "String.length()" because "str" is null
Execution completed. Cleaning up resources...
Program continues after handling exceptions.
Practical-27
Aim: Develop a program to implement user defined exceptions.
// Step 1: Create a user-defined exception class
class InvalidAgeException extends Exception {
// Constructor to pass error message
public InvalidAgeException(String message) {
super(message);
}
}
public class UserDefinedExceptionDemo {
// Method to check age for voting eligibility
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above to vote.");
} else {
System.out.println("You are eligible to vote!");
}
}
public static void main(String[] args) {
try {
// Step 3: Test with an invalid age
checkAge(16); // This will throw the custom exception
} catch (InvalidAgeException e) {
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 42
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
System.out.println("Caught Exception: " + e.getMessage());
}
System.out.println("Program continues after handling the exception.");
}
}
Output:
Caught Exception: Age must be 18 or above to vote.
Program continues after handling the exception.
Practical-28
Aim: Develop a program to demonstrate use of throw, throws, and finally
keyword.
// Custom Exception Class
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class ThrowThrowsFinallyDemo {
// Method that uses `throws` to declare an exception
static void checkNumber(int num) throws CustomException {
if (num < 0) {
// Using `throw` to explicitly throw an exception
throw new CustomException("Number cannot be negative!");
} else {
System.out.println("Valid number: " + num);
}
}
public static void main(String[] args) {
try {
// Calling the method that may throw an exception
checkNumber(-5);
} catch (CustomException e) {
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 43
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
System.out.println("Caught Exception: " + e.getMessage());
}
// `finally` block executes no matter what
finally {
System.out.println("Finally block executed: Cleaning up resources...");
}
System.out.println("Program continues after handling exceptions.");
}
}
Output:
Caught Exception: Number cannot be negative!
Finally block executed: Cleaning up resources...
Program continues after handling exceptions.
Practical-29
Aim: Develop a program that executes two threads. One thread displays “Java
Programming” every 2 seconds, and the other displays “Semester - 4th” every 5
seconds.(Create the threads by extending the Thread class)
// Thread 1: Displays "Java Programming" every 2 seconds
class JavaThread extends Thread {
public void run() {
try {
while (true) {
System.out.println("Java Programming");
Thread.sleep(2000); // Pause for 2 seconds
}
} catch (InterruptedException e) {
System.out.println("JavaThread interrupted");
}
}
}
// Thread 2: Displays "Semester - 4th" every 5 seconds
class SemesterThread extends Thread {
public void run() {
try {
while (true) {
System.out.println("Semester - 4th");
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 44
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Thread.sleep(5000); // Pause for 5 seconds
}
} catch (InterruptedException e) {
System.out.println("SemesterThread interrupted");
}
}
}
// Main Class
public class MultiThreadDemo {
public static void main(String[] args) {
// Creating thread objects
JavaThread thread1 = new JavaThread();
SemesterThread thread2 = new SemesterThread();
// Starting both threads
thread1.start();
thread2.start();
}
}
Output:
Java Programming
Java Programming
Semester - 4th
Java Programming
Java Programming
Java Programming
Semester - 4th
...
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 45
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-30
Aim: Develop a program that executes two threads. One thread will print the even
numbers and the another thread will print odd numbers between 1 to 10.(Create the
thread by implementing runnable interface)
// Thread 1: Prints Even Numbers
class EvenNumberThread implements Runnable {
public void run() {
for (int i = 2; i <= 10; i += 2) {
System.out.println("Even: " + i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
System.out.println("EvenNumberThread interrupted");
}
}
}
}
// Thread 2: Prints Odd Numbers
class OddNumberThread implements Runnable {
public void run() {
for (int i = 1; i < 10; i += 2) {
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 46
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
System.out.println("Odd: " + i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
System.out.println("OddNumberThread interrupted");
}
}
}
}
// Main Class
public class EvenOddThreadDemo {
public static void main(String[] args) {
// Creating runnable objects
EvenNumberThread evenTask = new EvenNumberThread();
OddNumberThread oddTask = new OddNumberThread();
// Creating thread objects and passing runnable instances
Thread evenThread = new Thread(evenTask);
Thread oddThread = new Thread(oddTask);
// Starting both threads
evenThread.start();
oddThread.start();
}
}
Output:
Even: 2
Odd: 1
Even: 4
Odd: 3
Even: 6
Odd: 5
Even: 8
Odd: 7
Even: 10
Odd: 9
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 47
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-31
Aim: Develop a program to demonstrate use of synchronization of threads when
multiple threads are trying to update a common variable.
// Class representing a shared counter with a synchronized method for updating
class SharedCounter {
private int count = 0;
// Synchronized method to ensure thread-safe update
public synchronized void increment() {
count++;
}
// Method to retrieve the current count value
public int getCount() {
return count;
}
}
// Thread class that increments the shared counter
class CounterThread extends Thread {
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 48
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
private SharedCounter counter;
public CounterThread(SharedCounter counter) {
this.counter = counter;
}
public void run() {
// Each thread increments the counter 1000 times
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
public class SynchronizationDemo {
public static void main(String[] args) {
SharedCounter counter = new SharedCounter();
// Creating two threads that share the same counter instance
Thread t1 = new CounterThread(counter);
Thread t2 = new CounterThread(counter);
// Start both threads
t1.start();
t2.start();
// Wait for both threads to complete execution
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
// Print the final counter value (expected: 2000)
System.out.println("Final count: " + counter.getCount());
}
}
Output:
Final count: 2000
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 49
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
Practical-32
Aim: Develop programs to create, write, modify, read operations on Text files.
import java.io.*;
public class FileOperations {
// Method to create a file
public static void createFile(String fileName) {
File file = new File(fileName);
try {
if (file.createNewFile()) {
System.out.println("File created: " + fileName);
} else {
System.out.println("File already exists: " + fileName);
}
} catch (IOException e) {
System.out.println("Error creating file: " + e.getMessage());
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 50
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
}
}
// Method to write initial content to the file
public static void writeFile(String fileName, String content) {
try (FileWriter writer = new FileWriter(fileName)) {
writer.write(content);
System.out.println("Successfully wrote to the file: " + fileName);
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
// Method to modify (append) the file
public static void modifyFile(String fileName, String additionalContent) {
try (FileWriter writer = new FileWriter(fileName, true)) { // 'true' enables append mode
writer.write(additionalContent);
System.out.println("Successfully appended to the file: " + fileName);
} catch (IOException e) {
System.out.println("Error appending to file: " + e.getMessage());
}
}
// Method to read and display the file's content
public static void readFile(String fileName) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
System.out.println("Reading from file: " + fileName);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading from file: " + e.getMessage());
}
}
public static void main(String[] args) {
String fileName = "example.txt";
String initialContent = "Hello, this is the initial content of the file.\n";
String additionalContent = "This is additional content appended to the file.\n";
// Create file
createFile(fileName);
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 51
TATVA INSTITUTE OF TECHNOLOGICAL STUDIES, MODASA
Department of I.T. Engineering
// Write initial content to the file
writeFile(fileName, initialContent);
// Append additional content to the file
modifyFile(fileName, additionalContent);
// Read and display the content of the file
readFile(fileName);
}
}
T.I.T.S./D.E./I.T. / OOPJ/4th /Practical list 52