I was going through the online tutorial provided by oracle. One of the exercises has a question 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.
(http://docs.oracle.com/javase/tutorial/java/javaOO/QandE/objects-answers.html)
Surely the last line means studentName is eligible for GC? Really confused, and I think this means I have not understood the nature of "null" and also object referencing properly, which is why I ask.
Before assigning null to studentName there are two references to "Peter Smith" (studentName and students[0]). After null is assigned to studentName, "Peter Smith" is still referenced by students[0]
What are the objects, actually, that cannot be garbage collected? "Peter Smith" and the String[10] array. Note these are the objects themselves, not the references to the objects! It is enough that just one reference exists to avoid garbage collection.
I use a mental trick which is to be verbose while reading code. It is easy to say "String" (vague) when what you mean is "String object" (the words in the String) or "String reference" (the variable pointing to the words) so this trick avoids this confusion.
Rewriting the pseudocode with my mental trick, labeling everything as object or reference the way I do in my mind:
1 String[] OBJECT student REFERENCE = new String[10] OBJECT;
2 String OBJECT studentName REFERENCE = "Peter Smith" OBJECT;
3 students[0] REFERENCE = studentName REFERENCE;
4 studentName REFERENCE = null;
In line 3 the String[0]_reference was pointed at the "Peter Smith" object. It is now clear that just the studentName reference was set to null but the "Peter Smith" object continues to exist and the array still points to it. Thus the objects aren't ever null, just one reference was nulled.
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