NullPointerException
NullPointerException — NPE — is thrown when your code tries to use a reference that is null as if it pointed to an object. It is the most common runtime exception in Java, nicknamed "the billion-dollar mistake" after Tony Hoare called out the null reference concept he introduced.
Typical triggers
String s = null;
s.length(); // NPE
int[] arr = null;
int x = arr[0]; // NPE
arr.length; // NPE
Map<String, User> m = getMap();
m.get("missing").getName(); // NPE if key not present (get returns null)
// Auto-unboxing a null Integer:
Integer boxed = null;
int n = boxed; // NPE
Helpful NullPointerExceptions (Java 14+)
Run with -XX:+ShowCodeDetailsInExceptionMessages (default on recent JVMs) and the message tells you exactly which reference was null:
Cannot invoke "String.length()" because "s" is null
Avoiding NPE
- Return
Optionalinstead of null from methods that might not find a value. Objects.requireNonNull(arg)at method entry to fail fast.getOrDefault/computeIfAbsenton Maps instead ofget.- Nullability annotations (
@Nullable,@NonNullfrom JetBrains or JSpecify) + static analysis. - Don't return null collections — return an empty
List.of()/Set.of()instead.
Catching NPE
Don't. NPE almost always indicates a bug — catching it hides the bug. The correct fix is to ensure the variable is not null before dereferencing, or use Optional.