NullPointerException in Java: Causes and Real Fixes

NullPointerException in Java: Causes and Real Fixes

TL;DR: NPE happens when you dereference null. Prevent it with constructor invariants, validation, @NotNull annotations, Optional for returns, and empty collections instead of null. Add tests that exercise null paths so failures are obvious.

What is a NullPointerException

Java throws it when code tries to access a member or call a method on null. Typical sources:

  • Uninitialized fields or constructor parameters.
  • DTOs from APIs with optional or missing fields.
  • Map lookups that do not find a key and return null.
  • Libraries that return null for performance or legacy reasons.

Prevention checklist

Constructor invariants

public final class User {
  private final String id;
  private final String name;

  public User(String id, String name) {
    if (id == null || name == null) throw new IllegalArgumentException("id and name required");
    this.id = id;
    this.name = name;
  }
}

Bean validation and annotations

class Command {
  @javax.validation.constraints.NotNull
  String userId;
}

public void handle(@org.jetbrains.annotations.NotNull Command cmd) {
  // ... static analysis can flag violations
}

Optional for return types, not fields

Optional<User> findById(String id) {
  // wrap absence instead of returning null
}

String displayName(User u) {
  return Optional.ofNullable(u.getName()).orElse("Guest");
}

Empty collections over null

List<Item> items = json.getItems();
if (items == null) items = java.util.Collections.emptyList();

Mapping layers with defaults

class ItemDto { String id; String title; }
class Item { String id; String title; }

Item map(ItemDto dto) {
  String id = dto != null && dto.id != null ? dto.id : "unknown";
  String title = dto != null && dto.title != null ? dto.title : "Untitled";
  Item i = new Item();
  i.id = id; i.title = title;
  return i;
}

Testing for null safety

  • Write unit tests that pass null to public boundaries and verify behavior.
  • Fuzz JSON deserialization with missing fields and wrong types.
  • Use mutation testing or coverage on the null paths.

Observability

  • Log with context, not just stack traces. Include ids and sizes.
  • Use structured logs so dashboards can filter by null-causing fields.

FAQ

When should I use Optional
Use Optional for return values to model absence. Avoid Optional fields and parameters.

Is using Optional everywhere a good idea
No. Use it where a value is genuinely optional. For required values, validate early and fail fast.

How do I test for null safety
Target constructors, mappers, and service boundaries. Create tests that pass null and assert a clear, handled outcome.

Cast this in your project

Photo by Pixabay: https://www.pexels.com/photo/empty-subway-train-302428/

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.