Ads by ProfitSence

NullPointerException, and fix it.

Last Updated on Wednesday 5th Oct 2022


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



Avoid returning null from your methods

					List<string> data = null;

public List getDataDemo()
   if(data == null)
      return Collections.EMPTY_LIST; //Returns unmodifiable list
   return data;