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()) overnull.
Related: Java: ArrayIndexOutOfBoundsException fix Β· Java: OutOfMemoryError fix