The Relational Operators
suggest changeThe operators \<
, <=
, \>
and >=
are binary operators for comparing numeric types. The meaning of the operators is as you would expect. For example, if a
and b
are declared as any of byte
, short
, char
, int
, long
, float
, double
or the corresponding boxed types:
- `a < b` tests if the value of `a` is less than the value of `b`.
- `a <= b` tests if the value of `a` is less than or equal to the value of `b`.
- `a > b` tests if the value of `a` is greater than the value of `b`.
- `a >= b` tests if the value of `a` is greater than or equal to the value of `b`.
The result type for these operators is boolean
in all cases.
Relational operators can be used to compare numbers with different types. For example:
int i = 1;
long l = 2;
if (i < l) {
System.out.println("i is smaller");
}
Relational operators can be used when either or both numbers are instances of boxed numeric types. For example:
Integer i = 1; // 1 is autoboxed to an Integer
Integer j = 2; // 2 is autoboxed to an Integer
if (i < j) {
System.out.println("i is smaller");
}
The precise behavior is summarized as follows:
- If one of the operands is a boxed type, it is unboxed.
- If either of the operands now a
byte
,short
orchar
, it is promoted to anint
. - If the types of the operands are not the same, then the operand with the “smaller” type is promoted to the “larger” type.
- The comparison is performed on the resulting
int
,long
,float
ordouble
values.
You need to be careful with relational comparisons that involve floating point numbers:
- Expressions that compute floating point numbers often incur rounding errors due to the fact that the computer floating-point representations have limited precision.
- When comparing an integer type and a floating point type, the conversion of the integer to floating point can also lead to rounding errors.
Finally, Java does bit support the use of relational operators with any types other than the ones listed above. For example, you cannot use these operators to compare strings, arrays of numbers, and so on.