Java String Comparison – Are Both Strings Equal?

javastring

String s1 = "learn";
String s1 = s1+"Java";

now s1 is pointing to "learnJava" string right ?

String s2 = "learnJava";

if(s1 == s2) is false. WHY ?

s2 should point to same "learnJava" as its already present in StringConstantPool(s1).

Best Answer

s2 should point to same "learnJava" as its already present in StringConstantPool.

Nope - the string pool is only used for constant strings unless you call intern.

So the string pool contains "learn", "Java" and "learnJava"... but s1 refers to a string not in the string pool, because the concatenation is performed at execution time.

If you had a compile-time constant expression, it would be different:

String s1 = "learn" + "Java"; // Constant expression
String s2 = "learnJava";
System.out.println(s1 == s2); // true, guaranteed

Or if you want to keep your execution-time concatenation:

String s1 = "learn";
s1 += "Java";
s1 = s1.intern();
String s2 = "learnJava";
System.out.println(s1 == s2); // true

In general though, just don't compare strings with ==... it's almost always a bad idea.

Related Question