Keir Simmons
Keir Simmons

Reputation: 1684

Java Garbage Collection with Assignment of Variables

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.

Upvotes: 1

Views: 431

Answers (3)

cherylcourt
cherylcourt

Reputation: 195

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"

Upvotes: -1

amit
amit

Reputation: 178451

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.

Upvotes: 4

Jigar Joshi
Jigar Joshi

Reputation: 240900

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;

Upvotes: 0

Related Questions