NullPointerException in Java

      No Comments on NullPointerException in Java

NullPointerException occurs when an application uses an object reference which has null value and performs operation on it.

e.g. Operations could be :

I.) calling method on Object reference having null value

Object obj = null;
System.out.println(obj.toString()); //throws Exception

II.) Unboxing Wrapper Objects having null value
Integer x = null;
int y = x; //throws Exception

III.) Accessing index of an array which is null.
int x[] = null;
System.out.println(“x[2] = “+x[2]); //throws Exception

IV.) Accessing length property of an array reference having null value
int x[] = null;
System.out.println(“length of x= “+x.length); //throws Exception

There are other scenarios as well where NullPointerException is thrown.

NullPointerException is checked or unchecked Exception??

NullPointerException is a subclass of RuntimeException. All subclasses of RuntimeException is an unchecked exception. Hence, NullPointerException is an unchecked exception.

Demo Program

The below demo prorgam would throw NullPointerException as it tries to autounbox null object.

package com.masterjavatutorial;
public class TestExample {
    public static void main(String[] args){
        Integer number = null;
        int X = number;

Output of the above program is as below:

Exception in thread "main" java.lang.NullPointerException
	at com.masterjavatutorial.TestExample.main(