I was wondering if java automatically turns a Integer into an int when comparing to an int? Or will the == try and compare references on primitives?
Is this always true or do I need to do i.intValue()==2
?
Integer i = Integer.valueOf(2);
if (i==2){
//always?
}
Yes, when comparing
int
using==
arguments will be unboxed if necessary.Relevant section from the Java Language Specification:
Same applies for
<
,<=
,>
,>=
etc, as well as+
,-
,*
and so on.So,
prints
true
:-)Right, and there is actually a similar situation for
Integers
as well.When boxing (transforming
int
toInteger
) the compiler uses a cache for small values (-128 - 127) and reuses the same objects for the same values, so perhaps a bit surprising, we have the following:yes, it's automatically converted. you can also do
Yes this works because auto (un)boxing.
Yes, it will unbox. This is covered in section 15.21.1 of the JLS (the numeric == operator):
(I've linkified section 5.1.8 as that's what talks about the conversion from
Integer
toint
being available.)It will compare primitives - the
Integer
will be unboxed. But as a rule of thumb: avoid that. Always prefer primitives, and be careful when comparing objects with==
Apart from seeing this in the JLS, here's how you can verify that:
Instead of
Integer.valueOf(2)
, which uses a cache, usenew Integer(2)
. This is guaranteed to be a different instance than the one that will be obtained if2
if boxed (the boxing happens withInteger.valueOf(..)
). In this case, the condition is still true, which means that it's not references that are compared.This is possible.
That Java-feature is called Autoboxing.