Is main a valid Java identifier?

后端 未结 12 1932
广开言路
广开言路 2020-12-23 02:48

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. 123

12条回答
  •  醉梦人生
    2020-12-23 02:58

    main is a valid java identifier, and the teacher is wrong.

    The relevant documentation is in the Java Language Specification, right here:

    Chapter 3. "Lexical Structure", section 3.8. "Identifiers":

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

    It says:

    An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter... An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

    Which means that you can prove that it is a valid identifier either by:

    • looking for it in the list of java keywords (hint: you won't find it there!) or simply by
    • using it as an identifier and observing that no compile-time error occurs.

提交回复
热议问题