The 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:
byte
, short
or char
, it is promoted to an int
.int
, long
, float
or double
values.You need to be careful with relational comparisons that involve floating point numbers:
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.