Why doesn't assigning a "null" variable to a variable make it available to the GC? (In this piece of code)

I was going through the online tutorial provided by oracle. One of the exercises has the following question:


The following code creates one array and one string object. How many references to these objects exist after the code is executed? Is either an 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 an array of students and this array has one reference to a Peter Smith string. None of the objects are 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? Actually I am confused and I think it means that I did not understand the nature of "null" and also am referring to the object correctly, which is why I am asking.

+3


source to share


3 answers


Before assigning null

to studentName

there are two references to "Peter Smith" ( studentName

and students[0]

). After the null

studentName is assigned, "Peter Smith" still refers tostudents[0]



+10


source


What are the really objects that cannot be garbage collected? "Peter Smith" and String Array [10]. Note that these are the objects themselves, not object references! It is enough that there is only one link to avoid garbage collection.

I am using a mental trick that needs to be verbose when reading the code. It's easy to say "String" (undefined) when you mean "String object" (words in a String) or "String reference" (a variable that points to words), so this trick avoids this confusion.

Rewriting pseudocode with my mental trick, designating everything as an object or a reference, as I do in my head:



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;

      

On line 3, the String [0] reference was pointed to the "Peter Smith" object. It is now clear that only the studentName reference has been set to zero, but the "Peter Smith" object continues to exist and the array still points to it. So objects are not always zero, only one link has been canceled.

+1


source


This page describes well the basic concept of Java references (and how they are basically pointers)

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

Although not about the question, it has a lot to do with it. Objects are referenced by pointers (links) in java. Understanding this should help.

+1


source







All Articles