java.lang.NullPointerException
Code called a method or accessed a field on a reference that is null.
Attempt to invoke virtual method on a null object reference Meaning
Since Java 14, helpful NPE messages tell you exactly what was null: Cannot invoke "String.length()" because "name" is null. Read that message and the first stack frame in your own package.
Common causes
- Uninitialized field or variable
- Method returned null (map lookup, repository find)
- Dependency injection didn’t populate a field (
@Autowiredon anew-created object) - Auto-unboxing a null
Integertoint - Android: view not found (
findViewByIdreturns null) or used after destroy
⚡ Quick fix
- Read the “because X is null” part of the message
- Find the first stack frame in your code
- Return
Optionalor empty collections instead of null - Validate inputs with
Objects.requireNonNull(x, "x")
Detailed fix by platform
Java
- Optional instead of null checks:java
String city = Optional.ofNullable(user) .map(User::getAddress) .map(Address::getCity) .orElse("Unknown");
Android
- In Kotlin, prefer non-null types and
?./?:; in Java, annotate with@Nullable/@NonNullso lint warns you.
Code examples
Helpful NPE message (Java 14+)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "name" is null
at com.example.App.greet(App.java:12)How to diagnose
- Message — What is null (Java 14+ tells you)?
- Frame — First frame in your package
- Origin — Where should the value have been set?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
Most viewed in Java
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 15 Oct 2026