When does an object become eligible for garbage collection in Java?
An object is eligible once no live thread can reach it through any chain of references from the GC roots, such as local variables, static fields and active threads. Setting a reference to null or leaving its scope can make it unreachable.
Explain it simply
A visiting card sitting in a drawer nobody can open is useless. Likewise, an object that no running code can reach is waste. The garbage collector starts from the known "roots", follows every reference, and treats anything it never touched as removable.
Example
class Ticket { int pnr; Ticket(int pnr) { this.pnr = pnr; } }
Ticket a = new Ticket(101);
Ticket b = a; // two references to one object
a = null; // object still reachable through b
b = null; // now unreachable: eligible for GC
Ticket x = new Ticket(1);
Ticket y = new Ticket(2);
x = y; // Ticket(1) has no reference left: eligibleWhat to say in the interview
"Java uses reachability, not reference counting. GC roots include local variables on active stacks, static fields, live threads, and JNI references. If an object cannot be reached from any root, it is eligible, even if other unreachable objects point to it, so circular references are not a problem. Eligible does not mean collected immediately; the JVM decides when to run a collection."
Common mistakes
- Believing null assignments are needed everywhere. Local variables disappear when the method ends.
- Thinking two objects pointing to each other can never be collected.