The left operand is an object reference or null value and the right operand is a class, interface, or arraytype.
In Java, the instanceof
operator is used to test whether an object is an instance of a particular class or interface. The legal operands for the instanceof
operator are:
- Object Reference: The left operand of the
instanceof
operator should be an object reference. - Class or Interface: The right operand should be a class or interface.
For example:
Object obj = new String("Hello");
if (obj instanceof String) {
// Code to be executed if obj is an instance of String
}
In this example, the left operand (obj
) is an object reference, and the right operand (String
) is a class. The instanceof
operator checks whether obj
is an instance of the String
class.
It’s important to note that using instanceof
to check types should be done carefully, as it may indicate a design issue in your code. In many cases, it’s preferable to use polymorphism and interfaces rather than explicit type checking.