Java Reference ยท java.lang
NullPointerException
Reference for NullPointerException: every way it is thrown, how to read helpful NPE messages, Objects.requireNonNull, Optional and defensive habits.
NullPointerException (NPE) is thrown when code uses null where an object is required. It is the most common runtime exception in Java. It extends RuntimeException, so it is unchecked.
The JVM throws it when you call an instance method on null, read or write a field of null, take the length of or index into a null array, throw a null reference, synchronize on null, or unbox a null wrapper such as an Integer. Library code also throws it deliberately to reject null arguments.
String name = null; name.length(); // throws NullPointerException
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public class NullPointerException extends RuntimeException
| Constructor | Description |
|---|---|
NullPointerException() |
No message. The JVM may still compute a helpful one. |
NullPointerException(String message) |
Explicit message, as Objects.requireNonNull(x, "msg") does. |
Usage notes
- Helpful NPE messages (Java 14+, on by default since 15). For JVM-thrown NPEs,
getMessage()describes what was null, for exampleCannot invoke "String.length()" because "<local1>" is null. Local variable names appear only when the class was compiled with-g; otherwise (including the source launcher these examples run under) they show as<local1>-style placeholders. Fields, method calls and array accesses are described by name. - Auto-unboxing.
int n = map.get(key);throws if the key is absent. UsegetOrDefault()or check first. - Fail early. Call
Objects.requireNonNull(arg, "message")at the top of constructors and public methods so the stack trace points at the real culprit. - Compare constants first:
"yes".equals(input)never throws, whileinput.equals("yes")can. - Return empty, not null. Prefer empty collections and arrays, and
Optionalfor "maybe no result" return types. Do not useOptionalfor fields or parameters. - Switch and for-each.
switchon anullselector throws unless acase nullexists (Java 21+); a for-each over anullcollection or array throws. - Catching an NPE to continue hides the bug. Fix the cause, or validate the input.
- Annotations such as
@Nullablefrom third-party libraries document intent and let tools warn, but the JDK itself does not enforce them.
Related
- null, Objects, Optional, Autoboxing, RuntimeException
- Lessons: Optional, Exception best practices