What is the difference between .equals() and == operator?

In Java, .equals() and the == operator are used for comparison, but they serve different purposes and are used in different contexts. Here’s a detailed explanation of the differences between them:

1. == Operator

  • Purpose: The == operator is used to compare the memory addresses (references) of two objects to determine if they refer to the exact same instance. For primitive data types, it compares the actual values.
  • Comparison for Primitive Types: For primitive data types (e.g., int, char, double), == compares the actual values.

java int a = 10; int b = 10; System.out.println(a == b); // Output: true

  • Comparison for Objects: For objects, == compares the references (memory addresses) to check if they point to the same object in memory.

java String str1 = new String("hello"); String str2 = new String("hello"); System.out.println(str1 == str2); // Output: false (different memory locations)

2. .equals() Method

  • Purpose: The .equals() method is used to compare the actual content or logical equality of two objects. It is defined in the Object class and can be overridden by subclasses to provide custom comparison logic.
  • Default Implementation: The default implementation of .equals() in the Object class is similar to ==, comparing memory addresses. However, many classes (like String, Integer, etc.) override this method to compare object content.
  • Comparison for Strings: For String objects, .equals() compares the actual sequence of characters.

java String str1 = new String("hello"); String str2 = new String("hello"); System.out.println(str1.equals(str2)); // Output: true (same content)

Example: == vs .equals()

Here’s an example showing the difference between == and .equals() with a String:

public class EqualityExample {
    public static void main(String[] args) {
        String str1 = new String("hello");
        String str2 = new String("hello");

// Using == operator
System.out.println("str1 == str2: " + (str1 == str2));  // Output: false

// Using .equals() method
System.out.println("str1.equals(str2): " + str1.equals(str2));  // Output: true

}


}  

In this example:

- str1 == str2 returns false because str1 and str2 are different objects in memory.

- str1.equals(str2) returns true because str1 and str2 have the same content.


Summary

  • Use == when you need to check if two references point to the same object or when comparing primitive values.
  • Use .equals() when you need to check if two objects are logically equivalent or have the same content.