Posted on: January 18, 2025 Posted by: rahulgite Comments: 0

equals() vs == in Java

Java provides two mechanisms for comparing objects and primitive types: the equals() method and the == operator. Both have distinct purposes and behaviors.


1. == Operator

  • Definition: The == operator is used to compare references for objects and values for primitive types.
  • Behavior:
    • For primitives, it compares the actual values.
    • For objects, it checks if the references point to the same memory location.

Example: Using == with Primitives

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 10;

        System.out.println(a == b); // true (compares values)
    }
}

Example: Using == with Objects

public class Main {
    public static void main(String[] args) {
        String s1 = new String("Hello");
        String s2 = new String("Hello");

        System.out.println(s1 == s2); // false (different references)

        String s3 = "Hello";
        String s4 = "Hello";

        System.out.println(s3 == s4); // true (same reference from string pool)
    }
}

2. equals() Method

  • Definition: The equals() method is used to compare the contents (or values) of objects.
  • Behavior:
    • Defined in the Object class.
    • The default implementation in Object compares references (similar to ==).
    • Many classes, such as String and Wrapper classes, override equals() to provide value-based comparison.

Example: Using equals() with Objects

public class Main {
    public static void main(String[] args) {
        String s1 = new String("Hello");
        String s2 = new String("Hello");

        System.out.println(s1.equals(s2)); // true (compares content)

        Integer num1 = 100;
        Integer num2 = 100;
        System.out.println(num1.equals(num2)); // true (compares value)
    }
}

3. Custom Implementation of equals() and hashCode()

When creating custom classes, overriding both equals() and hashCode() is essential to maintain the contract between these two methods. The hashCode() method is used to generate a hash value for the object, primarily used in collections like HashMap and HashSet.

Example: Overriding equals() and hashCode()

import java.util.Objects;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;

        Person person = (Person) obj;
        return age == person.age && name.equals(person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

public class Main {
    public static void main(String[] args) {
        Person p1 = new Person("Alice", 25);
        Person p2 = new Person("Alice", 25);

        System.out.println(p1.equals(p2)); // true (compares attributes)
        System.out.println(p1.hashCode() == p2.hashCode()); // true (consistent hash codes)
    }
}


Key Points for equals() and hashCode():

  1. Consistency: If two objects are equal (equals() returns true), their hashCode() values must also be equal.
  2. Performance in Collections: Collections like HashMap and HashSet use hashCode() for efficient lookups.
  3. Best Practice: Always override hashCode() when overriding equals().

Key Differences Between == and equals()

Feature== Operatorequals() Method
TypeOperatorMethod
ComparisonCompares references for objects, values for primitivesCompares object content (if overridden)
Default BehaviorCompares memory addressesSame as == (in Object class)
Override PossibleNoYes
Best Use CaseFor primitives or reference comparisonFor logical equality comparison

Conclusion:

  • Use == for comparing primitives or checking if two references point to the same object.
  • Use equals() for comparing the content of objects, especially when working with classes that override equals().
  • Always override hashCode() when overriding equals() to ensure consistent behavior in hash-based collections.
  • Custom implementations of equals() and hashCode() provide logical equality and efficient usage in collections like HashMap and HashSet.

Leave a Comment