Monday, September 7, 2009

NullPointerException thrown when comparing strings

When comparing strings in Java a run-time NullPointerException will be thrown if either string is null.
This can be avoided by performing a comparison between a constant and variable string which could potentially be null.

That is, variable.equals(CONSTANT) will throw a run-time exception if the variable is null. Therefore, a better comparison would be CONSTANT.equals(variable)

The following will throw an exception

public class StringCompare {
final static String ELEMENT = "constant";
public static void main( String[] args ) {
String element = null;
element = getElementValue();
if (element.equals(ELEMENT)) {
System.out.println("element " + element + " matches ELEMENT " + ELEMENT);
}
}

private static String getElementValue() {
return null;
}
}

Whereas this will not throw an exception

public class StringCompare {
final static String ELEMENT = "constant";
public static void main( String[] args ) {
String element = null;
element = getElementValue();
if (ELEMENT.equals(element)) {
System.out.println("element " + element + " matches ELEMENT " + ELEMENT);
}
}

private static String getElementValue() {
return null;
}
}

No comments: