Java has six relational operators. Every one of them returns a boolean, never a value of the operand's own type, which is what makes them safe to drop straight into an if.
| Operator | Name | Meaning |
|---|---|---|
== | Equal to | Both sides are the same |
!= | Not equal to | The two sides differ |
> | Greater than | Left is larger |
>= | Greater than or equal | Left is larger or the same |
< | Less than | Left is smaller |
<= | Less than or equal | Left is smaller or the same |
Two of the six work on any operand, and the other four need numbers or something the language can order.
int x = 20;
int y = 30;
System.out.println(x < y);
// true
System.out.println(x > y);
// false
System.out.println(x == y);
// false
System.out.println(x != y);
// true
System.out.println(x >= y);
// false
System.out.println(xThe <, >, <= and >= operators are ordering comparisons, so they need operands the language knows how to put in order. String is not one of them, which surprises people who expect any type with compareTo to work directly.
String a = "apple";
String b = "banana";
System.out.println(a < b);
// error: operator 'The type of both operands must also be compatible. A boolean has no ordering at all, so every ordering comparison on one is rejected.
boolean flag = true;
System.out.println(flag < false);
// error: bad operand types for binary operator '