Consider the following example:
class Wrapper { int n; public Wrapper(int k) { n = k; } public String toString() { return ""+n;} public static Wrapper valueOf(int k) { return new Wrapper(k); } }
Now replace the Integer in your code with the Wrapper class above:
private static void changeInteger(Wrapper x) { x = Wapper.valueOf(5); } public static void main(String[] args) { Wrapper x = Wrapper.valueOf(0); changeInteger(x); System.out.println(x); }
Since you mentioned that you know about passing by value, I hope it is clear why this code does what it does.
Now back to your code. Under the hood, this is exactly the same code. The only difference is that you are not calling Wrapper.valueOf : the compiler does this for you through autoboxing. Once you realize that this is what is happening, the problem should be clear to you.
ByteCode changeInteger() to show that Integer.valueOf() is being called:
private static void changeInteger(java.lang.Integer); Code: Stack=1, Locals=1, Args_size=1 0: iconst_5 1: invokestatic #16;
dasblinkenlight
source share