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; String studentName = "Peter Parker"; students = studentName; studentName = null; ...
My answer was studentName is eligible for garbage Collection.But the answer given was both are not eligible.What I thought was students refers to the String "Peter Parker" and studentName also does the same.Now that studentName refers to null, students remains referring to "Peter Parker" ( I checked this by printing it out).The explanation given was students is still referring to studentName so studentName is also not eligible for garbage Collection.But I'm not understanding this that since studentName now refers to null and students refers to "Peter Parker".Is my understanding wrong?
studentName = null; is executed,
students both hold references to the same
String object (whose value is
"Peter Parker"). When you assign
students still refers to that object, so it can't be garbage collected.
Java doesn't garbage collect reference variables, it garbage collects the objects that were referenced by these variables once there are no more references to them.