String equality vs equality of location

Java only automatically interns String literals. New String objects (created using the new keyword) are not interned by default. You can use the String.intern() method to intern an existing String object. Calling intern will check the existing String pool for a matching object and return it if one exists or add it if there was no match.

If you add the line

s3 = s3.intern();

to your code right after you create s3, you’ll see the difference in your output.

See some more examples and a more detailed explanation.

This of course brings up the very important topic of when to use == and when to use the equals method in Java. You almost always want to use equals when dealing with object references. The == operator compares reference values, which is almost never what you mean to compare. Knowing the difference helps you decide when it’s appropriate to use == or equals.

Leave a Comment