java - Immutable type wrapper -


this question has answer here:

i'm confused 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 creates following output

  a. main()     10    1. inc()      10    2. inc()      11    b. main()     10  

if type wrapper immutable, why value increased between line "1. inc" , "2. inc" , line "b. main" print same value "1. main"?

thank you

chris

if type wrapper immutable, why value increased between line "1. inc" , "2. inc"

because you're not mutating existing integer object - you're creating new 1 (well, - it'll use common cached objects, point value of nr refer different object after nr++). think of this:

nr++; 

as instead:

int tmp = nr.intvalue(); tmp++; nr = integer.valueof(tmp); 

so fact see text representation of nr changing doesn't mean object refers has mutated - in case, cause nr has taken on new value, referring different object.

you can see 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);     // print 10     system.out.printf("original: %d\n", original); }  

and line "b. main" print same value "1. main"?

the reference passed value, is. means inc(nr1) doesn't modify nr1 @ - refers same object did before. said above, inc also doesn't modify object (because wrapper types immutable). therefore after call, nr1 refers same object wrapping same value (10).


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -