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 that is null.
See the following section to learn how this error is generated 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 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:
The code:
public class error_demo { public static void main(String []args) { Integer Interger_demo = null; int int_pri = Interger_demo.intValue(); System.out.println(int_pri); } }
Output:
You see, the NullPointerException is raised as the null value of the Integer object is assigned to an int type variable.
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.
Below, I used almost the same code as above except that null to the 0 and see the output:
The code:
public class error_demo { public static void main(String []args) { Integer Interger_demo = 0; int int_pri = Interger_demo.intValue(); System.out.println("The NullPointerException is fixed and value of variable is: " +int_pri); } }
Output:
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:
As I try to display the array length by using the System.out.println, the exception is raised as follows:
The code for accessing null array length:
public class error_demo { public static void main(String []args) { String anArray[] = null; System.out.println("The length of String array is: " +anArray.length); } }
Output: