Best practices to avoid NullPointerException

Call equals() and equalsIgnoreCase() method on known String

Always call equals() method on known String which is not null. Since equals() method is symmetric, calling a.equals(b) is same as calling b.equals(a), and that’s why many programmer don’t pay attention on object a and b. One side effect of this call can result in NullPointerException, if caller is null.


Object unknownObject = null;

//wrong way - may cause NullPointerException
if(unknownObject.equals("knownObject")){
 System.err.println("This may result in NullPointerException if unknownObject is null");
}

//right way - avoid NullPointerException even if unknownObject is null
if("knownObject".equals(unknownObject)){
 System.err.println("better coding avoided NullPointerException");
}

Prefer valueOf() over toString() where both return same result

Since calling toString() on null object throws NullPointerException, if we can get same value by calling valueOf() then prefer that, as passing null to  valueOf() returns “null”, specially in case of wrapper classes  like Integer, Float, Double or BigDecimal.


BigDecimal bd = getPrice();
System.out.println(String.valueOf(bd)); //doesn’t throw NPE
//throws "Exception in thread "main" java.lang.NullPointerException"
System.out.println(bd.toString()); 

Using null safe methods and libraries

There are lot of open source library out there, which does the heavy lifting of checking null for you. One of the most common one is StringUtils from Apache commons. You can use StringUtils.isBlank(), isNumeric(), isWhiteSpace() and other utility methods without worrying of  NullPointerException.


//StringUtils methods are null safe, they don't throw NullPointerException
System.out.println(StringUtils.isEmpty(null));
System.out.println(StringUtils.isBlank(null));
System.out.println(StringUtils.isNumeric(null));
System.out.println(StringUtils.isAllUpperCase(null));

Output:
true
true
false
false

Avoid returning null from method, instead return empty collection or empty array.

This Java best practice or tips is also mentioned by Joshua Bloch in his book Effective Java which is another good source of better programming in Java. By returning empty collection or empty array you make sure that basic calls like size(), length() doesn’t fail with NullPointerException. Collections class provides convenient empty List, Set and Map as Collections.EMPTY_LIST, Collections.EMPTY_SET and Collections.EMPTY_MAP which can be used accordingly.


public List getOrders(Customer customer)
{
   List result = Collections.EMPTY_LIST;
   return result;
}