1
votes

I have been going through the Java tutorials on the Java website and have been left confused with an answer they gave to a question.

The question is as follows: "The following code creates one array and one string object. How many references to those objects exist after the code executes? Is either object eligible for garbage collection?"

String[] students = new String[10];
String studentName = "Peter Smith";
students[0] = studentName;
studentName = null;

Answer: "There is one reference to the students array and that array has one reference to the string Peter Smith. Neither object is eligible for garbage collection."

Why is studentName not eligible for garbage collection? Nothing is pointing to studentName, and it's value is null.

3
Objects are garbage collected, not variables. - Oliver Charlesworth

3 Answers

4
votes

studentName is a variable not an object - you garbage collect only objects.
The only objects in here, as mentioned are the created String[] and "Peter Smith", and both are reachable, and thus not eligable for GC.

0
votes

studentName is reference to Object not an actual Object,

If you mean Object referred by studentName

String studentName = "Peter Smith";

then it is still being referred by students[0]

students[0] = studentName;
-1
votes

If you look at the documentation on that site it says the following in the summary page:

"The garbage collector automatically cleans up unused objects. An object is unused if the program holds no more references to it. You can explicitly drop a reference by setting the variable holding the reference to null."

Even though the reference to "Peter Smith" is released by studentName when it is set to null, the string array students still has a reference to that object so it's not eligible for garbage collection. The array itself also still has a reference to it. If you put this in a small program and run it and print out students[0] after this code block it will print "Peter Smith"