== vs equals()
== compares primitive values and object references; equals() compares object contents.
Available since: Java 1.0
Syntax
a == b / a.equals(b)Examples
For primitives == compares values, for objects it asks "is this the same object":
void main() {
int a = 1000;
int b = 1000;
IO.println(a == b);
String s1 = "hi";
String s2 = new String("hi");
IO.println(s1 == s2);
IO.println(s1.equals(s2));
}Output:
true
false
trueThe Integer wrapper trap: small numbers are cached, large ones are not:
void main() {
Integer x = 127, y = 127;
Integer p = 1000, q = 1000;
IO.println(x == y);
IO.println(p == q);
IO.println(p.equals(q));
}Output:
true
false
trueNotes
The rule: compare primitives (int, double, char, boolean) with == and objects (String, Integer, records, lists) with equals(). The exception is enum values, compared with ==. For equals() to work in your own class you must override it (together with hashCode()); records do this automatically.
Because of rounding errors, double values are rarely exactly equal: 0.1 + 0.2 == 0.3 is false. Compare with a tolerance: Math.abs(a - b) < 1e-9.
See also
- String.equals() — Compares the contents of two strings.
- Object.equals() — Compares objects by meaning. By default it works like ==, so classes override it.
- Objects.equals() — Compares two objects with equals(), safely for null.
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.