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 Parker";
-
students[0] = studentName;
-
studentName = null;
-
...
-
Answer 2: There is one reference to the students array and that array has one reference to the string Peter Parker. Neither object is eligible for garbage collection.
Q:- A program can set all references to an object to null so that it becomes eligible for garbage collection. Right?....But here we have set studentName to 'null' then why in answer its written "Neither object is eligible for garbage collection. "????
After execution of line #1 the students reference points to an array of ten String
references. Those references don't point to anything yet.
After execution of line #2 the studentName reference points to string "Peter Parker".
After execution of line #3 the first reference in the array also points to that same
string.
After execution of line #4 studentName doesn't point to anything anymore.
So at the end 'students' points to an array of ten references; all of them are null
except for the first one: it points to a String "Peter Parker".
kind regards,
Jos