Difference between equals() method and == in Java

Generally, the equals() method and == operator are used in Java to compare objects to check for equality. In this article, let’s learn a few important differences between the equals() method and == operator.

  1. The main difference between the equals() method and the == operator is that one is a method and the other is an operator.
  2. == operator is used during the reference comparison. On other hand equals() method is used for content comparison.
  3. equals() method can be overridden by Object.equals() method. Whereas == operator can’t be overridden.

Example

package PraticeProblems;

public class stringCamparision {

  public static void main(String[] args) {
    String str1 = "Hello World!!";
    String str2 = "Hello World!!";
    String str3 = new String("Hello World!!");
    // content of str1, str2, str3
    System.out.println(str1);
    System.out.println(str2);
    System.out.println(str3);
    // Using == operator
    System.out.println(str1 == str2);
    System.out.println(str1 == str3);
    // Using equals() method
    System.out.println(str1.equals(str2));
    System.out.println(str1.equals(str3));
  }
}

Output

Hello World!!
Hello World!!
Hello World!!
true
false
true
true

Explanation

Here s1 and s2 refer to different objects. But when we use the == operator for s1 and s2 comparison it returns true because they both have the same address in the heap. By using the equals() method also it returns true because it compares the content of object s1 and s2.

On the other hand, when we use the == operator for comparing s1 and s3 it returns false because both have different addresses. But by using the equals() method, it returns true because contains the same content.

Also, refer

How to compare two strings in Java

Program to check two Strings are Anagram or not using Hashmap in Java

Leave a Reply

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