Is main a valid Java identifier?

后端 未结 12 1982
广开言路
广开言路 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 03:21

    As the other answers state

    main is a valid Java identifier, as well as java1234.

    I guess the confusing comes from the fact that the main(String[]) method is often used as entry point by the JVM1. However, that doesn't mean that the token main itself cannot be used as identifier2.

    The specs say so, and the following declarations are also valid:

    • A field:

      private int main;
      
    • A local variable:

      String main = "";
      
    • A method:

      private void main() { ... }
      
    • A class (although a class name starting with lowercase is discouraged):

      public class main { ... }
      
    • A package:

      package main;
      

    1: As noted in the comments, the JVM specification itself does not mandate any particular method as entry point, but the widely used java tool often uses such a method as entry point.
    2: I would generally avoid creating a main method other than main(String[]).

提交回复
热议问题