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

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

他答了b,答错了。

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

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

main是有效的标识符吗?


当前回答

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

其他回答

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

是“Java字母和Java数字的序列,其中第一个是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.

字符序列main是一个标识符,而不是关键字或保留字。

JLS的相关章节是3.8:

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

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

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

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不是一个有效的标识符,要么只是问题的措辞错误。他可能是想说“一个很好的标识符”。 但是,忽视你儿子的论点,从而阻止他以科学的方法检查相关文献(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);
    }
}