Say we have two Integer objects:
Integer i=100,j=200;
Does (j-i) evaluate to another Integer Wrapper object with value 100, or a primitive int?
Quick test shows that java is using an Integer cache, and re-uses the i:
@Test
public void test() {
Integer i=100, j=200;
System.out.println("i: " + System.identityHashCode(i));
System.out.println("j: " + System.identityHashCode(j));
Integer sub = j-i;
System.out.println("j-i: " + System.identityHashCode(sub));
}
Outputs:
i: 1494824825
j: 109647522
j-i: 1494824825 <-- same as i
The result will be an int 100.
Both i and j will be auto-unboxed so the result of i-j will be an int.
But if you assign the result to as follows:
Integer r = i - j;
then the result will be auto-boxed again.
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