Below is my code:
class Demo{
public static void main(String[] args) {
Integer i = new Integer(12);
System.out.println(i);
modify(i);
System.out.println(i);
}
private static void modify(Integer i) {
i= i + 1;
System.out.println(i);
}
}
The OUTPUT of the above CODE is
12
12
but as I know, we are passing the wrapper object "i", it means it should be "Call by reference",Then the value should change to 13.but its 12.
Any one has proper explanation for this?
解决方案
References are passed by value, and besides of that Integer is immutable.
When passing i to the method modify the value of the reference is passed (the reference is local to that method) and when you assign another object to it you only modify that local reference/variable holding the reference. The original remains unchanged.
Immutable means that an object once created / instantiated it not possible to change its state any more.