Is null check needed before calling instanceof?
Very good question indeed. I just tried for myself.
public class IsInstanceOfTest {
public static void main(final String[] args) {
String s;
s = "";
System.out.println((s instanceof String));
System.out.println(String.class.isInstance(s));
s = null;
System.out.println((s instanceof String));
System.out.println(String.class.isInstance(s));
}
}
Prints
true
true
false
false
JLS / 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
.
API / Class#isInstance(Object)
If this
Class
object represents an interface, this method returnstrue
if the class or any superclass of the specifiedObject
argument implements this interface; it returnsfalse
otherwise. If thisClass
object represents a primitive type, this method returnsfalse
.
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 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.
No, it's not. instanceof
would return false
if its first operand is null
.
Using a null reference as the first operand to instanceof
returns false
.