Canonical representation

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.

Advertisements

2 thoughts on “Canonical representation

    • Actually it’s the expression which is used by javadoc : “Returns a canonical representation for the string object”.
      The meaning is that you will get the original value of this string (which one in the string pool).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s