instanceof Operator

The instanceof operator can be used to test if an object is of a specified type. It is normally used in an if statement and its syntax is this.

if (objectReference instanceof type)

where objectReference references an object being investigated. For example, the following if statement returns true.

String s = "Hello";
if (s instanceof java.lang.String)

However, applying instanceof on a null reference variable returns false. For example, the following if statement returns false.

String s = null;
if (s instanceof java.lang.String)

Also, since a subclass “is a” type of its superclass, the following if statement, where Child is a subclass of Parent, returns true.

Child child = new Child();
if (child instanceof Parent)    // evaluates to true