java.lang.NullPointerException
Code called a method or accessed a field on a reference that is null.
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+)
text
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 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.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 2 Oct 2026