I'm confused about Type wrappers being immutable when executing following code
static void inc(Integer nr)
{
System.out.printf("1. inc() \t %d \n", nr);
nr++;
System.out.printf("2. inc() \t %d \n", nr);
} // inc()
public static void main(String[] args)
{
Integer nr1 = 10;
System.out.printf("a. main() \t %d \n", nr1);
inc(nr1);
System.out.printf("b. main() \t %d \n", nr1);
} // main()
Executing it creates following output
a. main() 10
1. inc() 10
2. inc() 11
b. main() 10
If a type wrapper is immutable, why then is the value increased between line "1. inc" and "2. inc" and does line "b. main" print the same value as "1. main"?
thank you
Chris
Because you're not actually mutating the existing
Integer
object - you're creating a new one (well, effectively - actually it'll use common cached objects, but the point is that the value ofnr
will refer to a different object afternr++
). Think of this:As instead:
So the fact that you see the text representation of
nr
changing doesn't mean that the object it refers to has mutated - in this case, the cause is thatnr
itself has taken on a new value, referring to a different object.You can see that with more diagnostics, too:
The reference is passed by value, just as it always is. That means
inc(nr1)
doesn't modifynr1
at all - it refers to the same object it did before. As I said above,inc
also doesn't modify the object (because the wrapper types are immutable). Therefore after the call,nr1
refers to the same object wrapping the same value (10).