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

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

他答了b,答错了。

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

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

main是有效的标识符吗?


当前回答

Main是完全有效的,因为从文档中可以看出:

是“Java字母和Java数字的序列,其中第一个是Java字母” 不是关键字 不是布尔字面值,即。“正确”或“错误” 不是空文字

其他回答

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

那位老师犯了一个小错误,要么认为main不是一个有效的标识符,要么只是问题的措辞错误。他可能是想说“一个很好的标识符”。 但是,忽视你儿子的论点,从而阻止他以科学的方法检查相关文献(Java规范)并进行实验(编写示例程序),这与教师应该做的事情完全相反。

public class Main {
    private static String main;
    public static void main(String[] main) {
        Main.main = main[0];
        new Main().main(Main.main);
    }
    private void main(String main) {
        System.out.println(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不是保留关键字,所以使用它是完全可以接受的,就测试而言,你至少应该得到一分或半分。