I got a question really confuses me,
After running Line 8 of the following code, which 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;
}
}
A.x
B.x and x2
C.x and x4
D.x4
My initial thought was only x2 is garbage collected because it is deferenced at line 8 when x2 = x4, and since java is pass by value, so X x2 = m1(x) won't affect x.
I've also found the exact same question (but different choices) here https://www.indiabix.com/java-programming/garbage-collections/discussion-202, and some comments saying x also should be garbage collected as well, which are contradictory to my thought, now I'm confused which choice to the question is correct, thanks in advance.