πŸ”§ Error Fixes
Β· 1 min read

Java NullPointerException β€” How to Fix It


java.lang.NullPointerException

You’re calling a method or accessing a field on a null reference.

Why this happens

In Java, object references default to null when not assigned. When you invoke a method, access a field, or index into an array on a null reference, the JVM throws a NullPointerException. Since Java 14+, the error message tells you exactly which variable was null.

Fix 1: Check for null

// ❌ user might be null
String name = user.getName();

// βœ… Check first
if (user != null) {
    String name = user.getName();
}

// βœ… Or use Optional (Java 8+)
Optional.ofNullable(user)
    .map(User::getName)
    .orElse("Unknown");

Fix 2: Initialize your variables

// ❌ Not initialized
String name;
System.out.println(name.length());  // NPE!

// βœ… Initialize
String name = "";

Fix 3: Check return values

// ❌ map.get() returns null if key missing
String value = map.get("key");
value.toUpperCase();  // NPE if key doesn't exist!

// βœ… Use getOrDefault
String value = map.getOrDefault("key", "default");

Alternative solutions

Use Objects.requireNonNull() at method boundaries to fail fast with a clear message:

public void setUser(User user) {
    this.user = Objects.requireNonNull(user, "user must not be null");
}

Use @Nullable/@NonNull annotations with static analysis tools to catch potential NPEs at compile time.

Prevention

  • Enable NPE-related inspections in your IDE to catch issues before runtime.
  • Prefer returning empty collections (Collections.emptyList()) over null.

Related: Java: ArrayIndexOutOfBoundsException fix Β· Java: OutOfMemoryError fix