Syntax
>>-RelationalExpression-instanceof-ReferenceType-><
Description
The instanceof keyword is used to test if a reference expression can be cast
to a reference type without raising a ClassCastException.
An expression whose type is a reference type may be tested using the instanceof operator to find out whether the class of the object referenced by the run-time value of the expression can be assigned to another reference type.
The type of a RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compilation error occurs. The ReferenceType mentioned after the instanceof operator must denote a reference type; otherwise, a compilation error occurs.
At run time, the result of the instanceof operator is true
if the value of the RelationalExpression is not null and the reference could be
cast to the ReferenceType without throwing a ClassCastException. Otherwise the
result is false.
If a cast of the RelationalExpression to the ReferenceType would be
rejected as a compilation error, then the instanceof relational expression
also produces a compilation error. In such a situation, the result of the instanceof
expression could never be true
Example
Consider the following example program:
class Point { int x, y; } class Element { int atomicNumber; } class Test { public static void main(String[] args) { Point p = new Point(); Element e = new Element(); if (e instanceof Point) { // compile-time error System.out.println("I get your point!"); p = (Point)e; // compile-time error } } }
This example results in two compilation errors. The cast (Point)e is incorrect because no instance of Element or any of its possible subclasses (none are shown here) could possibly be an instance of any subclass of Point. The instanceof expression is incorrect for exactly the same reason. If, on the other hand, the class Point were a subclass of Element:
class Point extends Element { int x, y; }
then the cast would be possible, though it would require a run-time check, and the instanceof expression would then be sensible and valid. The cast (Point)e would never throw an exception because it would not be executed if the value of e could not correctly be cast to type Point.
Syntax diagrams
Java types
boolean keyword
class keyword
interface keyword
Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.