我的一个孩子在高中学习Java,他的一次考试是这样的:

下列哪个在Java中是有效的标识符? 123 java。 b主要 c . java1234 d。{abce whoot e。)

他答了b,答错了。

我看了看这个问题,认为main是一个有效的标识符,它应该是正确的。

我们查看了标识符的Java规范,它加强了这一点。我们还编写了一个示例程序,其中包含一个名为main的变量和一个方法。他写了一份书面反驳,包括Java文档参考,测试程序和老师忽略了它,说答案仍然是错误的。

main是有效的标识符吗?


当前回答

Main是一个有效的Java标识符,而teacher是错误的。

相关文档在Java语言规范中,就在这里:

第三章。词汇结构,第3.8节。“标识符”:

https://docs.oracle.com/javase/specs/jls/se10/html/jls-3.html#jls-3.8

它说:

标识符是Java字母和Java数字的无限长度序列,其中第一个必须是Java字母…标识符不能与关键字(§3.9)、布尔字(§3.10.3)或空字(§3.10.7)具有相同的拼写(Unicode字符序列),否则会发生编译时错误。

这意味着你可以通过以下方法证明它是一个有效的标识符:

在Java关键字列表中查找它(提示:您在那里找不到它!)或简单地通过 使用它作为标识符,并观察是否发生编译时错误。

其他回答

它是一个有效的标识符吗?是的。

它是一个好的标识符吗?如果您将它用于JVM启动时启动的方法以外的任何事情,则不会。

是否列出了其他有效标识符?是的。

考试说明上说要选最佳答案了吗?

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是一个标识符,而不是关键字或保留字。

JLS的相关章节是3.8:

标识符是Java字母和Java数字的无限长度序列,其中第一个必须是Java字母。 标识符: IdentifierChars,但不是关键字或BooleanLiteral或NullLiteral IdentifierChars: JavaLetter {JavaLetterOrDigit} JavaLetter: 任何“Java字母”的Unicode字符 JavaLetterOrDigit: 任何“Java字母或数字”的Unicode字符

字符序列main符合上述描述,并且不在第3.9节的关键字列表中。

(出于同样的原因,字符序列java1234也是一个标识符。)

这在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

Should be single word. That is spaces are not allowed. Example: mangoprice is valid but mango price is not valid. Should start with a letter (alphabet) or underscore or $ symbol. Example: price, _price and $price are valid identifiers. Should not be a keyword of Java as keyword carries special meaning to the compiler. Example: class or void etc. Should not start with a digit but digit can be in the middle or at the end. Example: 5mangoescost is not valid and mango5cost and mangocost5 are valid. Length of an identifier in Java can be of 65,535 characters and all are significant. Identifiers are case-sensitive. That is both mango and Mango are treated differently. Can contain all uppercase letters or lowercase letters or a mixture.

它们是类名、方法名、变量名……

main不是保留字,根据上面定义标识符的解释,main是一个有效的标识符,java1234也是。由于上述解释,其余选项无效。

main和java123都是有效的标识符,main不是保留关键字,所以使用它是完全可以接受的,就测试而言,你至少应该得到一分或半分。