NullPointerException, and fix it.

Last Updated On Monday 30th May 2022

java.lang.nullpointerexception

A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference.

	public class Test {
    public static void main(String[] args) {
        String foo = null;
        int length = foo.length();   // HERE
    }
}
	

null pointer exception java

Ternary Operator

  • This operator results in the value on the left-hand side if the not null else, the right-hand side is evaluated.
	String str = (param == null) ? "NA" : param;
	

Check Method Arguments for null very early

  • You should always put input validation at the beginning of your method.
  • So that the rest of your code does not have to deal with the possibility of incorrect input.
  • So if someone passes in a null, things will break early in the stack rather than in some deeper location

Carefully Consider Chained Method Calls

	ref.method1().method2().method3().methods4();
	

Avoid returning null from your methods

	List<string> data = null;

@SuppressWarnings("unchecked")
public List getDataDemo()
{
   if(data == null)
      return Collections.EMPTY_LIST; //Returns unmodifiable list
   return data;
}