What is the difference between equals() and “==” ?

Equals is intended to check logical equality and == checks if both references point to same object. (Thanks Sandeep)

a == b;// Compares references, not values.

a.equals(b);// Compares values for equality.

In Core Java, the difference between equals() and == lies in their functionality and what they compare:

  1. equals() method:
    • equals() is a method defined in the Object class, and it is meant to be overridden by classes that need to define specific behavior for object comparison.
    • The default implementation in the Object class compares object references, which means it checks if two object references point to the exact same object in memory.
    • Many classes in Java override the equals() method to provide meaningful comparison based on the content or attributes of objects.

    Example:

    java
    String str1 = new String("Hello");
    String str2 = new String("Hello");
    // This will be true, as String class overrides equals() to compare content
    boolean isEqual = str1.equals(str2);

  2. == operator:
    • The == operator in Java is used for reference comparison when applied to objects.
    • If used with primitive data types (e.g., int, char, etc.), it compares the actual values.
    • When used with objects, it compares the references, checking if both references point to the exact same object in memory.

    Example:

    java
    String str1 = new String("Hello");
    String str2 = new String("Hello");
    // This will be false, as it compares references, not content
    boolean isSameReference = (str1 == str2);

In summary, equals() is meant for content-based comparison and is often overridden by classes to provide meaningful comparisons, while == is used for reference comparison, checking if two references point to the exact same object in memory.