NullPointerException in Java — What It Means and How to Fix It
What Java's NullPointerException means and how to fix it.
Published November 1, 2026
A NullPointerException (NPE) occurs when code uses an object reference that is null, such as calling a method on it. It is the most common Java runtime exception.
What it means and why it happens
Typical causes: uninitialised fields, a method returning null, missing map entries or auto-unboxing a null Integer.
Read the full message: it names the file and line where the problem was detected, which is the best place to start.
What you see
run the code
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "s" is null
Practical examples
Code that triggers it
String s = null;
int n = s.length();The fix
String s = getName();
int n = (s != null) ? s.length() : 0;
// or
Optional.ofNullable(s).map(String::length).orElse(0);Fail fast
Objects.requireNonNull(user, "user must not be null");Common mistakes
- Returning null instead of empty collections or Optional.
- Auto-unboxing null into int.
- Ignoring helpful NPE messages (Java 14+).
Key takeaways
- NullPointerException: A NullPointerException (NPE) occurs when code uses an object reference that is null, such as calling a method on it.
- Read the message and the line number first.
- Fix the cause, don't just silence the error.
FAQ
How do I find the null?
Modern JVMs name the null variable in the message; check the line in the stack trace.
How do I find which line caused NullPointerException?
The error message and stack trace show the file and line; start there and work backwards.