Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does subtracting two Integer objects result in an Integer or a primitive int?

Tags:

java

wrapper

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?

like image 735
aps Avatar asked Oct 26 '25 13:10

aps


2 Answers

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
like image 128
Sean Adkinson Avatar answered Oct 29 '25 11:10

Sean Adkinson


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.

like image 38
Bhesh Gurung Avatar answered Oct 29 '25 12:10

Bhesh Gurung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!