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?++ 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?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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With