CODE
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");
}
}
}
Not Equal
Equal
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.
Integer firstReference = new Integer(10);
Integer secondReference = firstReference;
System.out.println(firstReference == secondReference);
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));
null
as argument to equals
method, so false
is returned. String first = "Merit Campus";
String second = null;
System.out.println(second.equals(first));
equals
method cannot be invoked using a null
reference, java.lang.NullPointerException
is thrown.