The string object above called studentname should be garbage collected now since it
points to null. however the answer book on the above says neither objects will be garbage
collected. do you know what is really happening???
studentName is itself not an object, it is a reference to one. Setting it to null simply means it does not refer to any object. I think the important concept to grasp is that objects are garbage collected, not references to objects.
M Zia wrote:James,
The "String studentname" is not an object in this case and will not be garbage collected
after setting it to null??
studentname is not an object - it is a reference variable. Reference variables are never garbage collected - only objects can be garbage collected and this happens when there are no longer any references to them.
Setting a reference variable to null means that it no longer references an object and that object may be eligible for garbage collection if there are no other references to it.
Thanks for replying so fast. I really appreciate it.
So in the above code, "students" refers to an array of 10 String objects.
When and if we set the "students" reference to null by setting students = null,
then the array of 10 String objects will be garbage collected?? or do we
have to set every member of the array to null in a for loop??
If the array reference is set to null, and there are no other references to any of its elements, then those 11 objects are eligible for garbage collection. If it is a small application, it will not be collected as garbage because the JVM will terminate before there is any need for garbage collection.
M Zia wrote:So in the above code, "students" refers to an array of 10 String objects.
To be precise it is an array of 10 String references, only one of which currently refers to a String object.
Campbell Ritchie wrote:If the array reference is set to null, and there are no other references to any of its elements, then those 11 objects are eligible for garbage collection.
Assuming the array elements refer to objects. In this case only one of them does and as that object is a String literal it wont ever be garbage collected. So only the array object itself would be eligible for garbage collection.