0

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
letter Q
  • 14,735
  • 33
  • 79
  • 118

1 Answers1

2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @QLiu: No worries. :-) BTW, swearing is a no-no on SO. – T.J. Crowder Jun 23 '15 at 18:28
  • So I get that Java is pass by value where the value can be a reference, but internally how is that different than in C where you pass by reference with & internally? – letter Q Jun 24 '15 at 16:05
  • @QLiu: C doesn't have pass-by-reference. C++ does. The difference is what the reference is to: In C++, if we have `foo(int &bar)` and we call it using `foo(x)`, inside `foo`, `bar` is a reference to the **variable** `x`. So `foo` can reach out and change the variable. That has nothing to do with object references, it's about *variable* references. Java doesn't have variable references. – T.J. Crowder Jun 24 '15 at 16:47