BackendBench
Coffee

Home โ€บ Java exceptions โ€บ NullPointerException

Unchecked exception ยท java.lang

NullPointerException: causes and fixes

A null reference was used where an object was needed: a method call, field access, unboxing or array access on null.

What it looks like

java.lang.NullPointerException: Cannot invoke "String.length()" because "name" is null

Extends RuntimeException in java.lang.

What it means

The JVM throws NullPointerException when code treats null as if it were an object: calling a method on it, reading or writing a field, taking the length of a null array, throwing null, or unboxing a null Integer into an int. Since Java 14 the message says exactly which expression was null, for example because "order.getCustomer()" is null, which usually points straight at the bug.

Common causes

How to fix it

  1. Read the helpful message first: it names the null variable or method call.
  2. Return Optional from methods that can legitimately have no result, and handle the empty case.
  3. Validate arguments at the start of a method with Objects.requireNonNull(x, "x") so the failure is near the cause.
  4. Initialise collections and fields, and let Spring create beans instead of calling new on them.

Broken and fixed

fails
String name = map.get("user");
int len = name.length(); // NPE when "user" is absent
works
String name = map.getOrDefault("user", "");
int len = name.length();

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

In Spring, a null autowired field almost always means the object was not created by the container (a new call, or a class outside component scanning). In JPA, a null association can mean it was never loaded or set.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is NullPointerException a checked or unchecked exception?

NullPointerException is an unchecked exception (it extends RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.

Which package is NullPointerException in?

It lives in java.lang, so the import is import java.lang.NullPointerException; (java.lang needs no import).

What is the first thing to check when I see NullPointerException?

Read the message and the first stack trace line in your own code. The usual causes are: A method returned null (a map lookup, a repository findBy that found nothing, a JSON field that was missing); and A field was never initialised, or a dependency was not injected because the object was created with new instead of by Spring.

Related exceptions

More tools you might need