How to Catch and Fix NullPointerException in Java

May 20th, 2021 • By Rollbar Editorial Team

The java.lang.NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null.

Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

What Causes NullPointerException

The NullPointerException in Java occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

Some of the most common scenarios for a Java NullPointerException are:

  • Calling methods on a null object
  • Accessing a null object’s properties
  • Accessing an index element (like in an array) of a null object
  • Passing null parameters to a method
  • Incorrect configuration for dependency injection frameworks like Spring
  • Using synchronized on a null object
  • Throwing null from a method that throws an exception

NullPointerException Example

Here is an example of a Java NullPointerException thrown when the length() method of a null String object is called:

public class NullPointerExceptionExample {
	private static void printLength(String str) {
	    System.out.println(str.length());
	}

	public static void main(String args[]) {
	    String myString = null;
	    printLength(myString);
	}
}

In this example, the printLength() method calls the length() method of a String without performing a null check prior to calling the method. Since the value of the string passed from the main() method is null, running the above code causes a NullPointerExceptionin Java:

Exception in thread "main" java.lang.NullPointerException
	at NullPointerExceptionExample.printLength(NullPointerExceptionExample.java:3)
	at NullPointerExceptionExample.main(NullPointerExceptionExample.java:8)

How to Fix NullPointerException

To fix the Java NullPointerException in the above example, the string should be checked for null or empty values before it is used any further:

import org.apache.commons.lang3.StringUtils;

public class NullPointerExceptionExample {
	private static void printLength(String str) {
		if (StringUtils.isNotEmpty(str)) {
			System.out.println(str.length());
		} else {
			System.out.println("Empty string");
		}
	}

	public static void main(String args[]) {
	    String myString = null;
	    printLength(myString);
	}
}

The code is updated with a check in the printLength() method that makes sure the string is not empty using the apache commons StringUtils.isNotEmpty() method. Only if the string is not empty the length() method of the string is called, else it prints the message Empty string to console.

How to Avoid NullPointerException

The Java NullPointerException can be avoided using checks and preventive techniques like the following:

  1. Making sure an object is initialized properly by adding a null check before referencing its methods or properties.
  2. Using Apache Commons StringUtils for String operations e.g. using StringUtils.isNotEmpty() for verifying if a string is empty before using it further.
  3. Using primitives rather than objects where possible, since they cannot have null references e.g. using int instead of Integer and boolean instead of Boolean
  4. Writing methods returning empty objects rather than null where possible e.g. empty collections and empty strings

Track, Analyze and Manage Java Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing Java errors easier than ever. Try it today

Get the latest updates delivered to your inbox.