RSS Feed
15
Oct.
2003

Tips 'n' Tricks: Prevent NullPointerException in string comparison

Very often I read the following statement:

if (someString.equals("foo")) ...
Now if someString is null this code would produce a nasty NullPointerException. One solution might be:
if ((someString != null) && someString.equals("foo")) ...
But there's a better way:
if ("foo".equals(someString)) ...

Very easy =)

Comments

1. Martin
<pre>StringUtils.equals(String, String)</pre> Is also pretty handy. The Jakarta Commons Lang package is used for Struts, Hibernate, WebWork, and many other popular Open-Source projects, and is a good source of sanity helper functions.

2. WoEyE
The class StringUtils features a lot of very usefull methods. So does the entire commons stuff from Jakarta. In case you don't know Jakarta commons take a look. It's worth!