instanceof with null: Behavior and Guarantees
What You'll Learn
You'll learn that instanceof always returns false when checking null references, which simplifies your code by eliminating redundant null checks.
The Core Behavior
In Java, the instanceof operator has a built-in guarantee: it always returns false for null references, regardless of what type you're checking against. This is true even when using pattern matching for instanceof.
String text = null;
if (text instanceof String) {
// This block never executes
System.out.println("Not null!");
}
The instanceof check returns false, so the block is skipped—no NullPointerException is thrown.
Why This Matters
Before understanding this behavior, you might write defensive code like this:
Object obj = getObject();
if (obj != null && obj instanceof Dog) {
Dog dog = (Dog) obj;
dog.bark();
}
But the null check is redundant! You can simplify to:
Object obj = getObject();
if (obj instanceof Dog) {
Dog dog = (Dog) obj;
dog.bark();
}
If obj is null, instanceof returns false and you safely skip the block.
Pattern Matching Maintains the Same Guarantee
With pattern matching, the guarantee still holds:
Object obj = null;
if (obj instanceof Dog dog) {
// Never executes, pattern variable 'dog' never bound
dog.bark();
}
The pattern variable dog is only created when the instanceof check succeeds—which never happens with null.
The Conceptual Reason
Think of instanceof as asking: "Is this object an instance of this type?" Since null represents the absence of an object (not an instance of anything), the answer is always "no."
Key Takeaway: instanceof always returns false for null references, so you never need a separate null check before using instanceof—the operator handles null safety for you.