Should I guard uses of the instanceof operator against possible null references?

John Mitchell

I.e., do I need to do something like:

if ((myObjRef != null) && (myObjRef instanceof SomeReferenceType))

No, you do not have to do that! You can just write the instanceof check:

if (myObjRef instanceof SomeReferenceType)

This is because of the fact that the instanceof operator is defined to work properly in the face of null. See Section 15.20.2 of JLS v2 (or Section 15.19.2 of JLS v1) for the definition.