The following code compiles (with Java 8):
Integer i1 = 1000;
int i2 = 1000;
boolean compared = (i1 == i2);
But what does it do?
Unbox i1
:
boolean compared = (i1.intvalue() == i2);
or box i2
:
boolean compared = (i1 == new Integer(i2));
So does it compare two Integer
objects (by reference) or two int
variables by value?
Note that for some numbers the reference comparison will yield the correct result because the Integer class maintains an internal cache of values between -128
to 127
(see also the comment by TheLostMind). This is why I used 1000
in my example and why I specifically ask about the unboxing/boxing and not about the result of the comparison.
Integer
class maintains an internal cache of values between-128 to 127
. So even if you comparedInteger i1=100
withInteger i2=100
using==
, you will gettrue
. You will getfalse
when bothi1
andi2
are not in that local cache range – Phalanstery