Course contentsShow
← Java
Lesson 299 of 2,8707. Reference Types and Object FundamentalsFree lesson

When Objects Become Eligible for GC

Identifying scenarios where objects lose all references and become candidates for garbage collection.

When Objects Become Eligible for GC

What you'll learn: You'll discover the exact conditions that make an object eligible for garbage collection so the JVM can reclaim its memory.

The Core Idea

An object becomes eligible for garbage collection when it is no longer reachable from any live part of your program. In simpler terms: if there's no way for your running code to access that object anymore, the garbage collector can safely remove it from the heap.

Think of it like balloons tied to your wrist with strings. As long as you're holding the string (a reference), the balloon stays with you. Cut all the strings (lose all references), and the balloon floats away—just like an object becoming eligible for GC.

Common Scenarios

1. Reassigning a reference:

Person p = new Person("Alice");
p = new Person("Bob");  // Alice object now has zero references

2. Setting a reference to null:

String message = new String("Hello");
message = null;  // String object is now eligible

3. Reference goes out of scope:

void process() {
    Car car = new Car();  // car reference exists
}  // car goes out of scope here; Car object becomes eligible

4. Multiple references all removed:

Dog d1 = new Dog();
Dog d2 = d1;  // Two references to same Dog
d1 = null;    // Still one reference left
d2 = null;    // NOW the Dog object is eligible

The Key Point

An object needs zero references pointing to it to become eligible. Even one remaining reference keeps it alive on the heap.

Key Takeaway: An object becomes eligible for garbage collection the moment no references in your active code point to it—whether through reassignment, nulling, or going out of scope.