Codementor Events

Java String Literal Comparison and NullPointerException

Published Dec 31, 2017Last updated Apr 09, 2018
Java String Literal Comparison and NullPointerException

When comparing String literals to String variables I often come across the following style of code:

final String MY_NAME = "Steve";

void myMethod(String aName) {
  if (aName.equals(MY_NAME)) {
    	// do something
    }
}

If I were to call the above method with a null argument, it would throw a NullPointerException. Of course you could add a defensive check but you would also be adding complexity and increasing method/codebase size:

final String MY_NAME = "Steve";

void myMethod(String aName) {
  // defensive check to avoid NullPointerException
  if (aName == null) {
    	return;
  }
  if (aName.equals(MY_NAME)) {
    	// do something
    }
}

A better solution to defending against a NullPointerException in such a scenario is to simply place the literal first. the String.equals methods will happily handle a null argument and you know your String literal will never be null (unless you explicitly set it of course):

final String MY_NAME = "Steve";

void myMethod(String aName) {
  if (MY_NAME.equals(aName)) {
    	// do something
    }
}
Discover and read more posts from Steve Donovan
get started