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:
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:
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
Discussion & Comments