String literals are created on what is called: Pool Memory.
However, when one creates a String with explicitly new
keyword, he actually creates a new String object, independent of the pool memory's one. Meaning that both references are not the same at all.
In your sample, you could solve the case by both ways:
_ use java.lang.String.intern
method: placing your explicitly created String into the pool memory.
_ use only literals to create/reuse String
.
For information, Pool Memory was created in order to avoid some useless creation of common/redundant literal Strings, thus optimizing memory space.
Similar concept exists for Integer: Integer caching in Java