0% found this document useful (0 votes)
3 views6 pages

Java OOP Lab Assignment

This document outlines a laboratory assignment for Java programming focused on object lifecycle and interfaces, including topics such as object creation, finalization, garbage collection, and polymorphism. It presents two programs: one that tracks object creation and finalization using a unique ID, and another that demonstrates the use of an interface for calculating the area of shapes like circles and triangles. Additionally, it includes explanations, sample outputs, and a set of viva questions and answers related to the concepts covered.

Uploaded by

shayarigazak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

Java OOP Lab Assignment

This document outlines a laboratory assignment for Java programming focused on object lifecycle and interfaces, including topics such as object creation, finalization, garbage collection, and polymorphism. It presents two programs: one that tracks object creation and finalization using a unique ID, and another that demonstrates the use of an interface for calculating the area of shapes like circles and triangles. Additionally, it includes explanations, sample outputs, and a set of viva questions and answers related to the concepts covered.

Uploaded by

shayarigazak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Programming — Laboratory Assignment Object Lifecycle & Interfaces

JAVA PROGRAMMING
Laboratory Assignment

Object Lifecycle & Interfaces

Topics Covered

Object Creation & Finalization | finalize() Method | Garbage Collection


Interface | Polymorphism | Shape Hierarchy | Runtime Binding

[Link] / BCA / [Link]. (Computer Science) • Object-Oriented Programming

Program 1: Object Creation & Finalization Tracker

Objective
Write a Java program that tracks the total number of objects created and finalized. Each object
must be assigned a unique ID at the time of creation, and the same ID must be printed when the
object is finalized by the Garbage Collector.

Key Concepts

Concept Description

[Link] / BCA / [Link]. CS • OOP with Java Page 1


Java Programming — Laboratory Assignment Object Lifecycle & Interfaces

static variable Shared across all instances; used to generate unique IDs and maintain
counters.
finalize() method Called by the JVM Garbage Collector just before an object is reclaimed
from memory.
[Link]() A hint to the JVM to run Garbage Collection (not guaranteed to run
immediately).
Unique Object ID Assigned via an incrementing static counter inside the constructor.

Java Source Code

import [Link];
import [Link];

public class ObjectTracker {


private static int objectCount = 0;
private static int finalizedCount = 0;
private int objectId;

public ObjectTracker() {
objectCount++;
[Link] = objectCount;
[Link]("Object Created | ID: " + objectId +
" | Total Created: " + objectCount);
}

@Override
protected void finalize() throws Throwable {
finalizedCount++;
[Link]("Object Finalized | ID: " + objectId +
" | Total Finalized: " + finalizedCount);
[Link]();
}

public static int getObjectCount() { return objectCount; }


public static int getFinalizedCount() { return finalizedCount; }

public static void main(String[] args) throws InterruptedException {


[Link]("===== Object Creation & Finalization Tracker =====\n");

ObjectTracker obj1 = new ObjectTracker();


ObjectTracker obj2 = new ObjectTracker();
ObjectTracker obj3 = new ObjectTracker();

[Link]("\n--- Making obj1 and obj2 eligible for GC ---");


obj1 = null;
obj2 = null;

[Link](); // Request GC
[Link](500); // Give GC time to run

[Link]("\n--- Creating more objects ---");


ObjectTracker obj4 = new ObjectTracker();
ObjectTracker obj5 = new ObjectTracker();

obj3 = null;

[Link] / BCA / [Link]. CS • OOP with Java Page 2


Java Programming — Laboratory Assignment Object Lifecycle & Interfaces

obj4 = null;

[Link]();
[Link](500);

[Link]("\n===== Final Summary =====");


[Link]("Total Objects Created : " + getObjectCount());
[Link]("Total Objects Finalized: " + getFinalizedCount());
[Link]("Objects Still Active : " +
(getObjectCount() - getFinalizedCount()));
}
}

Program Output

===== Object Creation & Finalization Tracker =====

Object Created | ID: 1 | Total Created: 1


Object Created | ID: 2 | Total Created: 2
Object Created | ID: 3 | Total Created: 3

--- Making obj1 and obj2 eligible for GC ---


Object Finalized | ID: 2 | Total Finalized: 1
Object Finalized | ID: 1 | Total Finalized: 2

--- Creating more objects ---


Object Created | ID: 4 | Total Created: 4
Object Created | ID: 5 | Total Created: 5
Object Finalized | ID: 3 | Total Finalized: 3
Object Finalized | ID: 4 | Total Finalized: 4

===== Final Summary =====


Total Objects Created : 5
Total Objects Finalized: 4
Objects Still Active : 1

Explanation
1. Every time new ObjectTracker() is called, the constructor increments the static counter and
assigns the current value as the object's unique ID.
2. When obj1 and obj2 are set to null, they become eligible for Garbage Collection. After
[Link]() and a short sleep, the JVM calls their finalize() methods.
3. The finalize() method prints the stored ID, proving which specific object was collected.
4. The final summary shows total created, total finalized, and how many objects are still alive in
memory.

[Link] / BCA / [Link]. CS • OOP with Java Page 3


Java Programming — Laboratory Assignment Object Lifecycle & Interfaces

Program 2: Shape Interface with Circle & Triangle

Objective
Create a Shape interface with an abstract method area(). Derive two concrete classes — Circle and
Triangle — from it. Use a Shape reference variable (polymorphism) to fill data members and display
the area of each shape. Input must be taken from the user at runtime.

Key Concepts

Concept Description
interface A contract that declares method signatures without implementation; all
methods are implicitly public and abstract.
implements Keyword used by a class to provide concrete implementations for all
interface methods.
Polymorphism A Shape reference variable (shapeRef) can point to any object whose
class implements Shape.
Runtime Binding The JVM decides at runtime which area() implementation to call based on
the actual object type.
Scanner Java utility class used to read user input from the console.

Java Source Code

import [Link];

// Shape Interface
interface Shape {
double area();
}

// Circle class implementing Shape


class Circle implements Shape {
private double radius;

public void fillData(Scanner sc) {


[Link]("Enter radius of Circle: ");
radius = [Link]();
}

@Override
public double area() {
return [Link] * radius * radius;
}
}

// Triangle class implementing Shape


class Triangle implements Shape {

[Link] / BCA / [Link]. CS • OOP with Java Page 4


Java Programming — Laboratory Assignment Object Lifecycle & Interfaces

private double base;


private double height;

public void fillData(Scanner sc) {


[Link]("Enter base of Triangle : ");
base = [Link]();
[Link]("Enter height of Triangle: ");
height = [Link]();
}

@Override
public double area() {
return 0.5 * base * height;
}
}

public class ShapeDemo {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("===== Shape Area Calculator =====\n");

// Using Shape reference for Circle


Circle c = new Circle();
[Link](sc);
Shape shapeRef = c; // Shape reference
[Link]("Area of Circle : %.4f sq. units%n%n",
[Link]());

// Using Shape reference for Triangle


Triangle t = new Triangle();
[Link](sc);
shapeRef = t; // Reassign Shape
reference
[Link]("Area of Triangle : %.4f sq. units%n", [Link]());

[Link]();
}
}

Sample Output

===== Shape Area Calculator =====

Enter radius of Circle: 7


Area of Circle : 153.9380 sq. units

Enter base of Triangle : 10


Enter height of Triangle: 6
Area of Triangle : 30.0000 sq. units

[Link] / BCA / [Link]. CS • OOP with Java Page 5


Java Programming — Laboratory Assignment Object Lifecycle & Interfaces

Formulae Used
Circle Area : π × r² (where r = radius, π ≈ 3.14159…)
Triangle Area : ½ × base × height

Explanation
1. The Shape interface declares a single method area() that every implementing class must define.
2. Circle and Triangle each implement area() with their respective geometric formulae.
3. The fillData() method in each class uses a Scanner object to accept runtime input from the user.
4. In main(), a Shape reference (shapeRef) is first pointed to a Circle, then reassigned to a Triangle
— demonstrating polymorphism and runtime method binding.

Viva Questions & Answers

Q1. What is the purpose of the finalize() method in Java?


The finalize() method is called by the Garbage Collector just before it reclaims an object's memory.
It can be overridden to perform cleanup (e.g., releasing resources), but its execution is not
guaranteed.

Q2. Is [Link]() guaranteed to invoke Garbage Collection immediately?


No. [Link]() is only a suggestion/hint to the JVM. The JVM may choose to ignore it or run GC at
a later time.

Q3. What is the difference between an abstract class and an interface?


An interface can only have abstract methods (prior to Java 8) and constants. An abstract class can
have both abstract and concrete methods, and can maintain state. A class can implement multiple
interfaces but can extend only one abstract class.

Q4. What is polymorphism? How is it shown in Program 2?


Polymorphism allows one reference variable to refer to objects of different types. In Program 2,
shapeRef (of type Shape) points to both Circle and Triangle at different points, calling the
appropriate area() method at runtime.

Q5. What happens if a class does not implement all methods of an interface?
The compiler throws an error. A class must implement every abstract method declared in the
interface, or it must itself be declared abstract.

[Link] / BCA / [Link]. CS • OOP with Java Page 6

You might also like