On my system, the code prints
s1 and s2 are notequal
s2 and s3 are equal
s1 and s3 are notequal
If your question is why, it has to do with how the Java compiler treats String literals.
Usually, Java will point all references to the same string literal to the same object, for efficiency. In the case of s2
and s3
, the compiler appears to have realized that the result of the concatenation is the same string literal, so it assigned the references s2
and s3
to point at the same object in memory. That is why those two compare equal with ==
.
Since s1
does not have the same value as s2
and s3
, it will be assigned a different memory location, so the reference will not compare equal with ==
.