Give the following code:
class A {
Boolean b;
A easyMethod(A a){
a = null;
return a;
}
public static void main(String [] args
First of all the interviewer is wrong about the Boolean -- there is no such object created by this code so there's nothing to be garbage collected.
It is incorrect to speak of variables like b
and a2
as being garbage collected. Objects are garbage-collected, not variables. If an in-scope variable references an object, then it cannot be garbage-collected. Simplistically, it's only when an an object is no longer referenced by any variable that it can be garbage collected.
So we have three instances of A being created in this code. They start out referenced by a1
etc. but since variable references change I'll refer to the object instances as A1, A2, and A3. Since you haven't shown a definition of the go
method I'm going to assume it's meant to be a call to easyMethod
.
Since the variable a1 is reassigned to null, nothing is pointing to instance A1, so it can be garbage-collected.
Since the variable a2 is never reassigned (the assignment in easyMethod
does not affect the original variable), instance A2 cannot be garbage-collected.
Since easyMethod
always returns null
and a3 is assigned the result of that method, nothing is pointing to instance A3, so it can also be garbage-collected.