What is a NullPointerException in Java, which operations raise it, and how do you prevent it rather than catch it?
answer
- null where an object is needed
- holding null versus using it
- instance members, not static ones
- hidden uses: unboxing, for-each, switch
- reject early, stop returning null
basics
~20 sNullPointerException is the unchecked exception thrown when null is used where an object is required, as in calling an instance method, reading an instance field or unboxing. Prevent it by rejecting null early and not returning null, rather than catching it.
solid answer
~50 s`NullPointerException` is an unchecked `RuntimeException`, thrown when `null` is used where an object is required. Calling an instance method, reading or writing an instance field or array element, reading an array's `length` and `throw null` all raise it. Less obvious cases are unboxing a null wrapper, for-each over null, `synchronized` on a null reference and `switch` on null with no `case null`. APIs also throw it on purpose, as `Objects.requireNonNull` does, and `List.of(s)` when `s` is null. Static members through a null reference, `"x=" + s` and `s instanceof String` do not throw. Prevent it by rejecting null at constructors and method entries, so the failure names its cause, by returning empty collections or `Optional` instead of null, and by using null-tolerant forms such as `Objects.equals`. Do not catch it: it usually means a bug, and a `catch` hides where the null came from.
code
java · 26 linesimport java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class NullDemo {
record User(String name) {
User {
Objects.requireNonNull(name, "name"); // fail here, and say which argument
}
}
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
// int count = stock.get("pen"); // would throw: null is unboxed to int
int count = stock.getOrDefault("pen", 0);
System.out.println(count); // 0
String label = null;
System.out.println("a".equals(label)); // false: label is only an argument
System.out.println(Objects.equals(label, "a")); // false
System.out.println("label=" + label); // label=null: concatenation does not throw
new User(null); // NullPointerException: name
}
}go deeper
Recall the definition and the everyday triggers: calling an instance method, reading a field or array element, and unboxing a null wrapper. Then give two ways to prevent it, neither of them a try-catch.
Explain the hidden uses: unboxing calling intValue, for-each calling iterator, switch on a null selector, synchronized on null. Also say why static members through a null reference do not throw.
Show the design habit: decide per boundary whether null is legal, reject it early with a named argument, return empty collections or Optional, and recognise NullPointerExceptions with no frames from HotSpot's fast throw in logs.
Treat nullness as a team policy: agree where null may appear, whether nullness annotations and a static checker run in the build, and how nulls from outside code are wrapped at integration points.
## What it is `java.lang.NullPointerException` is an unchecked exception: it extends `RuntimeException`, so the compiler does not force anyone to handle it. Its documentation says it is thrown when an application attempts to use `null` in a case where an object is required. A reference variable holding `null` refers to no object. Holding `null` or passing it around is legal. The failure comes at the first operation that needs the object, which can be far from where the `null` started, and that distance is what makes these bugs tedious. `javac` does not help here: `String s = null; s.length();` compiles with no warning, even under `-Xlint:all`. ## What raises it The class documentation lists the core cases under the words "These include", and the Java Language Specification (JLS) gives the rest: | Operation | Example | Source | |---|---|---| | Call an instance method | `s.length()` | JLS 15.12.4.4 | | Read or write an instance field | `box.count` | JLS 15.11.1, 15.26.1 | | Read or write an array element | `arr[0]` | JLS 15.10.4, 15.26.1 | | Read an array's length | `arr.length` | Class documentation | | Throw a null value | `throw ex;` | JLS 14.18 | | Unbox a null wrapper | `int n = boxed;` | JLS 5.1.8 | | Enter a monitor on null | `synchronized (lock) { }` | JLS 14.19 | | Loop over null | `for (String x : list)` | JLS 14.14.2 translation | | Switch on null with no `case null` | `switch (s)` | JLS 14.11.3 | | Bind a method reference | `s::length` | JLS 15.13.3 | Several of these hide the use of the object. `int n = boxed` converts to `boxed.intValue()`, which is why `int count = map.get(key)` throws on an absent key, and why a conditional expression mixing `Integer` and `int` can throw too. `throw null` throws a new `NullPointerException` in place of the null. For-each calls `iterator()` or reads `length` on its expression. A `case null` label, final since Java 21, is what lets a `switch` accept null. ## What does not throw - **Static members through a null reference.** `box.staticMethod()` has no target reference, so the expression is evaluated, its value discarded, and the method runs. A static field behaves the same way. - **String concatenation.** `"x=" + s` gives `x=null`, because string conversion turns a null reference into the four characters `null`. - **`instanceof` and comparison.** `s instanceof String` is `false`, and `s == null` is the ordinary check. - **A null argument, in itself.** `"a".equals(s)` returns `false`, because `s` is only an argument. What happens next is that method's contract. - **`HashMap.get(null)`.** That map allows a null key, so the lookup is legal, and with none stored it returns `null`. ## Thrown on purpose The documentation also says applications should throw this class to indicate other illegal uses of `null`, and library methods do: - `Objects.requireNonNull(x)` and `Objects.requireNonNull(x, "x")` throw it when `x` is null. - `List.of(...)` rejects null elements at creation. The `List` contract also lets a query for an ineligible element either throw or return `false`, and on JDK 27 `List.of("x").contains(null)` throws. - `Optional.of(null)` throws, while `Optional.ofNullable(null)` gives an empty `Optional`. - `TreeMap.get(null)` with natural ordering and `ConcurrentHashMap.get(null)` throw it. ## Preventing it - **Reject null at the boundary.** `Objects.requireNonNull(name, "name")` in a constructor still throws this exception, so it does not remove the failure: it moves it to the entry point, with the argument named, before the bad value is stored. - **Do not produce null.** Return an empty collection rather than null. Return `Optional` where "no result" is a real outcome: its documentation says it is primarily intended as a method return type for that. - **Build complete objects.** Assign `final` fields in the constructor, and validate in a record's compact constructor, so no half-built object exists to be used. - **Use null-tolerant forms where null is legal.** `"literal".equals(s)`, `Objects.equals(a, b)` and `Objects.requireNonNullElse(s, fallback)` each state what null should mean, and `map.getOrDefault(key, 0)` does the same for an absent key. - **Let tools check.** Nullness annotations and a static checker in the build report what `javac` does not. ## Why catching it is the wrong fix The exception usually marks a bug, and a `catch` leaves that bug in place. It also catches every `NullPointerException` from the whole block and everything the block calls, including ones you did not have in mind. When one does appear, work back to the cause: 1. Read the message and stack trace. The helpful message, on by default since Java 15, normally says what was null, and the trace says where. 2. Trace that value back to where it first became null. 3. Decide whether null is legal there. If it is not, reject it at the boundary. If it is, handle it explicitly at the point of use.
- Why does calling a static method through a null reference not throw?A static method has no target reference, so nothing needs the object. The Java Language Specification says the qualifying expression is evaluated and its result discarded, and then the method runs. Any side effects in that expression still happen. An instance method is different: a null target throws `NullPointerException` when the method is located.
- Does Objects.requireNonNull prevent a NullPointerException?No, it throws one itself. What it changes is where and how: the failure happens at the method or constructor entry, with your message, rather than later at a distant use after the bad value was stored. That makes the bug easy to trace to its caller. Prevention proper means the caller never passes null.
- How can int count = map.get(key); throw when the line shows no method call on a null?The assignment unboxes. `Map<String, Integer>.get` returns `null` for an absent key in a map like `HashMap`, and converting that `Integer` to `int` means calling `intValue()` on it, which throws. The line has a hidden use of the object. For an absent key, use `getOrDefault` or test for the key first. A key mapped to null defeats both, so declaring the variable as `Integer` and handling null explicitly is the general fix.
- Passing null to any method throws NullPointerException straight away.
- Calling a static method through a null reference throws NullPointerException.
- String concatenation with a null reference throws NullPointerException.
- Objects.requireNonNull stops a NullPointerException from being thrown.
- Catching NullPointerException around the code is the normal way to handle nulls.
- Assigning a method's Integer result to an int cannot throw, because no method is called on it.
- NullPointerException
- Java 1.0
- Objects.requireNonNull
- Java 1.7
- Optional
- Java 1.8
- case null label in switch
- Java 21pre-release 17
- Helpful NullPointerException messages
- Java 14
Assumes Java 27; NullPointerException.java is unchanged from 25, and a switch accepts null only through case null, final since 21.
context
- NullPointerException (Java SE 27 & JDK 27)docs.oracle.com
- Chapter 15. Expressionsdocs.oracle.com
- Objects (Java SE 27 & JDK 27)docs.oracle.com