How to resolve a NullPointerException in Java?


A NullPointerException is a runtime exception thrown by the JVM when our application code, other referenced API or the middleware encounters the following conditions.

  • Attempting to invoke an instance method of a null object.

  • Attempting to access or modify a particular field of a null object.

  • Attempting to obtain the length of a null object as an array.

Steps to resolve NullPointerException

  • Review the java.lang.NullPointerException stack trace and determine where the Exception is triggered (Application code, third-party API, middleware software and extract the line).

  • If the problem is at the application code then a code walk-through will be required. If the problem is found from third-party API or middleware, need to first review the referenced code and determine if it could indirectly be the source of the problem, for instance, passing a null value to a third party API method, etc.

  • If problem found within the application code, then attempt to determine which Object instance is null and causing the problem. We need to modify the code in order to add proper null check validations and proper logging so we can understand the source of the null value as well.

Example

public class NPEDemo {
   private String field1 = null;
   private String field2 = null;
   public String getField1() {
      return field1;
   }
   private void setField1(String field1) {
      this.field1 = field1;
   }
   public String getField2() {
      return field2;
   }
   private void setField2(String field2) {
      this.field2 = field2;
   }
   public static void main(String[] args) {
      try {
         NPEDemo npe = new NPEDemo();
         npe.setField1("field1 value");
         npe = null;
         npe.setField2("field2 Value");
      } catch (Throwable e) {
         System.out.println("Java Error is: "+e );
         e.printStackTrace();
      }
   }
}

Output

Java Error is: java.lang.NullPointerException
java.lang.NullPointerException
	at NPEDemo.main(NPEDemo.java:21) 

Updated on: 21-Nov-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements