Sunday 12 August 2012

Difference between == , equals and equalsIgnoreCase


A lot of Java new programmers get confused when comparing String with another. With so many different ways to do comparison on String, every of them seems to be the same. But the fact is, they are NOT! Having to know the differences on these will help to create a better , more efficient application, thus getting required results.

Here, we will compare ways and differences between == , equals and equalsIgnoreCase.


== Operator 



This operator compares two object references to see whether they refer to the same instance. Consider x and y, two String object references, then x==y comparing the memory addresses of the objects referenced by x and y (i.e. not the data of the objects).

String s1 = new String(“Java”);

String s2 = new String(“Java”);

System.out.println(s1==s2); ——> returns false

String s3 = s1;

System.out.println(s3==s1); ——-> returns true


boolean equals(Object anObject)

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.


String f1 = “mouse”;

String f2 = “mouse”;

String f3 = “MOUSE”;

System.out.println(f1.equals(f2)); ——> returns true

System.out.println(f1.equals(f3)); ——> returns false


boolean equalsIgnoreCase(String anotherString)




Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case.

String s1 = new String(“Java”);

String s2 = new String(“JAVA”);

System.out.println(s1.equalsIgnoneCase(s2)); ——> returns true

No comments:

Post a Comment