Java Reference ยท Operators
Java comparison operators
Reference for Java comparison operators ==, !=, <, >, <= and >=: operand types, NaN behavior, floating-point pitfalls and comparing references.
Java has six comparison operators: ==, !=, <, >, <= and >=. Each produces a boolean. The four relational operators (<, >, <=, >=) work only on numeric types, including char. The equality operators == and != also work on boolean and on references.
Before comparing, operands go through numeric promotion, so 1 == 1.0 is true and 'a' < 98 is true. For references, == compares identity (are these the same object?), not content. Use equals() for content; see == vs. equals().
boolean ok = age >= 18 && age < 65;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
a == b a != b a < b a > b a <= b a >= b
| Operator | Operand types | Result |
|---|---|---|
< > <= >= |
numeric (byte to double, char, and boxed numbers, which are unboxed) |
boolean |
== != |
numeric, boolean, or two references of related types |
boolean |
Usage notes
- Chaining does not exist.
1 < x < 10does not compile (abooleancannot be compared with<to anint). Write1 < x && x < 10. - NaN is unordered. Every comparison with
NaNisfalseexcept!=. Test withDouble.isNaN().Double.compare()andequals()use a total order that putsNaNlast and treats0.0and-0.0as different. - Do not use
==on computed floating-point values. Compare with a tolerance, or useBigDecimal. - References.
==is true only when both refer to the same object (or both arenull).new String("a") == "a"isfalse. - Boxed values.
Integer == Integercompares identity, and only small cached values (-128 to 127 by default) happen to be identical. A relational operator like<=or mixing with a primitive unboxes, so it compares values. Anullwrapper then throwsNullPointerException. - Enums are safely compared with
==. - Redundant booleans.
if (flag == true)is justif (flag).