You are currently viewing How to Fix NullPointerException In Java

How to Fix NullPointerException In Java

1. Introduction

NullPointerException is probably the first Exception you’ll see if you are a fresher in Java programming. In this tutorial, you will learn how to fix it. You will also learn some best practices to follow to avoid that exception.

2. What Java Says about NullPointerException

From the Javadoc, a NullPointerException is thrown if any of the following conditions are met:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Next, let’s see how to reproduce a NullPointerException.

3. How to Reproduce

3.1. Calling the instance method of a null object

In the following code, we are invoking the Strring.concat() method on a null object (firstName).

        String firstName = null;//null object
        String lastName = "Doe";
        String fullName =  firstName.concat(lastName);// NullPointerException

Output

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.concat(String)" because "firstName" is null
    at Scratch.main(scratch.java:5)

To fix the issue, you must initialize the firstName variable with a non-null value:

        String firstName = "John ";
        String lastName = "Doe";
        String fullName = firstName.concat(lastName);

Unboxing of Wrapper Classes
Unboxing is the process of converting an object of a Wrapper type (Integer, Double, Boolean, etc.) to its corresponding primitive type. You should be aware that this process may produce a NullPointerException in some situations.
Have a look at the code below:

        Integer i = null;
        boolean isZero = i == 0;

This code produces the following output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "i" is null
    at Scratch.main(scratch.java:4)

As you can see, unboxing from Integer to int is equivalent to calling the method Integer.intValue(). Since the Integer object is null, a NullPointerException is raised.

3.2. Accessing or modifying the field of a null object

The code below attempts to modify the firstName attribute of a null object.

        Student student = null;//null object
        student.firstName = "John";//NullPointerException

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot assign field "firstName" because "student" is null
    at Scratch.main(scratch_2.java:18)

To solve the error, you must create an instance of the Student class:

        Student student = new Student();
        student.firstName = "John";

3.3. Taking the length of null as if it were an array

The code below is trying to compute the sum of an array of integers. However, the array on which it is being performed is not initialized. Therefore, a NullPointerException is raised.

        int[] nullableArray = null;//null array
        int sum = 0;
        for(int i=0; i < nullableArray.length; i++){//NullPointerException
            sum += nullableArray[i];
        }

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "nullableArray" is null
    at Scratch.main(scratch.java:4)

To fix this exception, you simply have to initialize the array in this way:

        int[] initializedArray = new int[5];//initializing the array by specifying its size
        int sum = 0;
        for(int i=0; i < initializedArray.length; i++){//No NullPointerException
            sum += initializedArray[i];
        }

3.4. Accessing or modifying the slots of null as if it were an array

Another common source of NullPointerException is attempting to load or modify a slot of a null array. The code below is trying to load the first element of a null array:

        int[] nullableArray = null;//null array
        int firstElement = nullableArray[0];//NullPointerException

Running the code above produces a NullPointerException:

Exception in thread "main" java.lang.NullPointerException: Cannot load from int array because "nullableArray" is null
    at Scratch.main(scratch.java:4)

Just like in the previous example, you must initialize the array to solve this exception:

        int[] initializedArray = new int[5];//initializing the array by specifying its size
        int firstElement = initializedArray[0];//No NullPointerException

3.5. Throwing null as if it were a Throwable value

Calling the method below with a null student object will result in a NullPointerException:

    private void displayStudentName(Student student) throws Exception {
        Exception ex = null;
        if(null != student){
            System.out.printf("Student's name is : %s %s",student.firstName(),student.lastName());
        }else{
            throw ex;//ex is null => NullPointerException
        }
    }

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot throw exception because "ex" is null
    at Scratch.displayStudentName(scratch.java:19)
    at Scratch.main(scratch.java:3)

To fix this, you should create a new instance of the Exception class in this way:

    private void displayStudentName(Student student) throws Exception {
        if(null != student){
            System.out.printf("Student's name is : %s %s",student.firstName(),student.lastName());
        }else{
            throw new Exception("Student object is null");//do this
        }
    }

4. Best Practices to Avoid NullPointerException

4.1. Always initialize variables to a Default Value

Depending on their type, you should always initialize your variables to a default value.

        String string = "";
        BigDecimal bigDecimal = BigDecimal.ZERO;
        List<Student> students = new ArrayList<>();

4.2. Check for null before accessing

Always perform a null-check on variables you receive as an input parameter of your method.

    private void printStudentName(Student student){
        if(null != student){//null check
            System.out.printf("Student's name is : %s %s",student.firstName(),student.lastName());
        }else{
            System.out.println("Student object is null");
        }
    }

4.3. Avoid returning null

Returning null is a common source of NullPointerException. Whenever you do it in one of your methods, the caller needs to perform a null-check. To avoid that, you should always return a default non-null value. Depending on the return type of your method, it might be an empty list, an empty String, an Optional, or any other type.

    private List<String> findStudentByCourse(String course){
        if(null == course || course.isEmpty()){
            return Collections.emptyList(); //Don't return null here
        }
        //...Continue
    }

4.4. Code defensively

You should not rely solely on null-checks to prevent NullPointerException. It’s better to adopt a defensive programming style. A popular approach is to prefer the Yoda syntax.
The Yoda style recommends always to put a string literal or a constant value to the left side of an operation:

        String nullableString = null;
        boolean isEmpty =  "".equals(nullableString); // No NullPointerException (string literal to the left side)
        BigDecimal nullableBigDecimal = null;
        int test = BigDecimal.ZERO.compareTo(nullableBigDecimal); // No NullPointerException (constant value to the left side)

5. Conclusion

In this brief tutorial, you learned about the NullPointerException and how to fix it.

Noel Kamphoa

Experienced software engineer with expertise in Telecom, Payroll, and Banking. Now Senior Software Engineer at Societe Generale Paris.