Difficulty: Medium
Correct Answer: 2
Explanation:
Introduction / Context:
Java's garbage collector can reclaim cycles, because it is based on reachability from GC roots. Two objects that reference each other but are not reachable from roots are still eligible for collection.
Given Data / Assumptions:
x2
and x3
initially reference two different objects (A and B).x2
is assigned to a new object C, and x3
is set to refer to x2
(thus both locals now point to C).
Concept / Approach:
After line 11, there are no live references from GC roots to A or B. Mutual references between A and B do not prevent collection.
Step-by-Step Solution:
x2 = new X2()
creates C; local x2
points to C, but B still points to A and A to B.Line 11: x3 = x2
makes both locals point to C; neither A nor B is referenced from any root.Therefore, A and B are both eligible: count = 2.
Verification / Alternative check:
A mark-and-sweep collector marks only objects reachable from roots; A and B will not be marked and then will be swept.
Why Other Options Are Wrong:
0 or 1 ignores that both A and B lost root reachability; 3 would require yet another unreferenced object.
Common Pitfalls:
Mistaken belief that cycles are never collected (true for simple reference counting, but not for Java's tracing GC).
Final Answer:
2
Discussion & Comments