Why id can't start with a digit in java

I can't think of anything other than "a string of digits that will be a valid identifier as well as a real number".

Is there any other explanation other than this?

+3


source to share


4 answers


Because that would make numeric literals from characters stand for serious PITA.



For example, if a digit is valid for the first character, the name variables 0xdeadbeef

or were valid 0xc00lcafe

. But this can also be interpreted as a hexadecimal number. By limiting the first character of a character to an unfamiliar, ambiguities of this kind are avoided.

+12


source


If it were possible, this appointment would be possible

int 33 = 44; // oh oh 

      



then how does the JVM distinguish between a numeric literal and a variable?

+7


source


This is to keep the rules simple for both the compiler and the programmer.

An identifier can be defined as any alphanumeric sequence that cannot be interpreted as a number, but you get into a situation where the compiler interprets the code differently than you expect.

Example:

double 1e = 9;
double x = 1e-4;

      

The result x

will not be 5

, but 0.0001

because it 1e-4

is a number in scientific notation and is not interpreted as a 1e

minus 4

.

+3


source


This is done in Java and many other languages, so the parser can classify a terminal character unambiguously regardless of its surrounding context. It is technically possible to allow identifiers that look like numbers or even keywords: for example, you could write a parser that removes the restriction on identifiers, allowing you to write something like this:

int 123 = 321; // 123 is an identifier in this imaginary compiler

      

The compiler knows enough to "understand" that whatever comes after a type name must be a variable name, so it 123

is an identifier, and therefore can treat it as a valid declaration. However, this will create more uncertainties in the future, because it 123

becomes an invalid number "shaded" by your new "identifier".

Ultimately, the rule works both ways: it helps compiler developers write simpler compilers, and it also helps programmers write readable code.

Note that there have been attempts in the past to create compilers that are not particularly picky about identifier names - for example

int a real int = 3

      

will declare an identifier with spaces (i.e. "a real int"

is the only identifier). However, this did not help readability, so modern compilers have abandoned this trend.

+2


source







All Articles