Why is this line not suitable for garbage collection?

The following code creates one array and one string object. How many references to these objects exist after code execution? Is it the right to collect garbage?

... String[] students = new String[10]; String studentName = "Peter Parker"; students[0] = studentName; studentName = null; ... 

My answer was studentName has the right to garbage collection. But the answer that was indicated does not meet the requirements. What I thought students [0] refer to String "Peter Parker", and studentName also does the same. Now this is studentName to null, students [0] still refer to "Peter Parker" (I checked this by printing it). The explanation given to students [0] still refers to studentName, so studentName is also not allowed to collect garbage. m not understanding this, since studentName now refers to null, and students [0] refer to "Peter Parker". I understand what is wrong?

+7
java string
source share
3 answers

Before studentName = null; executed, studentName and students[0] keep references to the same String object (whose value is "Peter Parker" ). When you assign null to studentName , students[0] still refers to this object, so it cannot be garbage collected.

Java does not garbage collect reference variables; it garbage collects objects referenced by these variables when there are no more references to them.

+6
source share

Here the String object is created using "Peter Parker" and studentName simply referring to it. Java will garbage collect the object that is lost and do not have a link, here you are confused with a studentName link. by setting null to studentName , you simply delete one link "Peter Parker" ; but it still refers to the element of the array, so it will not collect garbage.

+3
source share

How many objects do you have?

You have two objects:

  • String "Peter Parker"
  • Array of strings.

How many links are / were for these objects?

There were three links:

  • The studentName variable refers to a string object.
  • The students variable refers to an array object.
  • The first position of the students[0] array object also refers to the string object.

How many references to these objects exist after code execution?

After executing this line:

 studentName = null; 

Only the first of three links is deleted. We still have two links.

Is it the right to collect garbage?

No , because:

  • The array object still refers to the students variable.
  • The string object "Peter Parker" still refers to the first position of the array object, students[0] .

Since both objects are still mentioned somewhere, neither of them has the right to garbage collection.


PS: I used the general concepts of "string" and "array" for objects, so it’s easier to mentally separate them from the actual variables String and String [] in the code.

+3
source share

All Articles