Reputation: 8601
Consider the following snippet:
Integer Foo = 2;
int foo = 1;
boolean b = Foo < foo;
is <
done using int
or Integer
? What about ==
?
Upvotes: 1
Views: 220
Reputation: 727077
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.
Upvotes: 3
Reputation: 84
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.
Upvotes: 0
Reputation: 234875
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
.
Upvotes: 4