This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: Is main a legitimate Java identifier?

One of my pups took a Java class in high school, and they had a quiz like this

Which is a valid Java identifier? a. 123java b. main c. java1234 d. {abce e. )whootCopy the code

He answered B and was wrong

I looked at the problem and decided that main was a legitimate identifier and that it should be correct.

We took a look at the Java specification for identifiers, and it confirms this. We also wrote a sample program with a variable named main and a method. He wrote a written rebuttal that included references to Java documentation and testing procedures, but the teacher ignored it and said the answer was still incorrect.

Is main a legal Java identifier?

answer

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); }}Copy the code

When this code is compiled and then executed, it will output like this

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.

Copy the code

The JLS related part is 3.8

An identifier is an unlimited sequence of Java letters and Java digits, where the first character must be a Java letter. Identifier:

IdentifierChars is not Keyword, not booleanLiteral, not NullLiteralCopy the code

IdentifierChars:

JavaLetter {JavaLetterOrDigit}
Copy the code

JavaLetter:

Any Unicode character that makes up a Java letterCopy the code

JavaLetterOrDigit:

Any Unicode character that forms a Java letter or numberCopy the code

The character sequence main fits the description above and is not in the keyword list on page 3.9. (The character sequence Java1234 is an identifier for the same reason.)

The article translated from Stack Overflow:stackoverflow.com/questions/5…