Comparing String objects with literals

This one’s pretty simple, but I find that it comes up in most code reviews that I perform. Developers commonly need to populate a String object, then check to see if the String contains a certain value;

String s;
s = someMethod();
if (s.equals("HelloWorld"))
{
    //Do something
}

Unfortunately, if someMethod() returns null for any reason, you end up getting a NullPointerException when you call s.equals() .

A developer’s first instinct is to check for null:

String s;
s = someMethod();
if (s!=null && s.equals("HelloWorld"))
{
    //Do something
}

This works, but there is a more elegant solution that will guarantee that you won’t get a NullPointerException. To do this, just change up your .equals statement so that you are calling the equals() method on the string literal instead of the String object:

String s;
s = someMethod();
if ("HelloWorld".equals(s))
{
    //Do something
}

Because a String literal (“HelloWorld”) can’t be null, “HelloWorld”.equals(s) will never throw a NullPointerException, even if s is null.

I’ve gotten into the habit of always writing comparisons against String literals this way so I don’t have to worry about null checks.

One thought on “Comparing String objects with literals”

  1. Hi

    On comparing two Strings, I generally use
    “org.apache.commons.lang.StringUtils.equals(…, …);”.

    Very handy…

Leave a Reply

Your email address will not be published. Required fields are marked *