Thursday, February 17, 2005

Idiosyncrasies of the == String comparison

Some fun with String equality ... (and btw, that's why it is advisable to use string.equals() instead of == )

String s1 = "True";
String s2 = "True";
s1 == s2 == true //compiler uses one instance for string literals

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

Pretty much summarizes various possiblities that arise in the == string comparison. Found this in a discussion on
Autoboxing in J2SE 5 on TSS.

No comments: