Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?
like image 250
user218867 Avatar asked Dec 17 '18 10:12

user218867


2 Answers

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).

like image 139
Andy Turner Avatar answered Oct 24 '22 12:10

Andy Turner


If we look at the Byte code of a++; It looks something like below:

    9: aload_1
   10: invokevirtual #22                 // Method java/lang/Integer.intValue:()I
   13: iconst_1
   14: iadd
   15: invokestatic  #16                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   18: astore_1

So the instructions are like getting the intValue() of a then increment it then call Integer#valueOf on the incremented value and Integer#valueOf create a new object.

like image 39
Amit Bera Avatar answered Oct 24 '22 13:10

Amit Bera