String Comparison

Two string can be compared using equals() method. Equality operator can't be used for comparing string. Equality operator only compare reference variable, whether both reference variable pointing to same object or not.

Example


class str 
{
public static void main(String arg[])
{
String a=new String("hello");
String b=new String("hello");
if(a==b)
System.out.println("Same object");
else
System.out.println("Different Object");

}
}
/*Ouput:
Different Object
*/

In above program two objects are created. Both having same value, But both objects are different that's why "a==b" condition will return false. Equality operator return true only in case when both reference variable point to same object. In order to check content of string object equals() method is used. "equals()" method return true if both object have same content.

Example


class str 
{
public static void main(String arg[])
{
String a=new String("hello");
String b=new String("hello");
if(a.equals(b))
System.out.println("Same object");
else
System.out.println("Different Object");

}
}
/*Ouput:
Same Object
*/

equals() method is case sensitive, means "hello" and "Hello" string are different. There is one more method equalsIgnoreCase() method which will ignore case and compare string.

Example


class str 
{
public static void main(String arg[])
{
String a=new String("hello");
String b=new String("Hello");
if(a.equalsIgnoreCase(b))
System.out.println("Same object");
else
System.out.println("Different Object");

}
}
/*Ouput:
Same Object
*/