Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

NullPointerException — using null instead of an object

NullPointerException (NPE) signals the use of null where an object is required. It extends RuntimeException, so it does not need to be declared in throws.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new NullPointerException()
new NullPointerException("message")

java.lang.NullPointerException indicates an attempt to use null where an object is needed. Typical causes include invoking an instance method, accessing a field or array element, reading an array's length through a null reference, and throw null.

As a subclass of RuntimeException, it is unchecked: no throws declaration is required. Recommended practice is to trace the missing value and validate or correct the data before use, rather than hide the defect with a broad catch.

The constructors NullPointerException() and NullPointerException(String message) create an exception without an explicit message or with a message. Do not assume fixed wording for JVM-generated messages: getMessage() may return implementation-specific text or null.

In the example, text.length() throws before any length is printed. The catch is only for demonstration and prints fixed text independent of JVM diagnostics.

Examples

public class Main {
    public static void main(String[] args) {
        String text = null;
        try {
            System.out.println(text.length());
        } catch (NullPointerException exception) {
            System.out.println("NullPointerException");
        }
    }
}

Result

NullPointerException

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources