Hit enter after type your search item

java.lang.nullpointerexception error and fixing with 3 examples

What is java.lang.NullPointerException?

The java.lang.NullPointerException is an error in Java that occurs as a Java program attempts to use a null when an object is required.

The NullPointerException is a public class that extends the RuntimeException.

The NullPointerException is thrown for different scenarios, for example, if you call the instance method of an object which is null.

Similarly, if an object is null and you try to access or modify the field of that null object, this error will occur. The exception will also be thrown if you try to take the length of an array which is null.

See the following section for learning how this error generates and how you may fix it.

An example of generating java.lang.NullPointerException with integer object

In this simple example, an instance of the Integer class is created and assigned it null. An int type (primitive) variable is declared and this is assigned the instance method of that null Integer object. See the output and code:


See online demo and code

The code:

You see, the NullPointerException is raised as the null value of Integer object is assigned to an int type variable.

Also, note that the error will generate for Integer object. If you declare a variable with the primitive type like int in above example without assigning a value, the error will not generate. As such, the default value for an int type variable is 0.

How to fix this error in above example?

Simply assign a value to the Integer object before assigning it to the primitive type int variable. See almost the same code where I changed the null to the zero in above code and see the output:

java-lang-nullpointerexception fixed

See online demo and code

The code:

An example of null array

In this example, the java.lang.NullPointerException is raised as the length of a String array is accessed which is set as null. This is how the String array is declared:

String anArray[] = null;

As I try to display the array length by using the System.out.println, the exception is raised as follows:

java-lang-nullpointerexception array

See online demo and code

The code for accessing null array length:


To avoid that error in an array, you should initialize an array before using the length method.

This div height required for enabling the sticky sidebar