Department of Computer Science
Name : B. Sc. (CS) 2nd Year (Open Elective)
Subject : Oops With Java
LAB MANUAL
Sr. Experiment Title Experiment Page
No. Date No.
1. Java Basic Program Structure – Printing "Hello, World!"
2. Data Types and Variables – Primitive vs. Non-Primitive
3. Control Statements – Sum of Even Numbers (1 to 100)
4. Classes and Objects – Student Class
5. Methods – Method Overloading for Area Calculation
6. Constructor – Parameterized & Default Constructor in Car Class
7. Inheritance – Vehicle, Car, and Bike (Hierarchical Inheritance)
8. Polymorphism – Method Overriding in Bank Interest Rates
9. Encapsulation – Account Class with Getters & Setters
10. Abstraction – Abstract Shape Class (Circle & Rectangle)
11. Interfaces – Multiple Inheritance using Interfaces
12. Exception Handling – Handling ArrayIndexOutOfBounds & Arithmetic
Exceptions
13. File Handling – Reading from One File & Writing to Another
14. Multithreading – Two Threads Printing Numbers Alternately
15. Collections Framework – ArrayList vs. LinkedList (Insertion &
Deletion)
Experiment 1: Java Basic Program Structure – Printing
"Hello, World!"
1. Title Page
Experiment Title: Java Basic Program Structure – Printing "Hello, World!"
2. Objective
To write a Java program that prints "Hello, World!" and understand the role of each component
in the program.
3. Problem Statement
Develop a Java program that prints "Hello, World!" and explain the structure of a Java program.
4. Algorithm / Logic
1. Start the program.
2. Define a class named HelloWorld.
3. Inside the class, create a main method.
4. Use [Link]() to print "Hello, World!".
5. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
7. Input & Output
Input: No user input required.
Output:
Hello, World!
8. Explanation of Code
public class HelloWorld {} defines the class.
public static void main(String[] args) {} is the main method where execution
starts.
[Link]("Hello, World!"); prints the message to the console.
9. Test Cases
Test Case Expected Output Actual Output
1 Hello, World! Hello, World!
10. Observations & Results
The program successfully prints "Hello, World!".
The structure of a Java program is understood.
11. Conclusion
The experiment was successfully completed. The Java program correctly prints "Hello, World!"
and demonstrates the basic structure of a Java program.
12. Enhancements / Future Scope
Modify the program to accept user input and display a custom message.
Extend the program with additional print statements.
Experiment 2: Data Types and Variables – Primitive vs.
Non-Primitive
1. Title Page
Experiment Title: Data Types and Variables – Primitive vs. Non-Primitive
2. Objective
To write a Java program demonstrating the difference between primitive and non-primitive data
types.
3. Problem Statement
Develop a Java program that declares and initializes primitive and non-primitive data types and
displays their values.
4. Algorithm / Logic
1. Start the program.
2. Declare and initialize variables of different primitive types (int, float, char, boolean, etc.).
3. Declare and initialize a non-primitive type (String).
4. Print all variables.
5. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
public class DataTypesDemo {
public static void main(String[] args) {
int number = 10;
float decimal = 5.5f;
char letter = 'A';
boolean flag = true;
String text = "Hello, Java!";
[Link]("Integer: " + number);
[Link]("Float: " + decimal);
[Link]("Character: " + letter);
[Link]("Boolean: " + flag);
[Link]("String: " + text);
}
}
7. Input & Output
Input: No user input required.
Output:
Integer: 10
Float: 5.5
Character: A
Boolean: true
String: Hello, Java!
8. Explanation of Code
Declares and initializes primitive types (int, float, char, boolean).
Declares and initializes a non-primitive type (String).
Prints all variable values.
9. Test Cases
Test Case Expected Output Actual Output
1 Integer: 10, Float: 5.5, ... Integer: 10, Float: 5.5, ...
10. Observations & Results
The program successfully demonstrates primitive and non-primitive data types.
The output matches the expected values.
11. Conclusion
The experiment was successfully completed. The Java program correctly demonstrates primitive
and non-primitive data types and displays their values.
12. Enhancements / Future Scope
Add more data types, such as arrays and objects.
Accept user input for different types.
Java: The Complete Reference by Herbert Schildt
Experiment 3: Java Control Statements – Sum of Even Numbers (1
to 100)
1. Title Page
Experiment Title: Java Control Statements – Sum of Even Numbers (1 to 100)
2. Objective
To write a Java program that calculates the sum of even numbers from 1 to 100 using control
statements.
3. Problem Statement
Develop a Java program that uses a loop to sum all even numbers between 1 and 100 and explain
the use of control statements.
4. Algorithm / Logic
1. Start the program.
2. Initialize a variable sum to 0.
3. Use a loop to iterate through numbers from 1 to 100.
4. Check if the number is even using the modulus operator (%).
5. If even, add the number to sum.
6. After the loop ends, print the total sum.
7. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
public class SumEvenNumbers {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
}
}
[Link]("Sum of even numbers from 1 to 100: " + sum);
}
}
7. Input & Output
Input: No user input required.
Output:
Sum of even numbers from 1 to 100: 2550
8. Explanation of Code
int sum = 0; initializes a variable to store the sum.
for (int i = 1; i <= 100; i++) loops through numbers from 1 to 100.
if (i % 2 == 0) checks if the number is even.
sum += i; adds the even number to sum.
The final sum is printed after the loop.
9. Test Cases
Test Case Expected Output
1 Sum of even numbers from 1 to 100: 2550
10. Observations & Results
The program successfully calculates the sum of even numbers from 1 to 100.
The use of control statements is understood.
11. Conclusion
The experiment was successfully completed. The Java program correctly calculates the sum of
even numbers using control statements.
12. Enhancements / Future Scope
Modify the program to calculate the sum for any user-defined range.
Extend the program to sum odd numbers as well.
Java: The Complete Reference by Herbert Schildt
Experiment 4: Java Classes and Objects – Student Class
1. Title Page
Experiment Title: Java Classes and Objects – Student Class
2. Objective
To write a Java program that demonstrates the concept of classes and objects using a Student
class.
3. Problem Statement
Develop a Java program that defines a Student class with attributes and methods to display
student details.
4. Algorithm / Logic
1. Start the program.
2. Define a class named Student.
3. Declare attributes such as name, rollNumber, and marks.
4. Create a constructor to initialize these attributes.
5. Define a method to display student details.
6. In the main method, create an object of the Student class and call the method to display
details.
7. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
class Student {
String name;
int rollNumber;
double marks;
// Constructor
Student(String name, int rollNumber, double marks) {
[Link] = name;
[Link] = rollNumber;
[Link] = marks;
}
void displayDetails() {
[Link]("Student Name: " + name);
[Link]("Roll Number: " + rollNumber);
[Link]("Marks: " + marks);
}
public static void main(String[] args) {
Student student1 = new Student("John Doe", 101, 95.5);
[Link]();
}
}
7. Input & Output
Input: No user input required; values are assigned in the constructor.
Output:
Student Name: John Doe
Roll Number: 101
Marks: 95.5
8. Explanation of Code
class Student {} defines the class.
Attributes name, rollNumber, and marks store student information.
The constructor initializes these attributes.
void displayDetails() prints student details.
The main method creates an object and calls displayDetails().
9. Test Cases
Test Case Expected Output
1 Student Name: John Doe, Roll Number: 101, Marks: 95.5
10. Observations & Results
The program successfully demonstrates the concept of classes and objects.
The Student class correctly stores and displays student details.
11. Conclusion
The experiment was successfully completed. The Java program correctly implements a class and
object using a Student class.
12. Enhancements / Future Scope
Extend the program to accept user input for student details.
Add more attributes and methods, such as calculating grades.
Java: The Complete Reference by Herbert Schildt
Experiment 5: Java Methods – Method Overloading for Area
Calculation
1. Title Page
Experiment Title: Java Methods – Method Overloading for Area Calculation
2. Objective
To write a Java program that demonstrates method overloading by calculating the area of
different shapes.
3. Problem Statement
Develop a Java program that uses method overloading to calculate the area of a square,
rectangle, and circle.
4. Algorithm / Logic
1. Start the program.
2. Define a class named AreaCalculator.
3. Create overloaded methods to calculate the area of a square, rectangle, and circle.
4. Implement each method using appropriate formulas.
5. In the main method, create an object of AreaCalculator and call the overloaded
methods with different arguments.
6. Display the calculated area.
7. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
class AreaCalculator {
// Method to calculate area of a square
double calculateArea(double side) {
return side * side;
}
// Method to calculate area of a rectangle
double calculateArea(double length, double width) {
return length * width;
}
// Method to calculate area of a circle
double calculateArea(double radius, boolean isCircle) {
return [Link] * radius * radius;
}
public static void main(String[] args) {
AreaCalculator calculator = new AreaCalculator();
[Link]("Area of square: " + [Link](5));
[Link]("Area of rectangle: " +
[Link](5, 10));
[Link]("Area of circle: " + [Link](7,
true));
}
}
7. Input & Output
Input: No user input required; values are passed as arguments.
Output:
Area of square: 25.0
Area of rectangle: 50.0
Area of circle: 153.93804002589985
8. Explanation of Code
class AreaCalculator {} defines the class.
calculateArea(double side) computes the area of a square.
calculateArea(double length, double width) computes the area of a rectangle.
calculateArea(double radius, boolean isCircle) computes the area of a circle
using [Link].
The main method creates an object and calls each overloaded method.
9. Test Cases
Test Case Shape Input Expected Output
1 Square 5 25.0
2 Rectangle 5, 10 50.0
3 Circle 7 153.93804002589985
10. Observations & Results
The program successfully demonstrates method overloading.
The area of square, rectangle, and circle is correctly calculated using different overloaded
methods.
11. Conclusion
The experiment was successfully completed. The Java program correctly implements method
overloading for area calculations.
12. Enhancements / Future Scope
Extend the program to include more shapes such as triangles and parallelograms.
Allow user input to provide dimensions dynamically.
Java: The Complete Reference by Herbert Schildt
Experiment 6: Java Constructors – Parameterized & Default
Constructor in Car Class
1. Title Page
Experiment Title: Java Constructors – Parameterized & Default Constructor in Car Class
2. Objective
To write a Java program that demonstrates the concept of default and parameterized constructors
using a Car class.
3. Problem Statement
Develop a Java program that defines a Car class with attributes for brand, model, and year.
Implement both a default constructor and a parameterized constructor to initialize objects with
different values.
4. Algorithm / Logic
1. Start the program.
2. Define a class named Car.
3. Declare attributes such as brand, model, and year.
4. Create a default constructor that initializes attributes with default values.
5. Create a parameterized constructor to initialize attributes with specific values.
6. Define a method to display car details.
7. In the main method, create objects using both constructors and display their details.
8. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
class Car {
String brand;
String model;
int year;
// Default constructor
Car() {
[Link] = "Unknown";
[Link] = "Unknown";
[Link] = 0;
}
// Parameterized constructor
Car(String brand, String model, int year) {
[Link] = brand;
[Link] = model;
[Link] = year;
}
// Method to display car details
void displayCarDetails() {
[Link]("Car Brand: " + brand);
[Link]("Car Model: " + model);
[Link]("Car Year: " + year);
}
public static void main(String[] args) {
Car defaultCar = new Car();
Car myCar = new Car("Toyota", "Corolla", 2022);
[Link]("Default Car:");
[Link]();
[Link]("\nMy Car:");
[Link]();
}
}
7. Input & Output
Input: No user input required; values are set in constructors.
Output:
Default Car:
Car Brand: Unknown
Car Model: Unknown
Car Year: 0
My Car:
Car Brand: Toyota
Car Model: Corolla
Car Year: 2022
8. Explanation of Code
class Car {} defines the class.
Attributes brand, model, and year store car details.
The default constructor initializes attributes with generic values.
The parameterized constructor initializes attributes with user-defined values.
The displayCarDetails() method prints the car's details.
The main method creates objects using both constructors and displays their details.
9. Test Cases
Test Case Constructor Type Expected Output
1 Default Constructor Brand: Unknown, Model: Unknown, Year: 0
2 Parameterized Constructor Brand: Toyota, Model: Corolla, Year: 2022
10. Observations & Results
The program successfully demonstrates the concept of constructors.
The default constructor initializes attributes with generic values, while the parameterized
constructor initializes them with specific values.
11. Conclusion
The experiment was successfully completed. The Java program correctly implements both
default and parameterized constructors in the Car class.
12. Enhancements / Future Scope
Extend the program to allow user input for car details.
Add additional attributes such as color and price.
Java: The Complete Reference by Herbert Schildt
Experiment 6: Java Inheritance – Vehicle, Car, and Bike
(Hierarchical Inheritance)
1. Title Page
Experiment Title: Java Inheritance – Vehicle, Car, and Bike (Hierarchical Inheritance)
2. Objective
To write a Java program that demonstrates hierarchical inheritance using a Vehicle superclass
and Car and Bike subclasses.
3. Problem Statement
Develop a Java program that defines a Vehicle superclass with attributes and methods. Create
Car and Bike subclasses that inherit from Vehicle and implement additional features.
4. Algorithm / Logic
1. Start the program.
2. Define a superclass named Vehicle with attributes like brand and speed and a method
to display details.
3. Define subclasses Car and Bike that extend Vehicle.
4. Add specific attributes and methods for Car and Bike.
5. In the main method, create objects of Car and Bike and display their details.
6. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
// Superclass Vehicle
class Vehicle {
String brand;
int speed;
Vehicle(String brand, int speed) {
[Link] = brand;
[Link] = speed;
}
void displayInfo() {
[Link]("Brand: " + brand);
[Link]("Speed: " + speed + " km/h");
}
}
// Subclass Car
class Car extends Vehicle {
int seats;
Car(String brand, int speed, int seats) {
super(brand, speed);
[Link] = seats;
}
void displayCarDetails() {
displayInfo();
[Link]("Seats: " + seats);
}
}
// Subclass Bike
class Bike extends Vehicle {
boolean hasGear;
Bike(String brand, int speed, boolean hasGear) {
super(brand, speed);
[Link] = hasGear;
}
void displayBikeDetails() {
displayInfo();
[Link]("Has Gear: " + (hasGear ? "Yes" : "No"));
}
}
public class HierarchicalInheritanceDemo {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 180, 5);
Bike myBike = new Bike("Yamaha", 120, true);
[Link]("Car Details:");
[Link]();
[Link]("\nBike Details:");
[Link]();
}
}
7. Input & Output
Input: No user input required; values are set in constructors.
Output:
Car Details:
Brand: Toyota
Speed: 180 km/h
Seats: 5
Bike Details:
Brand: Yamaha
Speed: 120 km/h
Has Gear: Yes
8. Explanation of Code
class Vehicle {} is the superclass containing attributes and a method for displaying
information.
class Car extends Vehicle {} inherits from Vehicle and adds seats.
class Bike extends Vehicle {} inherits from Vehicle and adds hasGear.
The main method creates objects of Car and Bike and displays their details.
9. Test Cases
Test Vehicle Input Expected Output
Case Type
1 Car Toyota, 180, 5 Brand: Toyota, Speed: 180 km/h, Seats: 5
2 Bike Yamaha, 120, Brand: Yamaha, Speed: 120 km/h, Has Gear:
true Yes
10. Observations & Results
The program successfully demonstrates hierarchical inheritance.
The Car and Bike classes inherit attributes and methods from Vehicle and extend them
with specific functionalities.
11. Conclusion
The experiment was successfully completed. The Java program correctly implements
hierarchical inheritance using a Vehicle superclass and Car and Bike subclasses.
12. Enhancements / Future Scope
Extend the program to include more vehicle types like Truck or Bus.
Add additional features such as fuel type or mileage.
Java: The Complete Reference by Herbert Schildt
Experiment 7: Java Polymorphism – Method Overriding in Bank
Interest Rates
1. Title Page
Experiment Title: Java Polymorphism – Method Overriding in Bank Interest Rates
2. Objective
To demonstrate method overriding by implementing different interest rates for different banks
using polymorphism.
3. Problem Statement
Develop a Java program that defines a parent class Bank with a method for returning interest
rates. Create child classes SBI, ICICI, and HDFC that override this method to provide specific
interest rates.
4. Algorithm / Logic
1. Start the program.
2. Define a superclass Bank with a method getInterestRate().
3. Create subclasses SBI, ICICI, and HDFC that override getInterestRate().
4. In the main method, create objects of different banks and display their interest rates.
5. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
// Parent class Bank
class Bank {
double getInterestRate() {
return 0;
}
}
// Child class SBI
class SBI extends Bank {
double getInterestRate() {
return 5.5;
}
}
// Child class ICICI
class ICICI extends Bank {
double getInterestRate() {
return 6.0;
}
}
// Child class HDFC
class HDFC extends Bank {
double getInterestRate() {
return 6.5;
}
}
public class BankInterestDemo {
public static void main(String[] args) {
Bank sbi = new SBI();
Bank icici = new ICICI();
Bank hdfc = new HDFC();
[Link]("SBI Interest Rate: " + [Link]() +
"%");
[Link]("ICICI Interest Rate: " + [Link]()
+ "%");
[Link]("HDFC Interest Rate: " + [Link]() +
"%");
}
}
7. Input & Output
Input: No user input required; objects are created with predefined values.
Output:
SBI Interest Rate: 5.5%
ICICI Interest Rate: 6.0%
HDFC Interest Rate: 6.5%
8. Explanation of Code
class Bank {} defines a parent class with a method for interest rate.
class SBI extends Bank {} overrides getInterestRate() to return 5.5%.
class ICICI extends Bank {} overrides getInterestRate() to return 6.0%.
class HDFC extends Bank {} overrides getInterestRate() to return 6.5%.
The main method demonstrates polymorphism by creating bank objects and calling
overridden methods.
9. Test Cases
Test Case Bank Expected Interest Rate
1 SBI 5.5%
2 ICICI 6.0%
3 HDFC 6.5%
10. Observations & Results
The program successfully demonstrates method overriding.
The Bank class provides a default method, and subclasses override it to return specific
interest rates.
11. Conclusion
The experiment was successfully completed. The Java program correctly implements
polymorphism using method overriding for bank interest rates.
12. Enhancements / Future Scope
Extend the program to include more banks with different interest rates.
Add user input to allow dynamic selection of banks.
Java: The Complete Reference by Herbert Schildt
Experiment 8: Java Encapsulation – Account Class with Getters &
Setters
1. Title Page
Experiment Title: Java Encapsulation – Account Class with Getters & Setters
2. Objective
To demonstrate encapsulation by implementing a bank account class with private data members
and public getter and setter methods.
3. Problem Statement
Develop a Java program that defines a class Account with private attributes accountNumber and
balance. Implement getter and setter methods to access and modify these attributes while
maintaining encapsulation.
4. Algorithm / Logic
1. Start the program.
2. Define a class Account with private attributes.
3. Implement public getter and setter methods for controlled access.
4. In the main method, create an account object and modify its attributes using setters.
5. Display account details using getters.
6. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
class Account {
private String accountNumber;
private double balance;
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
[Link] = accountNumber;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
if (balance >= 0) {
[Link] = balance;
} else {
[Link]("Invalid balance amount!");
}
}
}
public class EncapsulationDemo {
public static void main(String[] args) {
Account acc = new Account();
[Link]("123456789");
[Link](5000);
[Link]("Account Number: " + [Link]());
[Link]("Balance: " + [Link]());
}
}
7. Input & Output
Input: No user input required; values are set using setter methods.
Output:
Account Number: 123456789
Balance: 5000.0
8. Explanation of Code
class Account {} defines a bank account class with private attributes.
Public getter and setter methods control access to accountNumber and balance.
The setBalance() method ensures only valid balance amounts are set.
The main method creates an account object, modifies attributes using setters, and
retrieves values using getters.
9. Test Cases
Test Case Input Expected Output
1 123456789, 5000 Account Number: 123456789, Balance: 5000.0
2 987654321, -100 Invalid balance amount!
10. Observations & Results
The program successfully demonstrates encapsulation.
Private data members are accessed only through getter and setter methods.
11. Conclusion
The experiment was successfully completed. The Java program correctly implements
encapsulation in an Account class.
12. Enhancements / Future Scope
Add more account functionalities such as deposit and withdrawal methods.
Implement user authentication for secure access.
Java: The Complete Reference by Herbert Schildt
Experiment 10: Java Abstraction – Abstract Shape Class (Circle &
Rectangle)
1. Title Page
Experiment Title: Java Abstraction – Abstract Shape Class (Circle & Rectangle)
2. Objective
To demonstrate abstraction in Java using an abstract class Shape with Circle and Rectangle
subclasses.
3. Problem Statement
Develop a Java program that defines an abstract class Shape with an abstract method to calculate
the area. Implement Circle and Rectangle subclasses that provide specific implementations.
4. Algorithm / Logic
1. Start the program.
2. Define an abstract class Shape with an abstract method calculateArea().
3. Create Circle and Rectangle classes that extend Shape.
4. Implement the calculateArea() method in each subclass.
5. In the main method, create objects of Circle and Rectangle and call calculateArea().
6. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
abstract class Shape {
abstract void calculateArea();
}
class Circle extends Shape {
double radius;
Circle(double radius) {
[Link] = radius;
}
void calculateArea() {
[Link]("Area of Circle: " + ([Link] * radius * radius));
}
}
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
void calculateArea() {
[Link]("Area of Rectangle: " + (length * width));
}
}
public class AbstractionDemo {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
[Link]();
[Link]();
}
}
7. Input & Output
Input: No user input required; values are set in constructors.
Output:
Area of Circle: 78.53981633974483
Area of Rectangle: 24.0
8. Explanation of Code
abstract class Shape {} defines an abstract class with an abstract method
calculateArea().
class Circle extends Shape {} implements calculateArea() for a circle.
class Rectangle extends Shape {} implements calculateArea() for a rectangle.
The main method creates objects of Circle and Rectangle and calls calculateArea().
9. Test Cases
Test Case Shape Input Expected Output
1 Circle Radius = 5 Area: 78.54
2 Rectangle Length = 4, Width = 6 Area: 24.0
10. Observations & Results
The program successfully demonstrates abstraction in Java.
The Shape class provides a blueprint for its subclasses, enforcing implementation of
calculateArea().
11. Conclusion
The experiment was successfully completed. The Java program correctly implements abstraction
using an abstract class and its concrete subclasses.
12. Enhancements / Future Scope
Extend the program to include more shapes like Triangle or Square.
Add additional functionalities such as perimeter calculations.
Java: The Complete Reference by Herbert Schildt
Experiment 11: Java Interfaces – Multiple Inheritance using
Interfaces
1. Title Page
Experiment Title: Java Interfaces – Multiple Inheritance using Interfaces
2. Objective
To demonstrate multiple inheritance in Java using interfaces.
3. Problem Statement
Develop a Java program that defines two interfaces, Printable and Showable, and a class that
implements both interfaces.
4. Algorithm / Logic
1. Start the program.
2. Define two interfaces Printable and Showable, each with a method declaration.
3. Create a class MultiInheritanceDemo that implements both interfaces.
4. Implement the methods from both interfaces in the class.
5. In the main method, create an object of MultiInheritanceDemo and call the methods.
6. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
interface Printable {
void print();
}
interface Showable {
void show();
}
class MultiInheritanceDemo implements Printable, Showable {
public void print() {
[Link]("Printing...");
}
public void show() {
[Link]("Showing...");
}
public static void main(String[] args) {
MultiInheritanceDemo obj = new MultiInheritanceDemo();
[Link]();
[Link]();
}
}
7. Input & Output
Input: No user input required.
Output:
Printing...
Showing...
8. Explanation of Code
interface Printable {} defines an interface with a method print().
interface Showable {} defines another interface with a method show().
class MultiInheritanceDemo implements Printable, Showable {} implements
both interfaces.
The main method creates an object of MultiInheritanceDemo and calls print() and
show().
9. Test Cases
Test Case Action Expected Output
1 Call print() Printing...
2 Call show() Showing...
10. Observations & Results
The program successfully demonstrates multiple inheritance using interfaces.
A single class can implement multiple interfaces without ambiguity.
11. Conclusion
The experiment was successfully completed. The Java program correctly implements multiple
inheritance using interfaces.
12. Enhancements / Future Scope
Extend the program to include more interfaces with additional functionalities.
Implement real-world scenarios such as a Readable and Writable interface.
Java: The Complete Reference by Herbert Schildt
Experiment 12: Java Exception Handling – Handling
ArrayIndexOutOfBounds & Arithmetic Exceptions
1. Title Page
Experiment Title: Java Exception Handling – Handling ArrayIndexOutOfBounds & Arithmetic
Exceptions
2. Objective
To demonstrate exception handling in Java by handling ArrayIndexOutOfBoundsException
and ArithmeticException using try-catch blocks.
3. Problem Statement
Develop a Java program that handles ArrayIndexOutOfBoundsException and
ArithmeticException using exception handling mechanisms.
4. Algorithm / Logic
1. Start the program.
2. Create an array and try accessing an invalid index to generate
ArrayIndexOutOfBoundsException.
3. Perform division by zero to generate ArithmeticException.
4. Use try-catch blocks to handle these exceptions and display appropriate messages.
5. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
[Link](arr[5]); // This will cause
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception Caught: Array index out of
bounds!");
}
try {
int result = 10 / 0; // This will cause ArithmeticException
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Exception Caught: Division by zero!");
}
}
}
7. Input & Output
Input: No user input required.
Output:
Exception Caught: Array index out of bounds!
Exception Caught: Division by zero!
8. Explanation of Code
try block is used to execute code that may cause an exception.
catch (ArrayIndexOutOfBoundsException e) {} handles invalid array access.
catch (ArithmeticException e) {} handles division by zero.
9. Test Cases
Test Case Input Expected Output
1 Access index 5 in array {1, 2, 3} Exception Caught: Array index out of bounds!
2 Perform 10 / 0 Exception Caught: Division by zero!
10. Observations & Results
The program successfully handles exceptions using try-catch blocks.
Proper error messages are displayed when exceptions occur.
11. Conclusion
The experiment was successfully completed. The Java program correctly handles
ArrayIndexOutOfBoundsException and ArithmeticException using exception handling
mechanisms.
12. Enhancements / Future Scope
Extend the program to handle more exceptions like NullPointerException or
InputMismatchException.
Implement custom exception handling for user-defined scenarios.
Java: The Complete Reference by Herbert Schildt
Experiment 13: Java File Handling – Reading from One File &
Writing to Another
1. Title Page
Experiment Title: Java File Handling – Reading from One File & Writing to Another
2. Objective
To demonstrate file handling in Java by reading content from one file and writing it to another.
3. Problem Statement
Develop a Java program that reads data from a source file and writes it to a destination file using
file handling mechanisms.
4. Algorithm / Logic
1. Start the program.
2. Open a source file for reading using FileReader.
3. Open a destination file for writing using FileWriter.
4. Read content from the source file and write it to the destination file.
5. Close both files.
6. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
import [Link].*;
public class FileHandlingDemo {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("[Link]");
FileWriter writer = new FileWriter("[Link]");
int ch;
while ((ch = [Link]()) != -1) {
[Link](ch);
}
[Link]();
[Link]();
[Link]("File copied successfully!");
} catch (IOException e) {
[Link]("An error occurred: " + [Link]());
}
}
}
7. Input & Output
Input: Source file ([Link]) with some text.
Output: The content is copied to [Link].
File copied successfully!
8. Explanation of Code
FileReader is used to read data from [Link].
FileWriter is used to write data to [Link].
while ((ch = [Link]()) != -1) { [Link](ch); } reads and writes
character by character.
Files are closed using [Link]() and [Link]().
9. Test Cases
Test Case Input (Source File) Expected Output (Destination File)
1 "Hello, World!" "Hello, World!"
2 "Java File Handling" "Java File Handling"
10. Observations & Results
The program successfully reads data from one file and writes it to another.
File handling in Java is implemented using FileReader and FileWriter.
11. Conclusion
The experiment was successfully completed. The Java program correctly implements file
handling by reading from a source file and writing to a destination file.
12. Enhancements / Future Scope
Extend the program to handle large files using BufferedReader and BufferedWriter.
Add error handling for cases like missing or unreadable files.
Java: The Complete Reference by Herbert Schildt
Experiment 14: Java Multithreading – Two Threads Printing
Numbers Alternately
1. Title Page
Experiment Title: Java Multithreading – Two Threads Printing Numbers Alternately
2. Objective
To demonstrate multithreading in Java by creating two threads that print numbers alternately.
3. Problem Statement
Develop a Java program that creates two threads, where one thread prints even numbers and the
other prints odd numbers alternately.
4. Algorithm / Logic
1. Start the program.
2. Create a shared class with a synchronized method to control alternate printing.
3. Create two threads: one for even numbers and one for odd numbers.
4. Start both threads and ensure proper synchronization.
5. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
class SharedPrinter {
private boolean isOdd = true;
synchronized void printOdd(int num) {
while (!isOdd) {
try {
wait();
} catch (InterruptedException e) {
[Link]();
}
}
[Link](num);
isOdd = false;
notify();
}
synchronized void printEven(int num) {
while (isOdd) {
try {
wait();
} catch (InterruptedException e) {
[Link]();
}
}
[Link](num);
isOdd = true;
notify();
}
}
class OddThread extends Thread {
SharedPrinter sp;
OddThread(SharedPrinter sp) { [Link] = sp; }
public void run() {
for (int i = 1; i <= 10; i += 2) {
[Link](i);
}
}
}
class EvenThread extends Thread {
SharedPrinter sp;
EvenThread(SharedPrinter sp) { [Link] = sp; }
public void run() {
for (int i = 2; i <= 10; i += 2) {
[Link](i);
}
}
}
public class MultithreadingDemo {
public static void main(String[] args) {
SharedPrinter sp = new SharedPrinter();
Thread oddThread = new OddThread(sp);
Thread evenThread = new EvenThread(sp);
[Link]();
[Link]();
}
}
7. Input & Output
Input: No user input required.
Output:
1
2
3
4
5
6
7
8
9
10
8. Explanation of Code
SharedPrinter class controls the synchronization for alternate printing.
OddThread and EvenThread handle odd and even number printing, respectively.
wait() and notify() ensure proper synchronization.
9. Test Cases
Test Case Expected Output
1 1 2 3 4 5 6 7 8 9 10
10. Observations & Results
The program successfully prints numbers alternately using two threads.
Proper synchronization ensures correct order of execution.
11. Conclusion
The experiment was successfully completed. The Java program correctly demonstrates
multithreading with synchronized alternate printing.
12. Enhancements / Future Scope
Extend the program to include multiple threads.
Implement a more dynamic approach using executors.
Java: The Complete Reference by Herbert Schildt
Experiment 15: Java Collections Framework – ArrayList vs.
LinkedList (Insertion & Deletion)
1. Title Page
Experiment Title: Java Collections Framework – ArrayList vs. LinkedList (Insertion &
Deletion)
2. Objective
To compare ArrayList and LinkedList in terms of insertion and deletion performance.
3. Problem Statement
Develop a Java program that inserts and deletes elements in ArrayList and LinkedList and
compares their execution time.
4. Algorithm / Logic
1. Start the program.
2. Create an ArrayList and LinkedList.
3. Insert elements into both lists and measure the time taken.
4. Delete elements from both lists and measure the time taken.
5. Compare results.
6. End the program.
5. Programming Language & Tools
Language Used: Java
Compiler: JDK
IDE Used: Eclipse / IntelliJ IDEA / VS Code
6. Code Implementation
import [Link].*;
public class CollectionsComparison {
public static void main(String[] args) {
List<Integer> arrayList = new ArrayList<>();
List<Integer> linkedList = new LinkedList<>();
long startTime, endTime;
// Insertion in ArrayList
startTime = [Link]();
for (int i = 0; i < 100000; i++) {
[Link](i);
}
endTime = [Link]();
[Link]("ArrayList Insertion Time: " + (endTime -
startTime) + " ns");
// Insertion in LinkedList
startTime = [Link]();
for (int i = 0; i < 100000; i++) {
[Link](i);
}
endTime = [Link]();
[Link]("LinkedList Insertion Time: " + (endTime -
startTime) + " ns");
// Deletion in ArrayList
startTime = [Link]();
[Link]();
endTime = [Link]();
[Link]("ArrayList Deletion Time: " + (endTime -
startTime) + " ns");
// Deletion in LinkedList
startTime = [Link]();
[Link]();
endTime = [Link]();
[Link]("LinkedList Deletion Time: " + (endTime -
startTime) + " ns");
}
}
7. Input & Output
Input: No user input required.
Output: Execution times for insertion and deletion operations.
8. Explanation of Code
ArrayList and LinkedList are used for comparison.
[Link]() measures execution time.
clear() is used to delete elements.
9. Test Cases
Test Case Expected Output
1 ArrayList and LinkedList execution times
10. Observations & Results
ArrayList performs faster in random access.
LinkedList is better for frequent insertions/deletions.
11. Conclusion
The experiment was successfully completed. The Java program correctly demonstrates the
differences in insertion and deletion performance between ArrayList and LinkedList.
12. Enhancements / Future Scope
Compare with Vector and Stack.
Implement performance tests with different data structures.
Java: The Complete Reference by Herbert Schildt