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).
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
Nope - the string pool is only used for constant strings unless you call
intern
.So the string pool contains
"learn"
,"Java"
and"learnJava"
... buts1
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:
Or if you want to keep your execution-time concatenation:
In general though, just don't compare strings with
==
... it's almost always a bad idea.