== vs equals()

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • == is an operator used to compare memory addresses (reference equality) for objects, and values for primitives.
  • .equals() is a method used to compare the meaningful content or state of two objects (value equality).

Concept

When comparing variables in Java, you must choose between the == operator and the .equals() method.

The == Operator

For primitive types (int, boolean, etc.), == strictly compares the values (e.g., 5 == 5).
For reference types (objects), == compares whether both references point to the exact same memory location on the heap. It does not check if the objects look the same inside.

The .equals() Method

.equals() is a method defined in the Object class (which every class inherits). By default, .equals() just uses == under the hood. However, classes like String, Integer, and List override this method to check if the actual content of the two objects is identical, regardless of their memory location.

Examples

public class EqualsExample {
    public static void main(String[] args) {
        // Primitives
        int a = 10;
        int b = 10;
        System.out.println(a == b); // true (values are the same)
        
        // Objects
        String s1 = new String("Java");
        String s2 = new String("Java");
        
        // Reference Equality
        System.out.println(s1 == s2); // false (different memory addresses on Heap)
        
        // Value Equality
        System.out.println(s1.equals(s2)); // true (content is the same)
    }
}

Interview Questions

Q: Can you use == to compare Strings?
A: It is highly discouraged. While == might sometimes return true for two strings due to the String Pool (e.g., String a = "hi"; String b = "hi"; a == b), it will fail if the strings are constructed dynamically or via new String(). Always use .equals() for Strings.

Q: If two objects are .equals(), must they have the same .hashCode()?
A: Yes. According to the contract defined in the Object class, if a.equals(b) is true, then a.hashCode() == b.hashCode() must also be true. If you override .equals() in a custom class, you must always override .hashCode().