Java Language Operators The Relational Operators (<, <=, >, >=)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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:

  1. If one of the operands is a boxed type, it is unboxed.
  2. If either of the operands now a byte, short or char, it is promoted to an int.
  3. If the types of the operands are not the same, then the operand with the "smaller" type is promoted to the "larger" type.
  4. The comparison is performed on the resulting int, long, float or double 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.



Got any Java Language Question?