NullPointerException Java Example

This Java example demonstrates the usage of NullPointerException class and when does this exception occur with a simple example.
The object of NullPointerException class thrown when an application attempts to use null in a case where an object is required. 
These include:
  • 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.
Applications should throw instances of this class to indicate other illegal uses of the null object. NullPointerException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.

NullPointerException Class Diagram

Java NullPointerException Example

In below example, the person object is null and we are invoking its fields on null object leads to NullPointerException.
package com.javaguides.corejava;

public class NullPointerExceptionExample {

    public static void main(String[] args) {

        Person personObj = null;
        try {
            String name = personObj.personName; // Accessing the field of a null object
            personObj.personName = "Ramesh Fadatare"; // Modifying the field of a null object
        } catch (NullPointerException e) {
            System.err.println("NullPointerException caught!");
            e.printStackTrace();
        }

    }
}

class Person {

    public String personName;

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }
}
Output:
NullPointerException caught!
java.lang.NullPointerException
 at com.javaguides.corejava.NullPointerExceptionExample.main(NullPointerExceptionExample.java:9)

How to fix java.lang.NullPointerException

Below articles explained very well about a fix for NullPointerException:

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course