1

Consider the following snippet:

Integer Foo = 2;
int foo = 1;
boolean b = Foo < foo;

is < done using int or Integer? What about ==?

P45 Imminent
  • 8,319
  • 4
  • 35
  • 78
  • both are done using `int` – Iłya Bursov Mar 09 '16 at 22:27
  • 1
    Duplicate: http://stackoverflow.com/questions/3352791/why-comparing-integer-with-int-can-throw-nullpointerexception-in-java or http://stackoverflow.com/q/7672317/1743880. Even better http://stackoverflow.com/q/9150446/1743880. Also http://stackoverflow.com/questions/31572567/integer-vs-int-comparison – Tunaki Mar 09 '16 at 22:30

4 Answers4

4

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

They will be done using int due to Autoboxing and Unboxing.

Geralt_Encore
  • 3,721
  • 2
  • 31
  • 46
  • This is also a useful resource http://stackoverflow.com/questions/27647407/why-do-we-use-autoboxing-and-unboxing-in-java – Monroy Mar 09 '16 at 22:30
0

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.