Java garbage collection: At which program point is the Bar object created on line 6 eligible for collection? class Bar { } class Test { Bar doBar() { Bar b = new Bar(); // line 6 return b; // line 7 } public static void main (String args[]) { Test t = new Test(); // line 11 Bar newBar = t.doBar(); // line 12 System.out.println("newBar"); newBar = new Bar(); // line 14 System.out.println("finishing"); // line 15 } }

Difficulty: Medium

Correct Answer: after line 14

Explanation:


Introduction / Context:
Garbage collection (GC) eligibility depends on reachability, not scope. An object becomes eligible when no live references from any GC root can reach it. This problem asks you to pinpoint that moment for a specific object.



Given Data / Assumptions:

  • Bar object created at line 6 and returned at line 7.
  • Assigned to newBar at line 12.
  • newBar is reassigned to a new Bar at line 14.


Concept / Approach:
While an object reference is stored in a local variable in a live stack frame, the object is reachable. Returning the reference from a method and assigning it to a local in the caller preserves reachability. Reassigning that local to a different object drops the last reference, making the original object eligible for GC.



Step-by-Step Solution:

Line 6: new Bar() created → referenced by local b.Line 7: b returned; at method exit the only live reference is in the caller once assigned.Line 12: newBar now references the same Bar → still reachable.Line 14: newBar is reassigned to a new Bar, dropping the last reference to the original. Original Bar becomes eligible here.


Verification / Alternative check:
Insert a System.identityHashCode print to differentiate the two Bar instances; observe eligibility change after reassignment.



Why Other Options Are Wrong:
After line 7 and line 12, there is still a reference (newBar). After line 15, eligibility already occurred at line 14. It is not a GC root.



Common Pitfalls:
Confusing scope exit of b with object lifetime; the returned reference keeps the object alive.



Final Answer:
after line 14

More Questions from Garbage Collections

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion