Will null instanceof SomeClass
return false
or throw a NullPointerException
?
Java – Is null check needed before calling instanceof
javanullnullpointerexception
Related Question
- Javascript – How to determine if a variable is ‘undefined’ or ‘null’
- Python – Referring to the null object in Python
- Java – How to split a string in Java
- Javascript – the difference between null and undefined in JavaScript
- Javascript – standard function to check for null, undefined, or blank variables in JavaScript
- Java – Why is the Spring @Autowired field null
Best Solution
No, a null check is not needed before using instanceof.
The expression
x instanceof SomeClass
isfalse
ifx
isnull
.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 patternmatching.)
So if the operand is null, the result is false.