After the assignment on line 8, how many X objects are eligible for garbage collection? public class X { public static void main(String [] args) { X x = new X(); X x2 = m1(x); // line 6 X x4 = new X(); x2 = x4; // line 8 doComplexStuff(); } static X m1(X mx) { mx = new X(); return mx; } }
-
A0
-
B1
-
C2
-
D3
-
EDepends on doComplexStuff()
Answer
Correct Answer: 1
Explanation
Introduction / Context:Counting eligible objects requires tracking each allocation and the references that point to them. The twist is the method m1 that returns a newly created object.
Given Data / Assumptions:
- Allocations: one for
xin main, one inm1, and one forx4in main. - After line 8,
x2is reassigned to refer tox4.
Concept / Approach:Track objects: A1 (for x), A2 (returned by m1 and held in x2), A3 (held by x4). Reassigning x2 = x4 drops the last reference to A2, making A2 eligible.
Step-by-Step Solution:
main:x = new X() → A1 referenced by x.m1: returns new X → A2 referenced by x2 after line 6.main: x4 = new X() → A3 referenced by x4.Line 8: x2 = x4 makes x2 point to A3, leaving A2 unreferenced → A2 eligible. A1 and A3 remain referenced.Verification / Alternative check:Printing System.identityHashCode of the three references reveals the handoff: A2 disappears from reachability after line 8.
Why Other Options Are Wrong:0 ignores A2; 2 or 3 would require additional reference drops; doComplexStuff() executes later and does not affect the count at line 8.
Common Pitfalls:Forgetting that the parameter reassignment in m1 doesn’t affect the caller’s original x.
Final Answer:1