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 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告