Java 中 true 和 false 是關鍵字嗎?


關鍵字 − Java 中的關鍵字對編譯器具有特殊含義,因此不能用作識別符號。Java 提供了一組 50 個關鍵字。

abstractcontinuefornewswitch
assertdefaultgotopackagesynchronized
booleandoifprivatethis
breakdoubleimplementsprotectedthrow
byteelseimportpublicthrows
caseenuminstanceofreturntransient
catchextendsintshorttry
charfinalinterfacestaticvoid
classfinallylongstrictfpvolatile
constfloatnativesuperwhile

保留字 − 在上面列出的關鍵字列表中,goto 和 const 目前未使用。它們是保留字(供將來使用)。

true、false 和 null − true、false 和 null 在 Java 中表示某些值,它們用作字面量。它們不被視為關鍵字。

但是,如果嘗試這樣做,則不能將它們用作 Java 中的識別符號,否則會生成編譯時錯誤。

示例

public class Example {
   public static void main(String args[]) {
      int true = 20;
      int false = 30;
      float null = 23.6f;
   }
}

輸出

Example.java:3: error: not a statement
   int true = 20;
   ^
Example.java:3: error: ';' expected
   int true = 20;
       ^
Example.java:4: error: not a statement
   int false = 30;
   ^
Example.java:4: error: ';' expected
   int false = 30;
       ^
Example.java:5: error: not a statement
   float null = 23.6f;
   ^
Example.java:5: error: ';' expected
   float null = 23.6f;
         ^
6 errors

更新於: 2019-07-30

923 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.