H.Rabiee
H.Rabiee

Reputation: 4837

Confusing Java allocation reference in constructor

Can someone please explain why the second output is not null? I understand that 999 is there because of reference value.

public class Set {

    int e[] = null;

    public Set(int[] e ) {
        this.e = e;
    }

    public void printSet() {
        for(int i = 0 ; i < e.length; i++) {
            System.out.println(e[i]);
        }
    }


    public static void main(String[] args) {
        int[] v = {1,2,3,4,5};

        Set m = new Set(v);
        m.printSet();

        v[0] = 999;
        v = null;

        System.out.println("-----------------");

        m.printSet();


    }

}

Output

1
2
3
4
5
-----------------
999
2
3
4
5

Upvotes: 0

Views: 56

Answers (3)

Ali Cheaito
Ali Cheaito

Reputation: 3846

First line in main(): int[] v = {1,2,3,4,5}; This of this as creating two entities:

  • One is an integer array containing the numbers 1 through 5
  • The second is a reference named v, that currently points to the after mentioned array

The you passed v to the Set class constructor:

Set m = new Set(v);

By doing this, you passed the location of the array to the constructor, who created a second reference to the same array object and called it e.

Then you nullified the v reference

v = null;

By doing so, you're telling Java that v should no longer point to the integer array object created earlier. That in itself, however, does not mean that the integer array will perish. It is still referenced by the Set.e reference. When that reference is nullified, then the array will become garbage collection eligible and would be removed from memory at some point.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201399

Because e still has a reference to the array, nulling the v reference does not render the array unreachable.

public Set(int[] e) {
    this.e = e; // <-- reference to the array
}

v[0] = 999;
v = null; // <-- now v doesn't refer to the array, but e still does.

Upvotes: 1

SLaks
SLaks

Reputation: 887215

v[0] = 999;

You just mutated an object which is referred to by both your local variable and the class instance.

v = null;

You just made the local variable refer to a new instance (or lack thereof).
The class instance field, which happens to refer to the previous value, is not affected.

Upvotes: 0

Related Questions