Exception in thread "main" java.lang.NullPointerException

Quick answer

You dereferenced a reference whose value was null — called a method, read a field, indexed an array, or unboxed it. On Java 14+ the message names exactly what was null ("Cannot invoke ... because ... is null"); read that phrase, then make that reference non-null or guard it before use.

The exact error string

Exception in thread "main" java.lang.NullPointerException:
    Cannot invoke "String.length()" because "name" is null
        at com.example.App.main(App.java:7)

(On JDK 8–13 you get just java.lang.NullPointerException with the stack trace — no "because ..." detail.)

How to read the helpful message (Java 14+)

The detail message has a fixed shape: "Cannot <action> because <expression> is null." The action tells you the operation (invoke a method, read/assign field, load from array, etc.), and the expression names the exact thing that was null — a local, a field, or even the return value of "Map.get(Object)". That expression is what you check.

Cause 1: method called on a null reference

String name = null;
int n = name.length();   // ❌ Cannot invoke "String.length()" because "name" is null

// ✅ guard, or guarantee non-null
if (name != null) {
    int n = name.length();
}

Cause 2: a lookup returned null (Map / JSON field)

Map<String, String> cfg = new HashMap<>();
String host = cfg.get("host").trim();  // ❌ get() returned null for a missing key

// ✅ supply a default instead of dereferencing null
String host = cfg.getOrDefault("host", "localhost").trim();

// ✅ or model an optional JSON field
Optional.ofNullable(cfg.get("host"))
        .map(String::trim)
        .ifPresent(this::connect);

Cause 3: auto-unboxing a null wrapper

Map<String, Integer> counts = new HashMap<>();
int c = counts.get("x");   // ❌ get() is null -> unboxing null Integer to int

// ✅ check, or use a primitive default
int c = counts.getOrDefault("x", 0);

Cause 4: uninitialized object field

class Cart { List<Item> items; }       // field defaults to null

Cart cart = new Cart();
cart.items.add(item);   // ❌ Cannot invoke "List.add" because "this.items" is null

// ✅ initialize the field
class Cart { List<Item> items = new ArrayList<>(); }

Common causes at a glance

Message fragmentWhat was nullFix
Cannot invoke "...()"the receiver referencenull-check / ensure non-null
because the return value of "Map.get"missing map keygetOrDefault / check
Cannot read field "..."the object holding the fieldinitialize the object
Cannot load from ... arraythe array referenceallocate the array first
unboxingnull wrapper (Integer/Long...)primitive default

Debugging checklist

Frequently Asked Questions

What causes java.lang.NullPointerException?

You used a reference whose value was null as if it pointed to an object — calling a method on it, reading or writing a field, indexing an array, or unboxing it to a primitive. There was no object there, so the JVM throws NullPointerException.

How do I read the Java 14+ helpful NullPointerException message?

Since JDK 14 (on by default from JDK 15) the message names exactly what was null, e.g. Cannot invoke "String.length()" because "<local1>" is null or because the return value of "Map.get(Object)" is null. That phrase points straight at the expression to check.

Why is my NPE message just a stack trace with no detail?

You're on JDK 8–13, or helpful messages are disabled. Read the top stack frame's file:line, then look at that line for the reference being dereferenced. On JDK 14 enable it with -XX:+ShowCodeDetailsInExceptionMessages; from JDK 15 it's the default.

How do I fix a NullPointerException?

Find which reference is null (the helpful message or the stack line tells you), then either guarantee it's non-null before use, guard with an if (x != null) check, supply a default with Optional/Objects.requireNonNullElse, or fix the upstream code that returned null.

Why does Map.get or a JSON field return null and NPE?

Map.get returns null for a missing key, and JSON parsers return null for absent/null fields. Chaining a method on that result (map.get(k).trim()) throws. Use getOrDefault, check for null, or model optional fields with Optional before dereferencing.

Does Optional eliminate NullPointerException?

Optional makes "might be absent" explicit and gives safe operations (map, orElse), which prevents many NPEs — but only if you don't call .get() on an empty Optional. It's a tool for API design, not a blanket guarantee against null.

More language & runtime errors

Browse the full reference for Java, Go, Node.js, Python, and database errors — exact message, cause, and fix.

All Error References JS: Cannot read properties of null Python: NoneType has no attribute
About the author

Pasindu Ishan is a software developer based in Sri Lanka. He builds privacy-first developer tools at JSON Dev Tools.