简体   繁体   中英

Java - why does assigning “null” to variable does not make it available for GC? (In this code snippet)

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.

This page explains the fundamental java concept of references well (and how they are essentially just pointers)

http://javadude.com/articles/passbyvalue.htm

Though not about the question, it is directly relevant. Objects are referenced by pointers (references) in java. Understanding that should help a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM