Menu
Topics Index
...
`


Strings > String Comparison >
Siva Nookala - 04 Apr 2016
== is a relational operator that returns true when both the string reference variables under comparison are referring to the same object. == simply looks at the bits in the variable, and they're either identical or they're not.

equals is a method defined in the Object class. The default implementation of the method provided in this class is similar to "==" equality operator and returns true if we are comparing two references of the same object. But this method is overridden by String class in such a way that when equals() of the String class is invoked, the contents of the String objects rather than the references are compared and a boolean value is returned accordingly i.e. if both the String objects contain the same sequence of characters, true is returned else false.
equals vs String Comparison
import java.lang.*;

class StringComparison
{
    public static void main(String args[])
    {
        String s1 = new String("Merit");
        String s2 = new String("Merit");
        if(s1 == s2)  //LINE A
        {
            System.out.println("Equal");
        }
        else
        {
            System.out.println("Not Equal");
        }
        if(s1.equals(s2))  //LINE B
        {
            System.out.println("Equal");
        }
        else
        {
            System.out.println("Not Equal");
        }
    }
}
OUTPUT

Not Equal
Equal

DESCRIPTION

In LINE A, s1 and s2 are compared using ==. So even though s1 and s2 contain the same sequence of characters, false is returned as they are two different reference variables. So the else block is executed.
In LINE B, s1 and s2 are compared using equals. Since equals checks for contents, true is returned as both the String objects contain the same sequence of characters. So if block is executed.

THINGS TO TRY
  • Try for the below code.
    Integer firstReference = new Integer(10);
    Integer secondReference = firstReference;
    System.out.println(firstReference == secondReference);
    The code will return true, since both firstReference and secondReference are refering to the same object.
  • String first = "Merit Campus";
    String second = null;
    System.out.println(first.equals(second));
    We can pass null as argument to equals method, so false is returned.
  • Try with the below code.
    String first = "Merit Campus";
    String second = null;
    System.out.println(second.equals(first));
    Since equals method cannot be invoked using a null reference, java.lang.NullPointerException is thrown.

When you really need to know if two references are same and point to the same object, use ==. But when you need to know if the objects themselves (not the references) are equal, use the equals()

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App