What does NullPointerException mean in Java?
What causes a NullPointerException
In Java, object references can be null, meaning they point to no object. If you try to dereference a null reference — for example, by calling a method, accessing a field, or taking its length — the JVM throws a NullPointerException.
Common scenarios include calling a method on an uninitialized variable, accessing an array element that is null, or getting a null return value from a method and using it without checking.
How to fix and prevent it
First, identify which variable is null. The stack trace tells you the line number. Use a debugger or add print statements to check the value of references before using them.
To prevent NPEs, initialize variables, check for null before dereferencing, or use Java's Optional class. In Java 14 and later, helpful NullPointerExceptions give more detailed messages about which variable was null.
- Initialize object references when you declare them, or assign a default non-null value.
- Use Objects.requireNonNull() to validate parameters.
- Prefer Optional for return values that might be absent.
- Use String.valueOf() instead of toString() on potentially null objects.
- Enable helpful NullPointerExceptions with -XX:+ShowCodeDetailsInExceptionMessages (Java 14+).
Example and stack trace
Consider: String s = null; int len = s.length(); This throws a NullPointerException at the line where s.length() is called. The stack trace shows the class, method, and line number.
In Java 14+, the message might say: 'Cannot invoke "String.length()" because "s" is null.' This makes debugging much faster.
Common mistakes
- Assuming the null variable is the one on the left side of the dot — it could be any part of a chain like a.b.c().
- Catching NullPointerException instead of fixing the root cause, which can hide bugs.
- Believing that an uninitialized object reference is automatically set to a default object — it's null.
