Skip to content
Tutorials Center
My learning

Topics

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().

Java
boolean ok = age >= 18 && age < 65;

Try it

Java Numeric comparisons and promotion

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.

Java NaN and mixed boxes

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

Java
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 < 10 does not compile (a boolean cannot be compared with < to an int). Write 1 < x && x < 10.
  • NaN is unordered. Every comparison with NaN is false except !=. Test with Double.isNaN(). Double.compare() and equals() use a total order that puts NaN last and treats 0.0 and -0.0 as different.
  • Do not use == on computed floating-point values. Compare with a tolerance, or use BigDecimal.
  • References. == is true only when both refer to the same object (or both are null). new String("a") == "a" is false.
  • Boxed values. Integer == Integer compares 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. A null wrapper then throws NullPointerException.
  • Enums are safely compared with ==.
  • Redundant booleans. if (flag == true) is just if (flag).