Often, we saw developers using == operator to compare two strings and hit some problems, but, the solution is to “use equals method to compare two string”.
Yeah that’s right, == operator compare addresses or references, not value. But check this snippet :
"abc" == "abc" // true "abc".equals("abc") // true new String("abc") == new String("abc") // false new String("abc").intern() == new String("abc").intern() // true
How is it possible that the last line correclty returns true ?
The JVM use pool (flywieght pattern) !
Imagine that whenever you use a literal, the JVM creates a new instance, and worse, imagine that you’re inside a loop …
The pool is used to share the same literal between multiple usages and thus saves memory.
So when you compare “abc” with “abc” using the == operator, you are comparing addresses but the both are equal (the same instance is retrieved from the pool).
When you call the intern method on a new String instance, this yields the canonical representation of the string, which turns out to be the literla instance from the pool, and thus the equality.