1

I have been going through the Java tutorials on the Java website and have been left confused with an answer they gave to a question.

The question is as follows: "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 Smith";
students[0] = studentName;
studentName = null;

Answer: "There is one reference to the students array and that array has one reference to the string Peter Smith. Neither object is eligible for garbage collection."

Why is studentName not eligible for garbage collection? Nothing is pointing to studentName, and it's value is null.

1
  • 2
    Objects are garbage collected, not variables. Commented Aug 25, 2014 at 20:26

3 Answers 3

4

studentName is a variable not an object - you garbage collect only objects.
The only objects in here, as mentioned are the created String[] and "Peter Smith", and both are reachable, and thus not eligable for GC.

Sign up to request clarification or add additional context in comments.

Comments

0

studentName is reference to Object not an actual Object,

If you mean Object referred by studentName

String studentName = "Peter Smith";

then it is still being referred by students[0]

students[0] = studentName;

Comments

-1

If you look at the documentation on that site it says the following in the summary page:

"The garbage collector automatically cleans up unused objects. An object is unused if the program holds no more references to it. You can explicitly drop a reference by setting the variable holding the reference to null."

Even though the reference to "Peter Smith" is released by studentName when it is set to null, the string array students still has a reference to that object so it's not eligible for garbage collection. The array itself also still has a reference to it. If you put this in a small program and run it and print out students[0] after this code block it will print "Peter Smith"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.