Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this String is not eligible for garbage collection?

Tags:

java

string

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;
...

My answer was studentName is eligible for garbage Collection.But the answer given was both are not eligible.What I thought was students[0] refers to the String "Peter Parker" and studentName also does the same.Now that studentName refers to null, students[0] remains referring to "Peter Parker" ( I checked this by printing it out).The explanation given was students[0] 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[0] refers to "Peter Parker".Is my understanding wrong?

like image 635
getsuga Avatar asked Sep 08 '16 06:09

getsuga


2 Answers

Before studentName = null; is executed, studentName and students[0] both hold references to the same String object (whose value is "Peter Parker"). When you assign null to studentName, students[0] 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.

like image 61
Eran Avatar answered Sep 21 '22 18:09

Eran


Here String object is created with "Peter Parker" and studentName is just referring it. Java will garbage collecting those object who are lost and have no reference , here you are confused with reference studentName. by assigning null to studentName you are just removing one reference of "Peter Parker"; but it still refer by array element , so it will not garbage collected.

like image 23
Jekin Kalariya Avatar answered Sep 20 '22 18:09

Jekin Kalariya