Anda Cristea wrote:
Q: Why c2 is not eligible for garbage collection?
A: after the call of method go(), c2 become null.
"null" and "no reachable reference to" are not synonymous.
An object, regardless of content--null or otherwise--is garbage collected when "the object is no longer reachable" (no references pointing to it and/or references are out-of-scope).
Think of an object like a glass of water: glassOfWater = null; just empties the glass of water; it doesn't throw the glass away or make the glass unusable. "null" is analogous to "empty", not "non-existent".
In addition to OP's answer, it is worth to mention, that cb reference variable isn't just different from c2 reference variable, it is a copy of c2. While these both reference variables refering to the same object, references are different, and once you re-assign cb to something else, you lose the link with the object c2 is refering to, but it has no effect for c2 reference variable.
Anda Cristea wrote:Why c2 is not eligible for garbage collection?
First of all, you shouldalwaysQuoteYourSources when you are posting a code snippet. Secondly when you post such a code snippet, you should not change the class name(s). And the reason why is pretty simple: using the class name of a code snippet ranchers can easily search (using the excellent search function) for topics about the same code snippet they have doubts/questions about. If you change the class name to something different, they might miss out on valuable information.
In this topic you'll find an excellent explanation (with additional code snippets) about exactly the same code snippet. Definitely worth reading!