Tuesday, October 19, 2010

String comparisons using ==, equals () or compartTo()

Using ==
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them).
Using equals()
Use the .equals() method to compare strings for equality. Similarly, use the .compareTo() method to test for unequal comparisons. For example,
String s1 = "True";
String s2 = "True";
s1 == s2 == true //compiler uses one instance for string literals , so works fine as 2 strings are
same taken from string pool.
String s3 = new String("False");
String s4 = new String("False");
s3 == s4 == false //two forced instances
String s5 = "True";
String s6 = "Tr" + "ue";
s5 == s6 == true //compiler evaluates and uses same instance
String s7 = "False";
String sx = "F";
String s8 = sx + "alse";
s7 == s8 == false //compiler won't evaluate where a second reference is involved
These values are all "equal". But == will return true or false based on _how_ the values were set.
Stick to .equals(), and enjoy the remaining features of autoboxing.
compareTo() and comparison operators
if (s > t)    // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
I guess I don't find it inconsistent, or at least not as inconsistent as the alternative would be. In each case the result is true or false based on whether the reference is pointing to the same object instance or not. When dealing with objects, == does not compare values. Doing so _would_ be inconsistent.

No comments:

Post a Comment

Chitika