Why can't Java variable names start with a number?

前端 未结 2 1096
半阙折子戏
半阙折子戏 2020-12-20 14:19

In Java, variable names start with a letter, currency character ($) etc. but not with number, :, or .

Simple question: why is

相关标签:
2条回答
  • 2020-12-20 14:54

    Simply put, it would break facets of the language grammar.

    For example, would 7f be a variable name, or a floating point literal with a value of 7?

    You can conjure others too: if . was allowed then that would clash with the member selection operator: would foo.bar be an identifier in its own right, or would it be the bar field of an object instance foo?

    0 讨论(0)
  • 2020-12-20 14:58

    Because the Java Language specification says so:

    IdentifierChars:

    JavaLetter {JavaLetterOrDigit}

    So - yes, an identifier must start with a letter; it can't start with a digit.

    The main reasons behind that:

    • it is simply what most people expect
    • it makes parsing source code (much) easier when you restrict the "layout" of identifiers; for example it reduces the possible ambiguities between literals and variable names.
    0 讨论(0)
提交回复
热议问题