Frequently in Java code, we come across the usage of == and equals(). The question arises whether == and equals() perform the same operations or whether they work differently. To answer this question, let us examine how == and equals() work and then identify their differences.

The == operator:

The == is a relational operator in Java that is used to compare two operands. It is used to determine whether the two operands are equal or not. Using the == operator, you can compare any primitive type such as int, char, float and Booleans. After comparison, the == operator returns a boolean value. If the two operands are equal, the == operator returns a true value. However, if the two operands are not equal, it returns a false value.
When used with objects, the == operator compares the two object references and determines whether they refer to the same instance.

Example:

public class ComparisonDemo {

    public static void main(String[] args) {
        Integer a = new Integer("10");
        Integer b = new Integer("10");
        if (a == b) {
            System.out.println("a and b are equal");
        } else {
            System.out.println("a and b are not equal");
        }
    }
}

Output :

a and b are not equal

The .equals() Method

equals() is a method available in the String class that is used to compare two strings and determine whether they are equal. This method returns a boolean value as a result of the comparison. If the two strings contain the same characters in the same order, the equals() method returns true. Otherwise, it returns a false value.

Syntax:


boolean equals(Object var);

Example:

public class ComparisonDemo {

    public static void main(String[] args) {
        String s1 = "Good Morning";
        String s2 = "Good Morning";
        System.out.println(s1.equals(s2));

        String s3 = new String("Good Evening");
        String s4 = new String("Good Evening");
        System.out.println(s3.equals(s4));

    }
}

Output:


true
true

== Versus .equals()

Though the == operator and the equals() method are used to test equality, they do not work the same way. While the equals() method compares each character within the two String objects, the == operator compares the two object references. Let’s consider the following example.

Example:

public class ComparisonDemo {

    public static void main(String[] args) {
        String str1 = "Good Day";
        String str2 = new String(str1);
        System.out.println(str1.equals(str2));
        System.out.println(str1 == str2);

    }
}

Output:

true
false

Here, str1 refers to a String instance that contains “Good Day” and str2 refers to a new object created using str1 as the initialiser. Though the two String objects str1 and str2 contain the same content “Good Day”, they are two different objects. Therefore, str1 and str2 refer to different instances, and the == operator returns a false value as a result.

Happy Learning 🙂