1

Consider the following snippet:

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

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

2

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

2

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

1 Comment

This is also a useful resource stackoverflow.com/questions/27647407/…
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.