The following code creates one array and one string object.
Now my questions are
Here is my code
String[] students = new String[10];
String studentName = "Peter Smith";
students[0] = studentName;
studentName = null;
I was thinking the answer is only one object i.e. students
But according to Oracle docs, Neither object is eligible for garbage collection
How should I infer the answer?
How many references to those objects exist after the code executes?
String[]
, obtainable through the expression students
.String
, obtainable through the expression students[0]
.Why?
Essentially, the answer is that objects, not variables, can ever be eligible for garbage collection.
In your case, you have copied a reference of the string (which is an object) into the first slot of the array. Even after you clear (set to null
) the initial variable, that same object is still visible from your code, by another name (and by "name" here I mean "expression", as described above). This is why the string is still not eligible 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 scenario, the string "Peter Smith"
would indeed be eligible for garbage collection as you'd expect, because it's not obtainable anymore by any expression.
(All the above concern the Java language and leave any possible JVM optimizations aside.)
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