Difficulty: Medium
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:
x
in main, one in m1
, and one for x4
in main.x2
is reassigned to refer to x4
.
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:
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
Discussion & Comments