How many references to these objects exist after code execution?
- One reference to
String[] , which can be obtained through the students expression. - One reference to
String , which can be obtained through the expression students[0] .
Why?
Essentially, the answer is that objects, not variables , may have the right to garbage collection.
In your case, you copied the link of the string (which is the object) into the first slot of the array. Even after you clear (set to null ) the initial variable, the same object is still displayed from your code with a different name (and by βnameβ here I mean βexpressionβ, as described above). This is why the string is still not suitable for garbage collection.
For comparison, consider your code without the third line:
String[] students = new String[10]; String studentName = "Peter Smith"; studentName = null;
In this case, the string "Peter Smith" really has the right to collect garbage, as one would expect, because it can no longer be received by any expression.
(All of the above refers to the Java language and leaves any possible JVM optimizations aside.)
source share