How to reduce NullPointerExceptions

This is a coding technique that can help reduce the number of NullPointerExceptions that you need to deal with without resorting to checking for null Strings every time you compare literal values.

This is the way we’re taught to compare equality between a String field and a literal String:

String name = null;
...
if (name.equals("Bob")){
   System.out.printLn("I found Bob!");
} else {
   System.out.printLn("Bob is still missing...");
}

The above example works fine as long as name is not null.  If name is null, this code will throw a NullPointerException.  We can add another condition as shown here to avoid the exception.

String name = null;
...
if (name != null && name.equals("Bob")){
   System.out.printLn("I found Bob!");
} else {
   System.out.printLn("Bob is still missing...");
}

But there’s an easier way and more concise way to handle this — you can invoke the equals() method on a literal String which will never throw a NullPointerException.

String name = null;
...
if ("Bob".equals(name)){
   System.out.printLn("I found Bob!");
} else {
   System.out.printLn("Bob is still missing...");
}

This code looks a little strange at first, but its a perfectly legitimate way to check for equality and will NEVER throw a NullPointerException since the literal String always has a value.

Advertisements

One thought on “How to reduce NullPointerExceptions

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s