I have a simple code snippet to test "Immutable" integer like below:
public static void changeInteger(Integer i) {
i;
}
public static void main(String[] args) {
Integer i = new Integer(3);
i;
System.out.println(i); // 4
ImmutableWrapper.changeInteger(i);
System.out.println(i); // still 4!
}
I could see as Java language design, a wrapper class Integer
is immutable when passed as function parameter.
What confused me is, why the ```` i``` inside main() will increase the value, while passing into function, doesn't change?
I wonder how does Java compiler or JVM achieve this? I know that Integer
is a reference type, so when passed as parameter, an reference is passed, and then i will change its wrapped value?
Wish technical explanation.
CodePudding user response:
Autoboxing and unboxing is the automatic conversion that compiler helps us to converse between the primitive types and wrapper classes.
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.1 says:
If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable after the new value is stored
So, i
equals to i = Integer.valueOf(i.intValue() 1)