A Tale of String Equality

by Mike on January 14, 2008
in java

In Java there are many ways to check if a String object is equal to a constant string. Here are three I’m going to talk about:

str1=="Value"; str1.equals("Value"); "Value".equals(str1);

The first item is very problematic — it checks to see if str1 and “Value1″ are pointing to the same reference. In the language of C, we are checking to see if the pointers to these strings are pointing to the same space in memory. Since “Value” is a literal string, the chances of that happening are very small — especially if str1 was assigned from the user, a database, etc. This is the worst way to test string equality in Java. And, really, most of us should have learned that long ago.The second item is probably the most common and it works well enough, but it has disadvantages.  The first one: what if str1 is null? If it’s null, then it has no “equals” method and you get an exception. So, really, the second item should be:

str1==null && str1.equals("Value")

Now a simple equality test becomes a compound statement, but it is still valid. But there is something more subtle happening here. The “equals” method accepts an object — any Object, in fact. So you give it a constant string as an plain Object, and in the method, it casts that Object into a String. So you are constructing on object out of a constant. Does that sound like a good idea? Not from from a performance perspective, it doesn’t.  And you care about performance, right?The third item looks a little weird, yet you know that it’ valid Java-syntax. But there are rewards for doing it this way. First, that string constant won’t ever be null, so you don’t need a compound statement. And while “equals” accepts an Object, “str1″ is already an Object, so no re-creation needs to be done. But what if “str1″ is null? Why it catches that too! Because you can send “null” to the “equals” method and the result should always be “false”. It seems that our problems are solved!So, really, in spite of how it looks, the follow seems to be the best way to test for String equality:

"Value".equals(str1);

Comments

One Response to “A Tale of String Equality”

Share Your Thoughts

You must be logged in to post a comment.