When setting an array element to a String object, does the element reference the object?

Taken from the official Java tutorial by Oracle, see question 2 here (boilerplate by me).

public static void main(String[] args) {

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

    System.out.println(students[0]);

}

The answer says that studentName is not eligible for garbage collection since the array students still references it. However, the final line prints “Peter Smith”, so to me it seems wrong that students[0] references studentName. Can someone please explain this?

Answer

You’re confusing the referencing variables (studentName and students[0]) with the object that they reference (“Peter Smith”). studentName and students[0] both reference the String object “Peter Smith”. Once neither of them reference “Peter Smith”–and assuming that there are no other references elsewhere–that object will be eligible for garbage collection. The references themselves go away when they go out of scope.

The tutorial got it wrong. There is no object studentName. studentName is a variable that, at one point, holds a reference to “Peter Smith” and at another point is null. Similarly, students[0] is one element in an array of memory locations that holds a reference to “Peter Smith” (the same String object). The tutorial confuses the idea of variables with the objects they reference.

I might speculate that they do this to avoid going into the details of memory usage. That’s something of an advanced topic. But their explanation IMO causes more confusion than it prevents.

Leave a Reply

Your email address will not be published. Required fields are marked *