本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看 活动链接
问题:main是一个合法的Java标识符吗?
我的一个崽崽在高中上Java课,在他们的测验里有一道这样的题目
哪个是合法的Java标识符?
a. 123java
b. main
c. java1234
d. {abce
e. )whoot
他回答b,结果错了
我看了这个问题,认为main是一个合法的标识符,它应该是正确的。
我们看了一眼标识符的Java规范,它也印证了这一点。我们还编写了一个示例程序,其中有一个名为main的变量和一个方法。他写了一个书面反驳,其中包括参考的Java文档还有测试程序,但是老师忽略了它,并且说答案仍然是不正确的。
main是一个合法的Java标识符吗?
回答
public class J {
public static void main(String[] args)
{
String main = "The character sequence \"main\" is an identifier, not a keyword or reserved word.";
System.out.println(main);
}
}
这个代码编译,然后执行时,会这样输出
The character sequence "main" is an identifier, not a keyword or reserved word.
The character sequence main is an identifier, not a keyword or reserved word.
JLS相关的部分是3.8
标识符是由Java字母和Java数字组成的不受长度限制的序列,其中字符第一个必须是Java字母。 Identifier:
IdentifierChars 不是Keyword 不是 booleanLiteral 不是 NullLiteral
IdentifierChars:
JavaLetter {JavaLetterOrDigit}
JavaLetter:
组成Java字母的任意Unicode字符
JavaLetterOrDigit:
组成Java字母或者数字的任意Unicode字符
字符序列main符合上面的描述,也不在第3.9节的关键字列表中。 (出于同样的原因,字符序列java1234也是一个标识符。)
文章翻译自Stack Overflow:stackoverflow.com/questions/5…