0% found this document useful (0 votes)
3 views

Java Lab Cycle 3 (1)

The document outlines a series of lab exercises aimed at teaching various concepts in Java programming, including inheritance, method overriding, abstract classes, interfaces, exception handling, and file I/O operations. Each exercise includes objectives, problem statements, and expected outputs to guide learners through practical implementations. The exercises progress from basic inheritance to more complex topics like multilevel inheritance and the use of packages, culminating in file handling and exception management.

Uploaded by

alninalnin1901
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Lab Cycle 3 (1)

The document outlines a series of lab exercises aimed at teaching various concepts in Java programming, including inheritance, method overriding, abstract classes, interfaces, exception handling, and file I/O operations. Each exercise includes objectives, problem statements, and expected outputs to guide learners through practical implementations. The exercises progress from basic inheritance to more complex topics like multilevel inheritance and the use of packages, culminating in file handling and exception management.

Uploaded by

alninalnin1901
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Lab Exercise 1: Inheritance Basics

Objective: Understand the concept of inheritance and how to create a subclass from a
superclass.

Problem Statement:

1. Create a superclass Vehicle with the following properties:


○ String brand
○ int speed
2. The class should have:
○ A constructor to initialise the properties.
○ A method void displayDetails() to display the vehicle's details.
3. Create a subclass Car that inherits from Vehicle. The Car class should have:
○ An additional property int numberOfDoors.
○ A constructor that initializes all properties, including those from the superclass.
○ Override the displayDetails() method to include the number of doors.
4. In the main method, create an object of the Car class, and use it to display all the
details of the car.

Expected Output:

Brand: Toyota
Speed: 180 km/h
Number of Doors: 4

Lab Exercise 2: Using super Keyword

Objective: Learn how to use the super keyword to invoke superclass methods and
constructors.

Problem Statement:

1. Create a superclass Person with the following properties:


○ String name
○ int age
2. The class should have:
○ A constructor to initialize the properties.
○ A method void displayInfo() to display the person's information.
3. Create a subclass Student that inherits from Person. The Student class should
have:
○ An additional property int studentID.
○ A constructor that initializes the name and age using the super keyword, and
initializes studentID.
○ Override the displayInfo() method to include the student ID, using the
super keyword to call the displayInfo() method of the superclass.
4. In the main method, create an object of the Student class, and use it to display the
student's details.

Expected Output:

Name: John Doe


Age: 20
Student ID: 12345

Lab Exercise 3: Superclass Method Overriding and super Usage

Objective: Understand method overriding and the role of super in accessing overridden
methods.

Problem Statement:

1. Create a superclass Animal with a method void sound() that prints "Animal makes a
sound".
2. Create a subclass Dog that overrides the sound() method to print "Dog barks".
3. In the Dog class, create a method void makeSound() that:
○ Calls the sound() method of the superclass using the super keyword.
○ Calls the overridden sound() method of the Dog class.
4. In the main method, create an object of the Dog class and call the makeSound()
method.

Expected Output:

Animal makes a sound


Dog barks

Lab Exercise 4: Constructor Chaining using super

Objective: Practice constructor chaining in inheritance using the super keyword.

Problem Statement:
1. Create a superclass Employee with the following properties:
○ String name
○ double salary
2. The class should have:
○ A constructor that initializes these properties.
○ A method void display() to display the employee's information.
3. Create a subclass Manager that has:
○ An additional property int teamSize.
○ A constructor that uses the super keyword to initialize name and salary, and
initializes teamSize.
○ Override the display() method to include the team size.
4. In the main method, create an object of the Manager class and use it to display the
manager's details.

Expected Output:

Name: Alice Johnson


Salary: 75000.0
Team Size: 10

Lab Exercise 5: Real-World Application of Inheritance and super

Objective: Apply inheritance concepts to solve a real-world problem.

Problem Statement:

1. Create a superclass Appliance with the following properties:


○ String brand
○ int power
2. The class should have:
○ A constructor to initialize these properties.
○ A method void displayInfo() to display the appliance's information.
3. Create a subclass WashingMachine with:
○ An additional property int capacity.
○ A constructor that uses the super keyword to initialize the brand and power,
and initializes capacity.
○ Override the displayInfo() method to include the capacity.
4. Create another subclass Refrigerator with:
○ An additional property int volume.
○ A constructor that uses the super keyword to initialize the brand and power,
and initializes volume.
○ Override the displayInfo() method to include the volume.
5. In the main method, create objects of WashingMachine and Refrigerator, and
display their details.

Expected Output:

Brand: Samsung
Power: 1500 W
Capacity: 7 kg

Brand: LG
Power: 500 W
Volume: 350 liters
-------------------------------------------------------------------------------------------------------------------------------

Lab Exercise 6: Multilevel Hierarchy

Objective: Understand the concept of multilevel inheritance in Java.

Problem Statement:

1. Create a base class Animal with the following properties:


○ String name
○ A method void eat() that prints "<name> eats food.".
2. Create a subclass Mammal that inherits from Animal and adds:
○ A method void walk() that prints "<name> walks on land.".
3. Create another subclass Dog that inherits from Mammal and adds:
○ A method void bark() that prints "<name> barks.".
4. In the main method, create an object of the Dog class and call the eat(), walk(), and
bark() methods.

Expected Output:

Dog eats food.


Dog walks on land.
Dog barks.
Lab Exercise 7: Method Overriding

Objective: Learn how to override methods in a subclass.

Problem Statement:

1. Create a superclass Shape with a method void draw() that prints "Drawing a
shape".
2. Create a subclass Circle that inherits from Shape and overrides the draw() method
to print "Drawing a circle".
3. Create another subclass Rectangle that also inherits from Shape and overrides the
draw() method to print "Drawing a rectangle".
4. In the main method, create objects of Circle and Rectangle and call the draw()
method on each.

Expected Output:

Drawing a circle
Drawing a rectangle

Lab Exercise 8: Method Overriding with super

Objective: Understand how to call a superclass's overridden method using super.

Problem Statement:

1. Create a superclass Vehicle with a method void start() that prints "Vehicle is
starting".
2. Create a subclass Car that overrides the start() method to print "Car is
starting", but also calls the superclass's start() method using super.
3. In the main method, create an object of the Car class and call the start() method.

Expected Output:

Vehicle is starting
Car is starting

Lab Exercise 9: Using final with Variables, Methods, and Classes

Objective: Understand the use of the final keyword with variables, methods, and classes.
Problem Statement:

1. Create a class Constants with a final variable PI (value: 3.14159) and a final
method getPI() that returns the value of PI.
2. Attempt to create a subclass MathConstants that tries to override the getPI()
method. Observe the compilation error and discuss why overriding is not allowed.
3. Create a final class ImmutableClass with a final method showMessage() that
prints "This is an immutable class".
4. Attempt to create a subclass ExtendedClass that tries to extend ImmutableClass.
Observe the compilation error and discuss why inheritance is not allowed.
5. In the main method, demonstrate that PI cannot be changed by attempting to reassign
its value. Discuss the immutability enforced by final.

Expected Observations:

● Attempting to override a final method results in a compilation error.


● Attempting to extend a final class results in a compilation error.
● Attempting to reassign a final variable results in a compilation error.

Lab Exercise 10: Real-World Application of Multilevel Hierarchy and final

Objective: Apply the concepts of multilevel inheritance, method overriding, and the final
keyword in a real-world scenario.

Problem Statement:

1. Create a base class Employee with the following properties:


○ String name
○ double salary
○ A method void work() that prints "<name> is working.".
2. Create a subclass Manager that inherits from Employee and adds:
○ A method void manage() that prints "<name> is managing the team.".
3. Create another subclass SeniorManager that inherits from Manager and overrides the
work() method to print "<name> is handling strategic tasks.", while still
using super to call the original work() method.
4. Make the SeniorManager class final to prevent further inheritance.
5. In the main method, create an object of SeniorManager and call the work() and
manage() methods.

Expected Output:

Senior Manager is working.


Senior Manager is handling strategic tasks.
Senior Manager is managing the team.
-------------------------------------------------------------------------------------------------------------------------------

Lab Exercise 11: Programs Using Packages

Objective: Understand the creation and usage of packages in Java.

Problem Statement:

1. Create a package com.college.student and define a class Student in this


package with the following properties:
○ String name
○ int rollNumber
A method void displayDetails() that prints the student's name and roll

number.
2. Create another package com.college.course and define a class Course in this
package with the following properties:
○ String courseName
○ int courseID
○ A method void showCourse() that prints the course name and course ID.
3. In the main method of a separate class, use the classes from both packages to create a
Student and assign them to a Course. Display the details of both the student and the
course.

Expected Output:

Student Name: John Doe


Roll Number: 101

Course Name: Java Programming


Course ID: 502

Lab Exercise 12: Abstract Classes

Objective: Learn how to use abstract classes to create a template for subclasses.

Problem Statement:

1. Create an abstract class BankAccount with the following properties:


○ String accountNumber
○ double balance
○ An abstract method void calculateInterest().
2. Create a subclass SavingsAccount that inherits from BankAccount and implements
the calculateInterest() method. The method should calculate and print the
interest as balance * 0.04.
3. Create another subclass CurrentAccount that also inherits from BankAccount and
implements the calculateInterest() method. For CurrentAccount, interest
should be calculated as balance * 0.02.
4. In the main method, create objects of SavingsAccount and CurrentAccount, set
their balances, and calculate and display the interest for each.

Expected Output:

Savings Account Interest: 400.0


Current Account Interest: 200.0

Lab Exercise 13: Abstract Classes with Concrete Methods

Objective: Understand the use of abstract classes with both abstract and concrete methods.

Problem Statement:

1. Create an abstract class Shape with:


○ An abstract method double area().
○ A concrete method void displayArea() that calls the area() method and
prints the result.
2. Create a subclass Circle that inherits from Shape and implements the area()
method to return the area of a circle (π * radius * radius).
3. Create another subclass Rectangle that inherits from Shape and implements the
area() method to return the area of a rectangle (length * width).
4. In the main method, create objects of Circle and Rectangle, set their dimensions,
and use displayArea() to print their areas.

Expected Output:

Area of Circle: 78.54


Area of Rectangle: 200.0
Lab Exercise 14: Interfaces

Objective: Learn how to define and implement interfaces in Java.

Problem Statement:

1. Create an interface Payable with a method double calculatePay().


2. Create a class Employee that implements the Payable interface with the following
properties:
○ String name
○ double hoursWorked
○ double hourlyRate
○ Implement the calculatePay() method to return hoursWorked *
hourlyRate.
3. Create another class Contractor that also implements the Payable interface with the
following properties:
○ String name
○ double fixedPayment
○ Implement the calculatePay() method to return the fixedPayment.
4. In the main method, create objects of Employee and Contractor, set their details,
and calculate and display their pay.

Expected Output:

Employee Pay: 1200.0


Contractor Pay: 3000.0

Lab Exercise 15: Multiple Interfaces

Objective: Understand how to implement multiple interfaces in a single class.

Problem Statement:

1. Create an interface Printable with a method void print().


2. Create another interface Scannable with a method void scan().
3. Create a class MultiFunctionPrinter that implements both Printable and
Scannable interfaces. The print() method should print "Printing
document...", and the scan() method should print "Scanning document...".
4. In the main method, create an object of MultiFunctionPrinter and call both the
print() and scan() methods.
Expected Output:

Printing document...
Scanning document...

Lab Exercise 16: Abstract Classes vs. Interfaces

Objective: Compare the use of abstract classes and interfaces in Java.

Problem Statement:

1. Create an abstract class Appliance with a concrete method void powerOn() that
prints "Appliance is powered on" and an abstract method void operate().
2. Create an interface RemoteControl with a method void turnOn().
3. Create a class TV that inherits from Appliance and implements RemoteControl. The
turnOn() method should print "TV is turned on with remote", and the
operate() method should print "TV is operating".
4. In the main method, create an object of TV, call the turnOn(), powerOn(), and
operate() methods, and discuss the differences between abstract classes and
interfaces based on this example.

Expected Output:

TV is turned on with remote


Appliance is powered on
TV is operating
-------------------------------------------------------------------------------------------------------------------------

Lab Exercise 17: Program Using Exception Handling

Objective: Understand how to handle exceptions in Java.

Problem Statement:

1. Write a program that accepts two integers from the user and performs division.
2. Implement exception handling to manage the following cases:
○ Division by zero (ArithmeticException)
○ Input mismatch when the user enters non-integer values
(InputMismatchException)
3. In the main method, display appropriate error messages if exceptions are caught, and
ensure the program continues to run.

Expected Output:

Enter the first number: 10


Enter the second number: 0
Error: Division by zero is not allowed.

Enter the first number: 10


Enter the second number: ABC
Error: Please enter valid integers.

Lab Exercise 18: Nested Try-Catch Blocks

Objective: Learn how to use nested try-catch blocks for handling multiple exceptions.

Problem Statement:

1. Write a program that reads an integer array from the user.


2. Implement nested try-catch blocks to handle the following:
○ Array index out of bounds (ArrayIndexOutOfBoundsException)
○ Division by zero when performing operations on array elements
(ArithmeticException)
3. In the main method, display appropriate messages for each type of exception.

Expected Output:

Enter the size of the array: 3


Enter array elements:
10
20
0
Attempting to divide 100 by array elements:
Result 1: 10
Result 2: 5
Error: Division by zero is not allowed.

Lab Exercise 19: Programs Using I/O Basics


Objective: Learn basic I/O operations in Java, including reading from and writing to the console.

Problem Statement:

1. Write a program that asks the user to input their name, age, and favorite color, and then
displays this information.
2. Use Scanner for input and System.out.println for output.

Expected Output:

Enter your name: Alice


Enter your age: 25
Enter your favorite color: Blue
Hello, Alice! You are 25 years old, and your favorite color is Blue.

Lab Exercise 20: Reading and Writing Files

Objective: Understand how to read from and write to files in Java.

Problem Statement:

1. Write a program that reads a list of names from a file called input.txt and writes
these names to another file called output.txt, but in uppercase.
2. Implement proper exception handling for file-related errors, such as
FileNotFoundException and IOException.

Expected Output:

input.txt (Content):
John
Jane
Bob

output.txt (Content):
JOHN
JANE
BOB

Lab Exercise 21: Appending Data to a File


Objective: Learn how to append data to an existing file.

Problem Statement:

1. Write a program that appends a new line of text to an existing file called notes.txt.
2. Ensure that if the file does not exist, it is created.
3. Implement exception handling for file-related errors.

Expected Output:

● Before appending:

Meeting at 10 AM


● After appending:

notes.txt:
Meeting at 10 AM
Don't forget the reports.

Lab Exercise 22: Handling Multiple Exceptions in File I/O

Objective: Learn how to handle multiple exceptions in file I/O operations.

Problem Statement:

1. Write a program that reads an integer from a file called data.txt and performs division
with another integer entered by the user.
2. Handle the following exceptions:
○ FileNotFoundException if the file does not exist.
○ NumberFormatException if the file content is not a valid integer.
○ ArithmeticException for division by zero.
3. Implement a finally block to close the file resource if it was successfully opened.

Expected Output:

Enter a number to divide by: 0


Error: Division by zero is not allowed.

Enter a number to divide by: 5


The result is: 4

Lab Exercise 23: Reading and Writing Objects to Files

Objective: Understand how to serialize and deserialize objects in Java.

Problem Statement:

1. Create a class Person with the following properties:


○ String name
○ int age
○ Implement Serializable interface.
2. Write a program that serializes an object of the Person class to a file called
person.dat.
3. Write another program that deserializes the object from the file and displays its contents.

Expected Output:

Serialized Object:
Name: Alice, Age: 30

Deserialized Object:

Deserialized Name: Alice

● Deserialized Age: 30

You might also like