The method String.intern() can be used to ensure that equal strings have equal references. String constants are intern
ed, so s1
and s2
will reference the same string. String.toString()
simply returns itself, that is, a.toString()
returns a, when a is a String. So, s2 also == s3.
In general, strings should not be compared by reference equality, but by value equality, using equals()
. The reason is that it's easy to get two strings that are equivalent but different references. For example, when creating substrings. An exception to this rule is that if you know both strings have been intern
ed beforehand (or you intern them as part of the comparison.)
To answer your implied question about heap or stack, Strings are allocated on the heap. Even if they were allocated on the stack, such as with the upcoming escape analysis and stack allocation, the semantics of the program will not change, and you will get the same result for both heap and stack allocation.