Checking Null Strings

It is important that your application handle null variables, as NullPointerException can occur on almost any line of your code (as long as that line has a method invocation).

The Traditional Way

You need to check equivalance of a String, but it may be null:


if (firstName != null) {
	if (firstName.equals("John")) {
		// Do something
	}
}

The outer if is necessary because doing the inner if directly causes a NullPointerException to be thrown.

Short Circuitry

Using Java’s short-circuit condition testing, it is often improved as:


if (firstName != null && firstName.equals("John")) {
	// Do something
}

Since && requires both conditions to be true, once Java evaluates the left portion and realizes it is false, it concludes that the entire condition is false and skips the right portion.

Avoiding the null

The shortest so far:


if ("John".equals(firstName)) {
	// Do something
}

In this case the equals is called on the “John” string, which cannot be null. If firstName happens to be null, it will not be equal to “John” and skips the doSomething block. In short, put the object that you are sure is not null in front, to perform the method invocation.

This method is less “readable” for noobs, they may not realize that the null condition is handled for here. Noobs should not attempt to learn this shortcut directly without realizing it is trying to handle a NullPointerException. Instead they should learn the traditional methods first and understand how this is realized, so that they know why NullPointerExceptions occur and how to fix them. Should both the variables being compared may be null, they should realize that this method does not work. (either through thinking or trying and discovering the bug)

RSS feed for comments on this post · TrackBack URL

Leave a Comment