Is main a valid Java identifier?

Gary Bak picture Gary Bak · Sep 10, 2018 · Viewed 15.4k times · Source

One of my kids is taking Java in high school and had this on one of his tests:

Which of the following is a valid identifier in Java?

a. 123java
b. main
c. java1234
d. {abce
e. )whoot

He answered b and got it wrong.

I looked at the question and argued that main is a valid identifier and that it should have been right.

We took a look at the Java spec for identifiers and it reinforced that point. We also wrote a sample program that had a variable called main, as well as a method. He created a written rebuttal that included the Java documentation reference, the test program and the teacher ignored it and says the answer is still incorrect.

Is main a valid identifier?

Answer

rgettman picture rgettman · Sep 10, 2018
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);
    }
}

This compiles, and when executed, emits this output:

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.

The relevant section of the JLS is 3.8:

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.

Identifier:

    IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral

IdentifierChars:

    JavaLetter {JavaLetterOrDigit}

JavaLetter:

    any Unicode character that is a "Java letter"

JavaLetterOrDigit:

    any Unicode character that is a "Java letter-or-digit"

The character sequence main fits the above description and is not in the keyword list in Section 3.9.

(The character sequence java1234 is also an identifier, for the same reasons.)