我的一个孩子在高中学习Java,并在他的一次测试中做了以下测试:
以下哪一项是Java中的有效标识符?
a. 123java
b. main
c. java1234
d. {abce
e. )whoot
他回答了b,但答错了。
我看了看这个问题,认为main
是一个有效的标识符,它应该是正确的。
我们研究了用于标识符的Java spec,它强化了这一点。我们还编写了一个示例程序,该程序有一个名为main
的变量和一个方法。他写了一份书面反驳,其中包括Java文档参考,测试程序和老师忽略了它,并表示答案仍然不正确。
main
是有效的标识符吗?
发布于 2018-09-11 04:08:38
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.
字符序列main
是标识符,而不是关键字或保留字。
The relevant section of the JLS is 3.8
标识符是由Java字母和Java数字组成的无长度限制的序列,其中第一个必须是Java字母。
标识符:
返回IdentifierChars,但不是关键字、BooleanLiteral或NullLiteral
IdentifierChars:
推送JavaLetter {JavaLetterOrDigit}
JavaLetter:
不包括任何为"Java字母“的Unicode字符
JavaLetterOrDigit:
不允许任何"Java字母或数字“的Unicode字符
字符序列main
符合上述描述,并且不在keyword list in Section 3.9中。
(出于同样的原因,字符序列java1234
也是一个标识符。)
发布于 2018-09-11 04:01:46
main
是一个有效的java标识符,老师错了。
相关文档在Java Language Specification中,就在这里:
第三章。“词汇结构”,3.8节。“标识符”:
https://docs.oracle.com/javase/specs/jls/se10/html/jls-3.html#jls-3.8
上面写着:
Java标识符是由
字母和数字组成的无长度限制的序列,其中第一个必须是Java字母...标识符不能与关键字(§3.9)、布尔文字(§3.10.3)或空文字(§3.10.7)具有相同的拼写(Unicode字符序列),否则会发生编译时错误。
这意味着您可以通过以下方式证明它是有效的标识符:
发布于 2018-09-11 20:11:34
这在Java 1.8上编译得很好...
public class main {
public String main = "main";
public void main(String main) {
System.out.println("This object is an instance of the class " + this.getClass().getCanonicalName());
System.out.println("The value of the argument \"main\" for this call to the method \"main(String main)\" is " + main);
System.out.println("The value of the field \"main\" is " + this.main);
}
public static void main(String[] args) {
main main = new main();
main.main(main.main + main.main);
}
}
This object is an instance of the class main
The value of the argument "main" for this call to the method "main(String main)" is mainmain
The value of the field "main" is main
https://stackoverflow.com/questions/52264638
复制相似问题