I don't understand how Java is pass by value

73 views Asked by At

So I thought Java was pass by value but why does the following code:

public static void main(String[] args) {

    List<Integer> numbers = new ArrayList<Integer>();
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);

    phase1(numbers);

    for (Integer number: numbers) {
        System.out.println("number = " + number);
    }
}

static void phase1(List<Integer> numbers) {
    numbers.remove(0);
}

Print the following?

number = 2
number = 3
1

There are 1 answers

3
T.J. Crowder On BEST ANSWER

So I thought Java was pass by value

It is.

...but why does the following code...print the following?

Because the value passed for reference types is the reference, not a copy of the object.

"Pass by reference" refers to a completely different thing, passing a reference to the variable. Java doesn't have that.

If Java had pass-by-reference, then this change to your method:

static void phase1(List<Integer> &numbers) {
// Pass-by-reference indicator --^--- that Java doesn't actually have
    numbers = new ArrayList<Integer>()
}

...would make your code print no numbers at all. But it doesn't, so it doesn't.

Think of the object reference as an int or long that uniquely identifies the object elsewhere in memory. (Which is basically what it is.) Just as a = b with ints copies b's value into a, so a = b copies b's value into a even when the value is an object reference. The value being copied is the reference, not the object it refers to.