Menu
Topics Index
...
`

equals vs String Comparison - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App