Consider the following snippet:
Integer Foo = 2;
int foo = 1;
boolean b = Foo < foo;
is <
done using int
or Integer
? What about ==
?
Consider the following snippet:
Integer Foo = 2;
int foo = 1;
boolean b = Foo < foo;
is <
done using int
or Integer
? What about ==
?
For all the relational operators (including therefore <
and ==
), if one type is the boxed analogue of the other, then the boxed type is converted to the unboxed form.
So your code is equivalent to Foo.intValue() < foo;
. This is deeper than you might think: your Foo < foo
will throw a NullPointerException
if Foo
is null
.
According to JLS, 15.20.1
The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2).
Further, 5.6.2 states that
If any operand is of a reference type, it is subjected to unboxing conversion
This explains what is happening in your program: the Integer
object is unboxed before the comparison is performed.
They will be done using int
due to Autoboxing and Unboxing.
The Wrapper types for primitive types in java does automatic "type casting" ( or autoboxing / unboxing) from Object to compatible primitive type. so Integer will be converted to int before passing it to comparison operators or arithmetic operators like < , > , == , = , + and - etc.