Littering and garbage collection logic

public String pop()
{ 
    String item = a[--N];
    a[N] = null; // Avoid littering 
    return item;
}

In the code above N decrements first and then indexes into array a. My question is, if item was assigned the value indexed at N-1 first, why bother making a[N] null when there was already nothing there at a[N]?

Kindly correct me where I am wrong in my logic in understanding this.


N is now, at that point in the code, the value that used to be N-1.


The code in question:

public String pop()
{ 
    String item = a[--N];
    a[N] = null; // Avoid littering 
    return item;
}

is equivalent to:

public String pop()
{ 
    N = N - 1;
    String item = a[N];
    a[N] = null; // Avoid littering 
    return item;
}

After the second line of this method is executed, both item and a[N] are references to the same object. By assigning null to a[N], you remove one of those references, and because the item is created on the stack, it is removed after the method returns. This way the only reference to the object is returned by the method. So if the caller don't assing this reference to some variable (or this reference is assgned, but somehow lost later), then there will be no references to this object anymore, and the GC will have a green light to remove the object from the memory.