Immutable type wrapper

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

Jon Skeet
people
quotationmark

If a type wrapper is immutable, why then is the value increased between line "1. inc" and "2. inc"

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 of nr will refer to a different object after nr++). Think of this:

nr++;

As instead:

int tmp = nr.intValue();
tmp++;
nr = Integer.valueOf(tmp);

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 that nr itself has taken on a new value, referring to a different object.

You can see that with more diagnostics, too:

static void inc(Integer nr)
{
    Integer original = nr;
    System.out.printf("1. inc() \t %d \n", nr);
    nr++;
    System.out.printf("2. inc() \t %d \n", nr);
    // This will print 10
    System.out.printf("Original: %d\n", original);
} 

and does line "b. main" print the same value as "1. main"?

The reference is passed by value, just as it always is. That means inc(nr1) doesn't modify nr1 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).

people

See more on this question at Stackoverflow