詳細闡述 Java 中 operator 的例項的合法運算元?


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 運算子的合法運算元

以下是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

更新於: 30-七月-2019

107 次瀏覽

啟動你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.