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

ComparisonChecks forUsed With
==Reference equalityPrimitives & Objects
.equals()Value/content equalityObjects only
Integer x = new Integer(2);
Integer y = new Integer(2);
 
x == y       // false (different objects)
x.equals(y)  // true  (same value)

Example

Override .equals() for custom value-based comparison
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