SoftwareSideHustles
Debugging

How to Fix a NullPointerException in Java (and Stop Getting Them)

Read Java's helpful NullPointerException messages, find which reference was null, fix the eight most common causes — from Map.get unboxing to Spring beans created with new — and design nulls out of your code.

By Software Side Hustles Editorial Team · Published · Updated · 4 min read

Quick answer: a NullPointerException (NPE) means you used a reference that points to nothing — calling a method, reading a field or unboxing a value on null. Since Java 14, the message tells you exactly which reference: Cannot invoke "String.length()" because "name" is null. Go to that line, find where that variable got its value, and fix the source: initialise it, handle the "not found" case, or make the method return something other than null.

Reading a modern NullPointerException message

text
Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "String.length()" because "name" is null
at com.example.Greeter.greet(Greeter.java:12)
at com.example.Main.main(Main.java:5)
  • What failed: calling String.length().
  • On what: the variable name.
  • Where: Greeter.java, line 12, inside greet.

These "helpful NullPointerExceptions" (JEP 358) are on by default since Java 15. If you see "<local1>" instead of a variable name, the class was compiled without debug information; compile with -g (most build tools do by default for development) to get names.

For chained calls, the message pinpoints the link:

text
Cannot invoke "Address.getCity()" because the return value of "Customer.getAddress()" is null

So customer.getAddress() returned null — the bug is in why that customer has no address, not in getCity().

On Java 8 to 13 you only get a line number. Split chained expressions onto separate lines, or use a debugger, to see which part is null.

The eight most common causes

1. Unboxing a null wrapper

java
Map<String, Integer> counts = new HashMap<>();
int c = counts.get("missing");
// Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null

Map.get returns null for a missing key, and assigning null to an int calls intValue() on it. Use counts.getOrDefault("missing", 0) or keep the result as Integer and check it. See checking if a key exists.

2. Fields that were never initialised

java
class Cart {
private List<Item> items; // null until assigned
void add(Item i) { items.add(i); } // NPE
}

Initialise collections where you declare them: private final List<Item> items = new ArrayList<>();.

3. Methods that return null for "not found"

repository.findByEmail(email).getName() fails when there is no such user. Return Optional<User> and make callers decide: findByEmail(email).map(User::getName).orElse("Guest"), or throw a meaningful exception (orElseThrow(() -> new UserNotFoundException(email))).

4. Spring beans created with new

java
@Service
class ReportService {
@Autowired private OrderRepository orders; // injected only by Spring
}
new ReportService().build(); // orders is null — Spring never saw this object

Dependency injection only happens for objects Spring creates. Inject ReportService where you need it instead of calling new. Prefer constructor injection — with final fields, a missing dependency fails at start-up rather than at the first request.

5. Arrays of objects

String[] names = new String[3]; contains three nulls, not three empty strings. names[0].trim() throws.

6. String comparisons in the wrong order

java
if (input.equals("yes")) // NPE when input is null
if ("yes".equals(input)) // false when input is null

Or use Objects.equals(a, b), which handles nulls on either side.

7. Data from outside the program

JSON fields that are absent, database columns that allow NULL, environment variables that are not set (System.getenv("API_KEY") returns null), request parameters. Validate at the boundary — with Bean Validation (@NotNull), explicit checks or a fail-fast configuration class — so nulls do not travel deep into your code.

8. Auto-closing and switch on null

switch (status) on a null enum or String throws an NPE before any case runs (pattern-matching switch in Java 21 can handle case null explicitly). Similarly, iterating a null collection with an enhanced for loop throws.

How to prevent NullPointerExceptions

  • Return empty collections, not null. List.of() is free; callers can loop without checks.
  • Use Optional for return values that may be absent — not for fields or parameters.
  • Fail fast at boundaries: this.repo = Objects.requireNonNull(repo, "repo"); turns a mysterious NPE later into a clear message now.
  • Annotate nullability (@Nullable, JSpecify, or your framework's annotations) and let IntelliJ, NullAway or the Checker Framework flag unsafe dereferences at compile time.
  • Prefer immutable objects constructed in a valid state — records with validated constructors — so fields cannot be null later.
  • Consider Kotlin for new modules: its type system separates String from String?.

What not to do

java
try {
process(order);
} catch (NullPointerException e) {
// ignore
}

Catching NPEs hides bugs and can leave data half-processed. Likewise, adding if (x != null) everywhere without asking why x is null spreads defensive noise through the codebase. Decide, for each value, whether null is a legal state. If it is, model it (Optional, a default); if it is not, reject it early.

Frequently asked questions

Is NullPointerException a checked exception?

No. It is a RuntimeException, so the compiler does not force you to handle it — which is why static analysis and annotations help.

How do I find which variable is null on Java 8?

Split the line so each dereference is on its own line, or set a breakpoint and inspect the variables. Upgrading to a supported LTS (17 or 21) gives you the helpful messages automatically.

Should I use Optional.get()?

Rarely. It throws NoSuchElementException when empty — an NPE by another name. Use orElse, orElseGet, orElseThrow with a message, map or ifPresent.

Where this skill pays off

Our free code review lab and the Java exercise in the response evaluation lab both test whether you notice missing null and edge-case handling in AI-written code. That eye for "what happens when this is absent?" is what AI training platforms pay experienced developers for — read how to prepare for technical AI evaluation work.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy