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 - boverflows for large values. UseInteger.compare. - Comparing
BigDecimalwithequalsβ usecompareTo.
Related
Pillar: Java operators. See also equals & hashCode, instanceof.