Equals is a method used to compare the contents (values) of two obejcts - not their memory locations.
String a = "hi";
String b = "hi";
a == b // true (same memory in string pool)
a.equals(b) // true (same content)
Comparison
Comparison | Checks for | Used With |
---|---|---|
== | Reference equality | Primitives & Objects |
.equals() | Value/content equality | Objects only |
Integer x = new Integer(2);
Integer y = new Integer(2);
x == y // false (different objects)
x.equals(y) // true (same value)
Example
public class Person {
String name;
Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceOf Person)) return false;
Person p = (Person) obj;
return this.name.equals(p.name);
}
}
Also override hashCode()
if using in a HashMap or HashSet.
Tip
Use
.equals()
when comparing String, wrapper objects or custom classes.
==
only for primitive or intentional reference checks.
Parent: _Object Methods