Will null instanceof SomeClass
return false
or throw a NullPointerException
?
Is null check needed before calling instanceof?
2021-6-3 anglehua
No, a null check is not needed before using instanceof.
The expression x instanceof SomeClass
is false
if x
is null
.
From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":
"At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
."
So if the operand is null, the result is false.
Using a null reference as the first operand to instanceof
returns false
.
采集自互联网,如有侵权请联系本人