Java中的instanceof运算子是什么?说明。

Java中的instanceof 运算符用于查找引用是Type的实例(即类还是接口)。

示例

public class InstanceOfExample {
   public static void main(String args[]) {
      String str = "hello";
      boolean bool = str instanceof String;
      System.out.println(bool);
   }
}

输出结果

true

实例运算符的合法操作数

以下是instanceof运算符的唯一合法操作数-

  • 左操作数-它必须是代表对象的引用。

  • 右操作数-它必须是Java类或接口的名称。

如果不使用这两个操作数,则将生成编译时错误。

示例

public class InstanceOfExample {
   public static void main(String args[]) {
      int i =20;
      boolean bool = i instanceof String;
      System.out.println(bool);
   }
}

编译时错误

InstanceOfExample.java:4: error: unexpected type
   boolean bool = i instanceof String;
                  ^
   required: reference
   found: int
1 error