One Simple way to Avoid Null Pointer Exceptions Doing String Comparisons
Published May 1, 2012
This article was published a really long time ago.
Its value then was likely questionable. Its value now is certainly pure nostalgia.
So you've got this code:
String someString = "Some String";
if someString.equals("Some String")
doSomething();
This is fine because someString is set to the string "Some String", and doSomething() will be called. If someString was set to "Something else" this would be fine too, because there is a value to compare to. But what if someString was null?
if someString.equals("Some String")
doSomething();
someString is not set to an instance of String, it is in fact null, so calling .equals() on null will cause a Null Pointer Exception.
The solution is really simple:
if "Some String".equals(someString)
doSomething();
This way .equals() will always be called on what you know is a String, furthermore .equals handles null values. I forget where I first saw this but I've always loved what a simple solution it is to the problem. Code robustly and you'll run into less trouble down the track.