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
 System.err.println("This may result in NullPointerException if unknownObject is null");

//right way - avoid NullPointerException even if unknownObject is null
 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"

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


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;

Naveen P.N

12+ years of experience in IT with vast experience in executing complex projects using Java, Micro Services , Big Data and Cloud Platforms. I found NPN Training Pvt Ltd a India based startup to provide high quality training for IT professionals. I have trained more than 3000+ IT professionals and helped them to succeed in their career in different technologies. I am very passionate about Technology and Training. I have spent 12 years at Siemens, Yahoo, Amazon and Cisco, developing and managing technology.