Class InstanceOfExpr

All Implemented Interfaces:
NodeWithExpression<InstanceOfExpr>, NodeWithRange<Node>, NodeWithTokenRange<Node>, NodeWithType<InstanceOfExpr, ReferenceType>, Observable, Visitable, HasParentNode<Node>, Cloneable

public class InstanceOfExpr extends Expression implements NodeWithType<InstanceOfExpr, ReferenceType>, NodeWithExpression<InstanceOfExpr>

The instanceof statement

Java ?? to 13

The instanceof expression is a relational operator, evaluating to true if the object on the left hand side is an instance of the type (ReferenceType) on the right hand side.

Example:
tool instanceof Drill

This is then used wherever a conditional/boolean value can be used. For example:
if (obj instanceof String) {
    String s = (String) obj;
    // use s
}

Java 14

Since JDK14, it is possible to bind a variable that is cast to the type being tested against. This is referred to as a Pattern within JEP305, and avoids the need to cast to the desired type.
Example:
tool instanceof Drill d

This is then used wherever a conditional/boolean value can be used. The scope of the variable created can vary, and is defined further within JEP305.
if (obj instanceof String s) {
    // can use s here
} else {
    // can't use s here
}


JDK14 Grammar

Per JEP305:
RelationalExpression:
     ...
     RelationalExpression instanceof ReferenceType
     RelationalExpression instanceof Pattern

Pattern:
     ReferenceType Identifier
See Also: