Alot 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.
==
This operator compares two object references to see whether they refer to the same instance. Meaning to say, it is used to check whether the two objects are the same object or not.
String s1 = new String(“mickey”);
String s2 = new String(“mickey”);
System.out.println(s1==s2); ——> returns false
String s3 = s1;
System.out.println(s3==s1); ——-> returns true
equals
This method creates two char arrays and puts the characters of each String objects in separate array and then performs the comparison.
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
equalsIgnoreCase
The special about this is it’ll do comparison on two String but ignoring the case of them.
String f1 = “mouse”;
String t1 = “cartoon”;
String t3 = “CARTOON”;
System.out.println(t1.equals(t2)); ——> returns true