📖 Scenario: Imagine you are managing a small library system. Each book is represented as an object. You want to understand when these book objects are created and when they are no longer needed (destroyed).
🎯 Goal: You will create a simple Java program that shows the creation and destruction of book objects by printing messages when objects are created and when they are about to be destroyed by the garbage collector.
📋 What You'll Learn
Create a Book class with a constructor that prints a creation message
Override the finalize() method in Book to print a destruction message
Create multiple Book objects in the main method
Remove references to some Book objects and call the garbage collector
Print messages to observe object lifetime
💡 Why This Matters
🌍 Real World
Understanding object lifetime helps manage memory in programs and avoid memory leaks.
💼 Career
Java developers must know how objects are created and cleaned up to write efficient and reliable applications.
Progress0 / 4 steps
1
Create the Book class with constructor
Create a class called Book with a constructor that prints "Book created" when a new object is made.
Java
Hint
The constructor has the same name as the class and no return type.
2
Add finalize method to Book class
Inside the Book class, add a protected void finalize() method that prints "Book destroyed" when the object is about to be removed by the garbage collector.
Java
Hint
Use @Override annotation and call super.finalize() inside the method.
3
Create Book objects and remove references
In the main method, create three Book objects named b1, b2, and b3. Then set b2 and b3 to null to remove their references.
Java
Hint
Remember to declare variables with the type Book and assign new objects using new Book().
4
Call garbage collector and print message
After setting b2 and b3 to null, call System.gc() to suggest garbage collection. Then print "Garbage collector called" to observe the output.
Java
Hint
Use System.gc() to suggest garbage collection and System.out.println() to print the message.
Practice
(1/5)
1. Which statement best describes the lifetime of an object in Java?
easy
A. An object exists as long as there is at least one reference to it.
B. An object exists only during the execution of the main method.
C. An object is deleted immediately after it is created.
D. An object exists forever once created, regardless of references.
Solution
Step 1: Understand object references in Java
Objects are created using new and remain in memory while referenced.
Step 2: Recognize garbage collection behavior
When no references point to an object, Java's garbage collector can remove it.
Final Answer:
An object exists as long as there is at least one reference to it. -> Option A
Quick Check:
Object lifetime depends on references [OK]
Hint: Remember: objects live while referenced, else garbage collected [OK]
Common Mistakes:
Thinking objects exist only during main method
Believing objects are deleted immediately after creation
Assuming objects live forever regardless of references
2. Which of the following is the correct way to create a new object in Java?
easy
A. MyClass obj = MyClass();
B. MyClass obj = create MyClass();
C. MyClass obj = new MyClass();
D. MyClass obj = new MyClass;
Solution
Step 1: Recall Java object creation syntax
Objects are created using the new keyword followed by the constructor call with parentheses.
Step 2: Check each option's syntax
MyClass obj = new MyClass(); uses correct syntax: new MyClass();. Options A, C, and D are incorrect due to missing new, wrong keywords, or missing parentheses.
Final Answer:
MyClass obj = new MyClass(); -> Option C
Quick Check:
Use new ClassName() to create objects [OK]
Hint: Use 'new' keyword plus parentheses to create objects [OK]
Common Mistakes:
Omitting the 'new' keyword
Forgetting parentheses after class name
Using incorrect keywords like 'create'
3. What will be the output of the following code?
class Test {
public static void main(String[] args) {
Test obj1 = new Test();
Test obj2 = obj1;
obj1 = null;
if (obj2 != null) {
System.out.println("Object alive");
} else {
System.out.println("Object dead");
}
}
}
medium
A. Runtime exception
B. Object dead
C. Compilation error
D. Object alive
Solution
Step 1: Analyze object references
Initially, obj1 points to the new object. Then obj2 also points to the same object.
Step 2: Check effect of setting obj1 to null
Setting obj1 to null removes one reference, but obj2 still references the object, so it remains alive.
Final Answer:
Object alive -> Option D
Quick Check:
Object lives while any reference exists [OK]
Hint: Object stays alive if any reference points to it [OK]
Common Mistakes:
Assuming object is dead after one reference is null
Confusing references with object existence
Expecting compilation or runtime errors
4. Identify the error in the following code related to object lifetime:
public class Demo {
public static void main(String[] args) {
String s = new String("Hello");
s = null;
System.out.println(s.length());
}
}
medium
A. Compilation error due to missing import
B. NullPointerException at runtime
C. No error, prints length of string
D. Syntax error in object creation
Solution
Step 1: Understand object reference and null assignment
The variable s initially references a String object, then is set to null, removing the reference.
Step 2: Analyze method call on null reference
Calling s.length() when s is null causes a NullPointerException at runtime.
Final Answer:
NullPointerException at runtime -> Option B
Quick Check:
Calling methods on null causes NullPointerException [OK]
Hint: Never call methods on null references [OK]
Common Mistakes:
Thinking code compiles but runs fine
Expecting compilation errors instead of runtime
Ignoring null assignment effect
5. Consider the following code snippet:
class Node {
Node next;
int value;
Node(int v) { value = v; }
}
public class Test {
public static void main(String[] args) {
Node a = new Node(1);
Node b = new Node(2);
a.next = b;
b = null;
// Which objects are eligible for garbage collection here?
}
}
Which objects are eligible for garbage collection after setting b = null;?
hard
A. No objects are eligible because a still references b through next.
B. Only object b is eligible because b reference is null.
C. Both a and b objects are eligible for garbage collection.
D. Only object a is eligible because b is null.
Solution
Step 1: Analyze references to objects
Variable a references the first Node object. Its next field references the second Node object originally referenced by b.
Step 2: Understand effect of setting b to null
Setting b to null removes one reference to the second Node, but a.next still references it, so it is not eligible for garbage collection.
Final Answer:
No objects are eligible because a still references b through next. -> Option A
Quick Check:
Objects live while any reference exists [OK]
Hint: Check all references, including fields, before assuming garbage collection [OK]
Common Mistakes:
Assuming null variable means object is collectible
Ignoring references inside other objects
Confusing variable nullification with object lifetime
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.