What is the difference between the “==” operator and the “.equals()” method in Java?

Here’s a clear explanation of the difference between == and .equals() in Java:

  1. == Operator:
    • Purpose: Checks if two references point to the same object in memory.
    • Use Case: Used for comparing primitive data types (e.g., int, char) or object references.
    • Example: String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1 == s2); // false (different memory locations)
  2. .equals() Method:
    • Purpose: Compares the contents (value) of two objects for equality.
    • Use Case: Used for comparing the actual data inside objects (e.g., strings, custom objects).
    • Can Be Overridden: Classes like String and Integer override .equals() to compare values.
    • Example: String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1.equals(s2)); // true (same content)

Key Difference:

  • ==: Checks if two references point to the same object.
  • .equals(): Checks if two objects have the same content.

Note:

For primitive types like int, == compares the values directly. For objects, use .equals() to compare their values.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top