Fix "java.lang.NullPointerException: Cannot invoke … because … is null" in Java
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>" is null at com.example.App.main(App.java:7)
- java.lang.NullPointerException: Cannot invoke "com.example.User.getName()" because the return value of "com.example.UserRepository.findByEmail(String)" is null
- java.lang.NullPointerException: Cannot read field "name" because "user" is null
- java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
- java.lang.NullPointerException: Cannot invoke "com.example.MailService.send(String)" because "this.mailService" is null
- Exception in thread "main" java.lang.NullPointerException at com.example.App.main(App.java:7)
You call a method or read a field on a reference that is null. Since Java 14, the message tells you exactly which expression was null: read the "because … is null" part and the first at line of your own code, then initialise the value or handle the null case before using it.
What this error means
In Java, a variable of an object type holds a reference. When it is null, there is no object behind it: calling a method, reading a field, reading an array length or unboxing a null Integer into an int throws a NullPointerException. Since JDK 14 (JEP 358, enabled by default since JDK 15), "helpful NPEs" state the impossible operation (Cannot invoke "String.length()") and the null expression (because "user" is null, or the return value of ... is null). When the message shows <local1> instead of a name, the class was compiled without local variable names (javac without -g): it is the first local variable of the method.
Common causes
- Method that returns
null:Map.get()on a missing key, a lookup that finds nothing, an API or JSON payload where the field is missing. - Field never initialised: an object field is
nullby default until a constructor or setter fills it (lists, services, configuration). - Spring injection that does not apply: an
@Autowiredfield in a class created withnew(not by Spring), sothis.mailServicestaysnull. - Auto-unboxing a
null:int total = map.get("x");throws an NPE onInteger.intValue()when the key does not exist. - Null array or collection element: an object array created with
new User[10]without filling the slots.
Step-by-step fix
-
Read the message and the right line
The part after
becausenames the null expression. In the stack trace, skip the JDK and framework lines and open the firstatline that points to your package: that is where the value is used.Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "name" is null at com.example.App.greet(App.java:12) <- your code: line 12 at com.example.App.main(App.java:7) -
Get the variable name back
If you see
<local1>or<local4>, recompile with debug information to get the real names. Maven and Gradle do it by default; it is mostly needed with plainjavacon the command line.javac -g -d out src/com/example/App.java java -cp out com.example.App -
Fix it at the source: initialise the value
The most robust fix is that the value cannot be null: initialise fields at declaration or in the constructor, and return an empty collection instead of
null.public class Cart { private final List<Item> items = new ArrayList<>(); public List<Item> getItems() { return items; // never null } } -
Handle the "missing" case explicitly
When absence is normal, make it visible:
Optionalfor a lookup, a default value for a map,Objects.requireNonNullto fail early with a clear message when a parameter is mandatory.// lookup that may find nothing String name = userRepository.findByEmail(email) .map(User::getName) .orElse("Anonymous"); // map with a default value (also avoids unboxing a null Integer) int total = counts.getOrDefault("x", 0); // mandatory parameter: fail early with a clear message this.client = Objects.requireNonNull(client, "client must not be null"); -
Spring case: use constructor injection
If the null field is a service, the class is probably not managed by Spring (created with
new, or missing@Service/@Component). Declare it as a bean and use constructor injection: a mistake then fails at startup instead of causing an NPE later.@Service public class OrderService { private final MailService mailService; public OrderService(MailService mailService) { this.mailService = mailService; } } // never: new OrderService() -> inject OrderService where you need it -
Check with the debugger
Set a breakpoint on the reported line, or an "exception breakpoint" on
NullPointerExceptionin IntelliJ IDEA / Eclipse / VS Code: execution stops at the exact moment of the error and you can see which variable isnulland where it comes from.
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Never return
nullfor a collection: returnList.of()or an empty list; for an optional single value, return anOptional. - Annotate your APIs with JSpecify (
@NullMarked,@Nullable) and enable static checking (NullAway, IntelliJ) to catch risky dereferences at compile time. - Prefer constructor injection with
finalfields, and validate inputs (JSON, forms) with Bean Validation (@NotNull).
Frequently asked questions
Why does the message show "<local1>"?
The class was compiled without the local variable table, so the JVM only knows their index. Recompile with javac -g (Maven and Gradle enable it by default) to see the real name.
Should I wrap the code in a try/catch NullPointerException?
No: catching an NPE hides the bug and leaves the object in an inconsistent state. Fix the cause (uninitialised value, unhandled absence) or check for null explicitly where it is an expected case.
Why do I not get the detailed "because … is null" message?
You are on a JDK older than 14, or the -XX:-ShowCodeDetailsInExceptionMessages option is set. Move to a recent JDK (21 or 25 LTS) to get detailed messages.
Useful tools for this error
More Java, Kotlin & .NET errors
- Fix "UnsupportedClassVersionError: compiled by a more recent version of the Java Runtime"
- Fix "Could not resolve all files for configuration" and "Could not find" in Gradle
- Fix "Web server failed to start. Port 8080 was already in use" in Spring Boot
- Fix "Failed to configure a DataSource: 'url' attribute is not specified" in Spring Boot
- Fix "java.lang.OutOfMemoryError: Java heap space" (and GC overhead limit exceeded)
- Fix "Object reference not set to an instance of an object" (NullReferenceException) in C#
- Fix "lateinit property binding has not been initialized" in Kotlin (Android)