I have the following code:
class Test {
public static void main(String[] args) {
String a,b,c;
a = new String(args[0]);
b = a;
a = null;
b = null;
}
}
Can someone tell me when a will be eligible for garbage collection. I think it’s after b is made null because don’t a and b reference the same object ?
Pitching my answer too. As the other answers say, the String/ object is available for Garbage Collection once it is no longer accessible (you no longer have a handle to it).
So if you had a one-direction linked list…
[1] -> [2] -> [3]and you had a handle to[1](which has a handle to[2]and onwards). If you set your handle to[1]to null, you would put the entire list available to the Garbage collector. As this answer says, you are able to call System.gc() to request the Garbage Collector run, but it is not guaranteed that it will.I believe the main focus to this answer is that objects are available to the garbage collector when they are inaccessible and that does not necessarily mean that there are no references to it. In my above example, even though
[1]had a handle to[2],[2]was available for the garbage collector because there was no handle to[1].