Question:
Is null check needed before calling instanceof?
Will null instanceof SomeClass return false or throw a NullPointerException?
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.
Code:
public class NullClass { public static void main(String[] args) { NullClass nc = null; if(nc instanceof NullClass){ System.out.println("YES"); } else { System.out.println("NO"); } } }
Output:
$ java NullClass NO