Difficulty: Medium
Correct Answer: Garbage collector is not invoked within methodA() because returned references keep objects reachable.
Explanation:
Introduction / Context:
GC questions often trick you into thinking that setting a local to null frees an object. In reality, reachability from any root keeps the object alive, including references inside arrays that are still in use (or returned).
Given Data / Assumptions:
obj1
references a new Object.obj2
is an array that stores that same reference at index 0 and the method returns obj2[0]
.
Concept / Approach:
Because methodA
returns a reference to the original object via the array element, that object remains reachable when control returns to main
. The local variable obj1
becoming null is irrelevant if another reference (inside obj2
) is returned. The array itself becomes eligible only if it is not returned; here, we do not return the array, only the element value, so the array is eligible upon method exit, not before.
Step-by-Step Reasoning:
obj2[0]
holds the object reference.Line 12: obj1 = null
drops one reference but the array still holds it.Line 13: returning obj2[0]
passes the reference to the caller, so the object remains reachable.
Verification / Alternative check:
If the method returned null
instead, then the array and object could become eligible on return if no other references exist.
Why Other Options Are Wrong:
Options A–C ignore continuing reachability; Option E wrongly assumes nulling a local frees the object.
Common Pitfalls:
Equating local scope end or nulling a local with object death; forgetting that returning a reference prolongs object lifetime.
Final Answer:
Garbage collector is not invoked within methodA() because returned references keep objects reachable.
Discussion & Comments