This line of code in the modify
method:
i= i + 1;
is operating on an Integer
, not an int
. It does the following:
- unbox
i
to an int value
- add 1 to that value
- box the result into another
Integer
object
- assign the resulting
Integer
to i
(thus changing what object i
references)
Since object references are passed by value, the action taken in the modify
method does not change the variable that was used as an argument in the call to modify
. Thus the main routine will still print 12
after the method returns.
If you wanted to change the object itself, you would have to pass a mutable object (as others have mentioned, Integer
is immutable) and you would have to call a mutator method or directly modify a field. For instance:
class Demo{
static class IntHolder {
private int value;
public IntHolder(int i) {
value = i;
}
public IntHolder add(int i) {
value += i;
return this;
}
public String toString() {
return String.valueOf(value);
}
}
public static void main(String[] args) {
IntHolder i = new IntHolder(12);
System.out.println(i);
modify(i);
System.out.println(i);
}
private static void modify(IntHolder i) {
i.add(1);
System.out.println(i);
}
}