Sub topic 8
How null behaves
This chapter covers what instanceof does when the value is null, and what that means for the code you write around a type pattern. It assumes you know basic Java syntax, subtyping, the &&, || and ! operators, and the earlier chapters on type patterns, binding variables and flow scoping.
The rule: null never matches
The instanceof operator has always returned false when its left operand is null. A type pattern keeps that rule exactly.
Object o = null;
System.out.println(o instanceof String s);This prints false. It does not throw a NullPointerException, and s is never assigned.
The reason is that null refers to no object. An object has a runtime class. null has none, so no type test can succeed against it. The result is the same for every type you could name in the pattern.
Pattern matching adds a second guarantee on top of this one. When the match succeeds, the binding variable holds a non-null reference. The value was tested as an instance of the pattern type, and null is never an instance of anything.
Dropping the redundant null check
Many older codebases guard instanceof with a null check, either from habit or from caution:
if (o != null && o instanceof String) {
String s = (String) o;
System.out.println(s.length());
}The o != null test adds nothing, because instanceof already returns false for null. With a pattern you can drop it:
if (o instanceof String s) {
System.out.println(s.length());
}Inside the block, s is safe to dereference. This is one of the quieter benefits of the feature: the type test, the cast and the null check are one operation.
Be careful not to confuse this with the cast itself. A cast of null succeeds, so (String) null is legal and gives null. A cast checks that the value is assignable, and null is assignable to every reference type. The instanceof operator asks a stricter question, whether the value is an instance, and the answer for null is no.
| Expression (with `Object o = null`) | Result |
|---|---|
| `o instanceof String` | `false` |
| `o instanceof String s` | `false` |
| `(String) o` | `null`, no exception |
| `o.getClass()` | throws `NullPointerException` |
| `!(o instanceof String s)` | `true` |
The last row is the one people forget. Negating a pattern match flips the result, so a null value takes the "did not match" path.
Handling null on purpose
Sometimes null is a meaningful case and you want to treat it separately from "some other type". Because a pattern never matches null, an explicit check is the way to do that. Order matters only for readability here, since the checks cannot overlap.
public class NullDemo {
static String describe(Object o) {
if (o instanceof String s) {
return "string of length " + s.length();
}
if (o == null) {
return "null";
}
return "other: " + o;
}
public static void main(String[] args) {
System.out.println(describe("hello"));
System.out.println(describe(null));
System.out.println(describe(42));
}
}The output is:
string of length 5
null
other: 42If you remove the o == null branch, describe(null) falls into the final return and produces other: null. That would be misleading, because null is not an "other" value in any useful sense. Whenever your code distinguishes "wrong type" from "missing", test for null explicitly.
A useful case: lookups that may be missing
A map lookup returns null when the key is absent. A pattern handles "absent" and "wrong type" in one test:
import java.util.HashMap;
import java.util.Map;
public class ConfigDemo {
static String readName(Map<String, Object> config) {
if (config.get("name") instanceof String name && !name.isBlank()) {
return name;
}
return "unknown";
}
public static void main(String[] args) {
Map<String, Object> config = new HashMap<>();
System.out.println(readName(config));
config.put("name", 7);
System.out.println(readName(config));
config.put("name", " ");
System.out.println(readName(config));
config.put("name", "Ada");
System.out.println(readName(config));
}
}This prints unknown, unknown, unknown and Ada. A missing key, a value of the wrong type and a blank string all lead to the fallback. The && condition only runs after a successful match, so name is non-null by the time isBlank() is called.
Null and the negated form
The early-return guard from the previous chapter deserves a second look with null in mind:
static int lengthOrMinusOne(Object o) {
if (!(o instanceof String s)) {
return -1;
}
return s.length();
}For a null argument, o instanceof String s is false, so the negation is true, and the method returns -1. The guard therefore covers two situations with one branch: the value is not a String, or there is no value at all. After the if, s is in scope and non-null, so s.length() is safe.
This is convenient when "not a string" and "missing" deserve the same handling. When they do not, split the cases:
static int lengthStrict(Object o) {
if (o == null) {
throw new IllegalArgumentException("o must not be null");
}
if (!(o instanceof String s)) {
return -1;
}
return s.length();
}The equals idiom benefits
The equals contract in Object requires that x.equals(null) returns false for any non-null x. The pattern form satisfies this without extra code:
@Override
public boolean equals(Object o) {
return o instanceof Point p && x == p.x && y == p.y;
}When o is null, the first operand is false, and && short-circuits, so the field comparisons never run. Before patterns, you wrote either if (o == null || getClass() != o.getClass()) or relied on instanceof alone. Both worked, but the pattern version makes the null case disappear from the source entirely.
Edge cases
The expression type is already the pattern type
Consider this method:
static boolean isNonNull(String text) {
return text instanceof String s;
}Java 21 and later accept this. Because the static type of text is already String, the type test is always true for a non-null value, so the expression is really a null test: it is false only when text is null. This is a legitimate way to write "bind this variable if it is not null", though text != null states the intent more plainly.
Java 16 through 20 reject this form with a compile-time error, because the pattern type is the same as the expression type or a supertype of it. If you must support those versions, use an ordinary null comparison. The next chapters on language levels cover version differences in more detail.
Primitive and generic values
A primitive cannot be null, so the question does not arise for it. A boxed value can be, and it follows the same rule: Integer n = null; Object o = n; gives o instanceof Integer i as false.
For generic patterns, the null rule is the same. The binding in c instanceof List<String> list is never null when it is assigned.
Components inside a record pattern
When record patterns appear later in this tutorial, one detail changes. A record pattern such as Point(int x, int y) still does not match a null record. But a nested type pattern that covers the whole component type can match a component that is null. Do not carry the "never null" assumption into nested patterns without checking the component types.
Common mistakes
- Adding
o != null &&before every pattern. It is dead weight. Remove it unless you need a separatenullpath. - Forgetting that
!(o instanceof T t)is true fornull. A guard that returns early also swallowsnull. Check fornullfirst if the cases must differ. - Treating "no match" as "wrong type". A
falseresult has three causes:null, an unrelated type, or a failed&&condition. Debug by testing them one at a time. - Assuming a cast and
instanceofagree.(String) oacceptsnull, ando instanceof Stringrejects it.
Summary of behavior
| Situation | Outcome |
|---|---|
| Operand is `null` | The pattern does not match and the expression is `false`. No exception is thrown. |
| Operand is a non-null instance of the pattern type | The pattern matches and the binding is assigned a non-null reference. |
| Negated pattern with a `null` operand | The expression is `true`, and the binding is not in scope there. |
| `equals(null)` written with a pattern | Returns `false` through short-circuit evaluation. |
| Pattern type equals the expression type | Allowed in Java 21 and later, and acts as a null test. |
Exercise
Given the method below, what do len(null), len("") and len("abc") return? Then explain why len never throws a NullPointerException.
static int len(Object o) {
if (!(o instanceof String s)) {
return -1;
}
return s.length();
}
Show answer
len(null) returns -1, len("") returns 0, and len("abc") returns 3. For null, o instanceof String s is false, so the negated condition is true and the method returns early. The call s.length() is reached only when the pattern matched, and a matched binding is always a non-null String, so no NullPointerException can occur.
Exercise
A method must return "missing" when the value is null, "not text" when it is some non-String object, and the string itself otherwise. Write it with a type pattern, and say why the null check cannot be left out.
Show answer
static String label(Object o) {
if (o instanceof String s) {
return s;
}
if (o == null) {
return "missing";
}
return "not text";
}
The explicit o == null check is required because the pattern never matches null. Without it, a null value would fall through to "not text", and the two cases would be indistinguishable.