Comparison Operators in Java

Comparison operators always produce a boolean. Java has six relational operators plus instanceof β€” a type-test operator.

The basics

a == b       // equal
a != b       // not equal
a < b        a <= b
a > b        a >= b
a instanceof String   // type check

== on objects is reference equality

String s1 = new String("hi");
String s2 = new String("hi");
s1 == s2;              // false β€” different objects
s1.equals(s2);         // true β€” content comparison

For every reference type (except enum constants), use .equals(). Strings from literals happen to be interned, which makes == appear to work β€” it breaks as soon as a new String or .substring() enters the picture.

Boxing pitfall

Integer a = 127, b = 127;
Integer c = 200, d = 200;
a == b;                // true  β€” cached (βˆ’128..127)
c == d;                // false β€” different objects

c.equals(d);           // βœ… always works

Floating-point ==

0.1 + 0.2 == 0.3;                // false
Math.abs(0.1 + 0.2 - 0.3) < 1e-9; // βœ… compare with tolerance

BigDecimal gotcha

new BigDecimal("1.00").equals(new BigDecimal("1.0"));   // false β€” different scale!
new BigDecimal("1.00").compareTo(new BigDecimal("1.0")); // 0 β€” equal value

Use compareTo() == 0 for BigDecimal equality.

Comparable and compareTo

public class Age implements Comparable<Age> {
    private final int years;
    @Override public int compareTo(Age other) {
        return Integer.compare(years, other.years);   // never use subtraction β€” overflow risk
    }
}

Common mistakes

  • == on Strings β€” use .equals() (or .equalsIgnoreCase()).
  • Boxing == bug β€” works by luck for small numbers, breaks for large.
  • Subtracting ints in compareTo β€” a - b overflows for large values. Use Integer.compare.
  • Comparing BigDecimal with equals β€” use compareTo.

Related

Pillar: Java operators. See also equals & hashCode, instanceof.