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.
Explanation
When two primitive values are compared using == operator autoboxing does not take place.
When two objects are compared using == operator autoboxing plays role.
When mixed combination is used that is it contains an Object and primitive type and comparison is done using == operator unboxing happens on the Object and is converted to primitive type.
Please go through the below link which will help you get understand detailed about auto-boxing with suitable example.
Refer Link : http://javarevisited.blogspot.in/2012/07/auto-boxing-and-unboxing-in-java-be.html
It is defined in the JLS #15.21.1:
And JLS #5.6.2:
So to answer your question, the
Integer
is unboxed into anint
.Lets do some examples :
Case -1 :
Byte code :
Case -2 :
Bytecode :
So, in case of comparison of
Integer
andint
with==
theInteger
is unboxed to anint
and then comparison happens.In case of comparing 2
Integers
, the references of 2Integers
are compared.