The Relational Operators

suggest change

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:

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Operators:
* The Relational Operators

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
39 Operators
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap