What does the ++ operator do to an Integer? [duplicate]

  • A+
Category:Languages

This question already has an answer here:

Following test case will pass:

@Test public void assignWrapperTest() {     System.out.printf("/nassign - %s/n", "wrapper");      Integer a = 1000;     Integer b = a;     System.out.printf("a = %d, b = %d/n", a, b);     Assert.assertEquals(a, b);     Assert.assertSame(a, b); // a, b are the same object,      a++;     System.out.printf("a = %d, b = %d/n", a, b);     Assert.assertNotEquals(a, b);     Assert.assertNotSame(a, b); // a, b are not the same object, any more, } 

So:

  • a is changed by ++.
  • b remains the same.

The questions are:

  • b = a just assign the reference value right, they refer to the same object, at this point there is only one object, right?
  • What ++ operator does on an Integer?
    Since Integer is immutable, does this means ++ created a new Integer object, and assigned it back to the original variable automatically? If that's the case, does that means a now point to a different object?
  • There are 2 objects now? And b still point to the original one ?

 


a++; 

Because a is an Integer, this is the same as:

a = Integer.valueOf(a.intValue() + 1); 

does this means ++ created a new Integer object

Maybe, but not necessarily: Integer.valueOf will reuse a cached value; a new value will only be created if outside the cached range (which is at least -128..127).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: