Monday, October 29, 2018

java - Is null check needed before calling instanceof?




Will null instanceof SomeClass return false or throw a NullPointerException?


Answer



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 is true if the
value of the RelationalExpression is
not null
and the reference could be
cast to the ReferenceType
without raising a ClassCastException.
Otherwise the result is false."




So if the operand is null, the result is false.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...