Skip to main content Skip to docs navigation
TechSpiderTutorials

java.lang.NullPointerException in Java

On this page

Java.lang.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.

NullPointerException Class Example

public class NullPointerExceptionExample {
    public static void main(String[] args) {
        // Create a string reference but do not initialize it (it is null)
        String myString = null;

        try {
            // Attempt to get the length of the null string
            int length = myString.length(); // This will cause NullPointerException
            System.out.println("Length of the string: " + length);
        } catch (NullPointerException e) {
            // Handle the exception
            System.out.println("Error: Cannot call method on a null reference!");
        } finally {
            System.out.println("Execution completed.");
        }
    }
}

Output:

Error: Cannot call method on a null reference!
Execution completed.