Why can an identifier not start with a number?

前端 未结 7 1780
[愿得一人]
[愿得一人] 2020-12-06 16:52

Why in java (I dont know any other programming languages) can an identifier not start with a number and why are the following declarations also not allowed?

         


        
相关标签:
7条回答
  • 2020-12-06 17:46

    That's because section 3.8 of the Java Language Specification says so.

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

    As for why this decision was made: probably because this simplifies parsing, avoids ambiguous grammar, allows introduction of special syntax in a later version of the language and/or for historical reasons (i.e. because most other languages have the same restrictionsimilar restrictions). Note that your examples example with -d is especially clear:

    int -d = 7;
    System.out.println("Some number: " + (8 + -d));
    

    Is the minus the first part of an identifier, or the unary minus?

    Furthermore, if you had both -d and d as variables, it would be completely ambiguous:

    int -d = 7;
    int d = 2;
    System.out.println("Some number: " + (8 + -d));
    

    Is the result 15 or 6?

    0 讨论(0)
提交回复
热议问题