`

Java标识符、关键字、Boolean字面量和空字面量的探讨

阅读更多

   时不时有人纠结true、false和null到底是不是java关键字(keyword),出于很多笔试题的基础部分总会出现这种选择题,还有很多书籍给出的关键字列表也有出入,所以虽然是太过于理论性的知识,也有很多人关注。

 

    首先给出结论,true、false和null三个全不是关键字(虽然很多面试题和书籍将其中全部或一部分列为关键字--如java核心技术第8版英文版附录将null列为关键字),其中true和false是Boolean字面量,null是空的字面量。


    下面来给出原因:
    1、很多人认为它们三个是关键字原因出于以下两点:
    ①普遍书籍给的标识符定义:Java标识符由数字,字母和下划线(_),美元符号($)组成。Java区分大小写,且首位不能是数字。Java关键字不能当作Java标识符 (整理自百度百科,印象中在大学和培训机构里学习时也是这么定义的。但是这是不完善的)。所以很多人由此来判断,true、flase和null并不能当标识符使用(若使用编译器会报错),所以他们是关键字。


    ②在IDE里,如Eclipse中打出true、false和null是蓝色加粗状态和其他关键字一样,所以他们是关键字。

    首先探讨观点①,查阅Java语言规范的官方文档,看一下标识符的完整定义:

http://docs.oracle.com/javase/specs/jls/se5.0/html/lexical.html#3.8 写道
3.8 Identifiers
An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7).

     可以看到最后一句话:Java关键字,布尔字面量和空字面量不能作为标识符


     然后看观点②:是因为关键字和布尔字面量、空字面量都不能作为关键字所以才在IDE中加粗显示的,而不是加粗显示的都是关键字。

   2、我们再来看一下Java关键字的标准定义,摘自Java语言规范官方文档:

http://docs.oracle.com/javase/specs/jls/se5.0/html/lexical.html#3.9 写道
3.9 Keywords
The following character sequences, formed from ASCII letters, are reserved for use as keywords and cannot be used as identifiers (§3.8):

Keyword: one of
abstract continue for new switch
assert default if package synchronized
boolean do goto private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while


The keywords const and goto are reserved, even though they are not currently used. This may allow a Java compiler to produce better error messages if these C++ keywords incorrectly appear in programs.

While true and false might appear to be keywords, they are technically Boolean literals (§3.10.3). Similarly, while null might appear to be a keyword, it is technically the null literal (§3.10.7).

 


   里面清楚地写道:Java包括50个关键字和2个保留关键字,共52个,其中true和false看上去虽然像关键字,但是它们是布尔字面量,null虽然看上去也像关键字,但它是空字面量。

   所以,我们现在可以得出结论,Java有52个关键字(50+2),true、false和null不是关键字。

   虽然总结这些没有什么实际意义,只是理论上的概念,这种知识点太过边边角角,不知道这些完全不妨碍你成为一个技术牛人,但是我认为这是一个态度的问题,如果有严谨的学习、工作态度,不是遇到这些问题时只是听别人怎么说就是什么,或者简单的在网上查阅下资料,自己去查阅文档,学习探讨下,也不至于有很多的书籍,授课内容,和企业面试题都是不完善、错的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics