Skip to content
  1. LuzineDebug
  2. Java, Kotlin & .NET
  3. Exception in thread "main" java.lang.NullPointer…
Java, Kotlin & .NET Beginner ≈ 10 min to fix

Fix "java.lang.NullPointerException: Cannot invoke … because … is null" in Java

Error message
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)
In short

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.

Be the first to confirm this fix

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

  1. 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.
  2. Field never initialised: an object field is null by default until a constructor or setter fills it (lists, services, configuration).
  3. Spring injection that does not apply: an @Autowired field in a class created with new (not by Spring), so this.mailService stays null.
  4. Auto-unboxing a null: int total = map.get("x"); throws an NPE on Integer.intValue() when the key does not exist.
  5. Null array or collection element: an object array created with new User[10] without filling the slots.

Step-by-step fix

  1. Read the message and the right line

    The part after because names the null expression. In the stack trace, skip the JDK and framework lines and open the first at line that points to your package: that is where the value is used.

    plaintext
    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)
  2. 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 plain javac on the command line.

    bash
    javac -g -d out src/com/example/App.java
    java -cp out com.example.App
  3. 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.

    java
    public class Cart {
        private final List<Item> items = new ArrayList<>();
    
        public List<Item> getItems() {
            return items; // never null
        }
    }
  4. Handle the "missing" case explicitly

    When absence is normal, make it visible: Optional for a lookup, a default value for a map, Objects.requireNonNull to fail early with a clear message when a parameter is mandatory.

    java
    // 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");
  5. 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.

    java
    @Service
    public class OrderService {
        private final MailService mailService;
    
        public OrderService(MailService mailService) {
            this.mailService = mailService;
        }
    }
    // never: new OrderService() -> inject OrderService where you need it
  6. Check with the debugger

    Set a breakpoint on the reported line, or an "exception breakpoint" on NullPointerException in IntelliJ IDEA / Eclipse / VS Code: execution stops at the exact moment of the error and you can see which variable is null and 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 null for a collection: return List.of() or an empty list; for an optional single value, return an Optional.
  • Annotate your APIs with JSpecify (@NullMarked, @Nullable) and enable static checking (NullAway, IntelliJ) to catch risky dereferences at compile time.
  • Prefer constructor injection with final fields, 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

All Java, Kotlin & .NET errors →