Difference between equals() and == in Java

In Java, == and equals() are both used to compare objects, but they serve different purposes and behave differently depending on the context. Let’s break down the differences:

1. Purpose

== :

  • Used for reference comparison (i.e., checking if two references point to the same memory location).
  • When used with primitives, it compares the actual values.

equals():

  • Used for content comparison (i.e., to check whether two objects are logically equivalent based on their content).
  • It can be overridden by classes (like String, Integer, Object) to provide custom logic for comparing objects.

2. Usage for Primitives

  • ==: When used with primitive data types (like int, char, boolean), == compares the actual values.
  • Example: int a = 5; int b = 5; System.out.println(a == b); // true, because values are the same
  • equals(): You cannot use equals() with primitive types directly since it is a method in Object and works only with objects (reference types).

3. Usage for Objects (Reference Types)

  • ==: When used with objects, == checks whether the two object references point to the same location in memory (i.e., whether they are the same object).

Example:

String s1 = new String("hello"); String s2 = new String("hello"); System.out.println(s1 == s2); // false, because s1 and s2 are different objects in memory
  • equals(): When used with objects, equals() checks whether the two objects are logically equal (i.e., have the same content). For example, the String class overrides equals() to compare the characters inside the string.

Example:

String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2));  // true, because s1 and s2 have the same content

    4. Default Behavior of equals()

    • The default implementation of equals() in the Object class behaves the same as ==. It compares object references (not the content). So, unless a class overrides equals(), it will check reference equality.

    Example (without overriding equals()):

    class Person {
        String name;
    
        Person(String name) {
            this.name = name;
        }
    }
    
    Person p1 = new Person("Alice");
    Person p2 = new Person("Alice");
    System.out.println(p1.equals(p2));  // false, because equals() is not overridden
    

      After overriding equals() (content comparison):

      class Person {
          String name;
      
          Person(String name) {
              this.name = name;
          }
      
          @Override
          public boolean equals(Object obj) {
              if (this == obj) return true;
              if (obj == null || getClass() != obj.getClass()) return false;
              Person person = (Person) obj;
              return name.equals(person.name);
          }
      }
      
      Person p1 = new Person("Alice");
      Person p2 = new Person("Alice");
      System.out.println(p1.equals(p2));  // true, because equals() is overridden to compare names
      

        5. Immutable Objects (e.g., String, Wrapper Classes)

        • For immutable objects like String and wrapper classes (Integer, Boolean, etc.), the equals() method is overridden to compare content.

        Example with String:

        String s1 = "hello";
        String s2 = "hello";
        System.out.println(s1 == s2);       // true, because of string interning (same reference)
        System.out.println(s1.equals(s2));  // true, because the content is the same
        

        Example with Integer:

        Integer a = 128;
        Integer b = 128;
        System.out.println(a == b);         // false, different objects (outside -128 to 127 range)
        System.out.println(a.equals(b));    // true, same content
        

          Summary Table:

          Comparison Aspect==equals()
          PurposeReference comparison (for objects) or value comparison (for primitives)Content (logical) comparison for objects
          Usage with PrimitivesCompares the actual values of primitive typesCannot be used with primitives
          Usage with ObjectsCompares the memory addresses (references)Compares object contents (can be overridden)
          Default Behavior for ObjectsCompares memory references (same as ==)Reference equality unless overridden
          Example with String"hello" == "hello" is true due to string interning"hello".equals("hello") is true for content
          OverridableNoYes, often overridden (e.g., in String, Integer)

          Key Points:

          • == checks for reference equality when used with objects (are the two variables pointing to the same memory location?).
          • equals() checks for content equality and is used to compare the logical equivalence of objects. For most objects (like String, Integer, and custom classes), you should use equals() to compare values rather than ==.

          Related Posts

          Leave a Reply

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