Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is null check needed before calling instanceof?

Will null instanceof SomeClass return false or throw a NullPointerException?

like image 659
Johan Lübcke Avatar asked Jun 01 '10 13:06

Johan Lübcke


People also ask

Does Instanceof handle null?

Using the instanceof Operator When an Object Is nullIf we use the instanceof operator on any object that's null, it returns false. We also don't need a null check when using an instanceof operator.

Should you always check for null?

In any case, it is always good practice to CHECK for nulls on ANY parameters passed in before you attempt to operate on them, so you don't get NullPointerExceptions when someone passes you bad data. Show activity on this post. If you don't know whether you should do it, the chances are, you don't need to do it.

Is null Instanceof string Java?

No, a null check is not needed before using 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".


1 Answers

No, a null check is not needed before using 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 patternmatching.)

"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.

like image 125
Andy Thomas Avatar answered Oct 05 '22 13:10

Andy Thomas