While beginning development in Java, especially if coming from a .NET background (but not necessarily) you might do string comparison with == in Java. Don’t do it. It will compare the string instances and not their effective value.
You might even try it first to check if == really works, testing it in a wrong manner like so :
public static void main(String[] args) { String s1 = "Abc"; String s2 = "Abc"; System.out.println("s1 == s2 -> " + (s1 == s2)); }
This will output
s1 == s2 -> true
.. which might lead you to believe this works. This does return the correct value because of a feature present in Java and .NET called string interning (not specific to Java or .NET).
Try to obtain a string instance dynamically like concatenating two existing instances and see how things don’t work anymore :
public static void main(String[] args) { String s1 = "Abc"; String s2 = "Abc"; // new lines : String capitalA = "A"; String bc = "bc"; String s3 = capitalA + bc; System.out.println("s1 == s2 -> " + (s1 == s2)); // new line : System.out.println("s1 == s3 -> " + (s1 == s3)); }
s1 == s2 -> true s1 == s3 -> false
Weird, huh? That’s because at compile time there are four distinct strings generated : “Abc” (once, even if referred twice), “A” and “bc”. The “Abc” instance obtained by joining “A” and “bc” will be generated at runtime and, of course, it will be a different instance than the first “Abc” instance. That’s why the result of the == operator comparison will be false.
Read more »
Recent Comments