This has to do with the fact that you cannot compare strings with ==
as well as compiler optimizations.
==
in Java only compares if the two sides refer to the exact same instance of the same object. It does not compare the content. To compare the actual content of the strings, you need to use s1.equals(s2)
.
Now the reason why s1 == s2
is true and s1 == s3
is false is because the JVM decided to optimize the code so that s1
and s2
are the same object. (It's called, "String Pooling.")
Per 3.10.5: Pooling of string literals is actually mandated by the standard.
Moreover, a string literal always refers to the same instance of class
String. This is because string literals - or, more generally, strings
that are the values of constant expressions (§15.28) - are "interned"
so as to share unique instances, using the method String.intern.