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
It is.
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:
...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
orlong
that uniquely identifies the object elsewhere in memory. (Which is basically what it is.) Just asa = b
withint
s copiesb
's value intoa
, soa = b
copiesb
's value intoa
even when the value is an object reference. The value being copied is the reference, not the object it refers to.