javaidentifier

Why some of identifiers are illegal in java?


As we all know, the legal identifiers in java are those identifiers which must start with a letter, a currency character ($) or a connecting character such as underscore(_).

And identifiers can not start with numbers and other like, (":", "-", "e#", ".f", etc.)

So my question is that why java restrict these keywords as an illegal identifiers.


Solution

  • The reason is that you want to make parsing the language easier, and to prevent ambiguous situations. Let's assume you could call a variable "-velocity" instead of "negative_velocity". Now what does this term mean?

    h = foo - -velocity
    

    Is this subtracting the negative velocity from foo, or is it negating velocity, and then subtracting it from foo? The same goes for other characters, e.g. the point for being both used as attribute access operator (foo.bar) and part of floating points (.78). The list continues.

    You could allow all this, but then you'd have to have a multi-stage parsing process where you have to parse the source once for identifier-declarations, and then parse it again, to try & find out where they are used. With this you could also end up in a situation where you - through an import - invalidate existing code that till then has been unambiguous, but now e.g. declares "-velocity" as identifier, and then the above expression is ambiguous.