Taken from the official Java tutorial by Oracle, see question 2 here (boilerplate by me).
public static void main(String[] args) {
String[] students = new String[10];
String studentName = "Peter Smith";
students[0] = studentName;
studentName = null;
System.out.println(students[0]);
}
The answer says that studentName
is not eligible for garbage collection since the array students
still references it. However, the final line prints "Peter Smith", so to me it seems wrong that students[0]
references studentName
. Can someone please explain this?
I would like to explain with the help of diagrams step by step.
String studentName = "Peter Smith";
After first line, a String is created in the String pool and a reference name studentName is pointing towards it.
students[0] = studentName;
At this point, another reference students[0] is pointing to the same object as shown in the below diagram. Now 2 references are pointing to the same object created in memory.
studentName = null;
After this point, the reference of studentName will point to null i.e. it is pointing to no object. But reference of students[0] is still pointing to the String object (Peter Smith) created.
Clearly after the third statement, one reference is pointing to null but one reference is still pointing to the Object created. Therefore the object is not eligible for garbage collection.
Hope it helps.
Update : Sorry if I have messed up with the variable names. But I hope you get the idea.
You're confusing the referencing variables (studentName
and students[0]
) with the object that they reference ("Peter Smith"). studentName
and students[0]
both reference the String
object "Peter Smith". Once neither of them reference "Peter Smith"--and assuming that there are no other references elsewhere--that object will be eligible for garbage collection. The references themselves go away when they go out of scope.
The tutorial got it wrong. There is no object studentName
. studentName
is a variable that, at one point, holds a reference to "Peter Smith" and at another point is null
. Similarly, students[0]
is one element in an array of memory locations that holds a reference to "Peter Smith" (the same String
object). The tutorial confuses the idea of variables with the objects they reference.
I might speculate that they do this to avoid going into the details of memory usage. That's something of an advanced topic. But their explanation IMO causes more confusion than it prevents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With