patternjavaCritical
Is null check needed before calling instanceof?
Viewed 0 times
checkcallingbeforeinstanceofneedednull
Problem
Will
null instanceof SomeClass return false or throw a NullPointerException?Solution
No, a null check is not needed before using
The expression
The Java 11 Language Specification expresses this concisely in section 15.20.2, "Type comparison operator instanceof". (Java 17 expresses this less concisely, after the introduction of
"At run time, the result of the
value of the RelationalExpression is
not
cast to the ReferenceType
without raising a
Otherwise the result is
So if the operand is null, the result is false.
instanceof.The expression
x instanceof SomeClass is false if x is null.The Java 11 Language Specification expresses this concisely in section 15.20.2, "Type comparison operator instanceof". (Java 17 expresses this less concisely, after the introduction of
instanceof pattern matching.)"At run time, the result of the
instanceof operator is true if thevalue of the RelationalExpression is
not
null and the reference could becast to the ReferenceType
without raising a
ClassCastException.Otherwise the result is
false."So if the operand is null, the result is false.
Context
Stack Overflow Q#2950319, score: 2222
Revisions (0)
No revisions yet.