Blog |

How to Catch and Fix NullPointerException in Java

How to Catch and Fix Null<wbr>Pointer<wbr>Exception in Java
Table of Contents

The java.lang.NullPointerException is a runtime exception in Java that occurs when trying to use a variable that does not point to an object and refers to nothing or null.

To use an analogy, it’s like trying to send a letter without specifying the recipient's address. Without an address, the letter cannot be delivered. Similarly, if a variable in Java doesn't point to an actual object, the program gets confused and throws a NullPointerException.

What Causes NullPointerException

The NullPointerException occurs when an uninitialized variable is used. Such a variable has no object reference and does not point anywhere. Therefore, it has a null value in Java and using it throws a NullPointerException.

Some of the most common scenarios for a 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 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()); //Trying to call a method on a null object
    }

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

In this example, the length() method of a String object is called without performing a null check. Since the value of the string passed from the main() method is null, running the above code causes a NullPointerException:

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

How to Avoid NullPointerException

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

  • Making sure an object is initialized properly before it is used. This can be done by checking whether an object is null or not before referencing its methods or properties. For example:
    if (myObject != null) {
    System.out.println(myObject.toString()); //Using object if not null
    } else {
    System.out.println("Object is null");
    }
  • Using Apache Commons StringUtils for String operations. For example, using StringUtils.isNotEmpty() for verifying if a string is not null or empty before using it further.
  • Using primitives rather than objects where possible. For example, int instead of Integer and boolean instead of Boolean. In Java, primitives cannot have null values.
  • Writing methods that return empty objects rather than null where possible. For example, returning empty collections and empty strings from a method.

To fix the NullPointerException in the earlier example, the String object 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)) { //Check to ensure not null or empty
            System.out.println(str.length());
        } else {
            System.out.println("Empty string");
        }
    }

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

The code here is updated with a check in the printLength() method that ensures the string is not null or empty using the apache commons StringUtils.isNotEmpty() method. This check avoids the NullPointerException since the length() method of the string is called only if it is not null or empty. Otherwise, the message Empty string is printed to the console.

Track, Analyze and Manage 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 error monitoring and triaging, making fixing Java errors easier than ever. Try it today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape