javaparsingsyntax

Why variable names in Java cannot have same names as keywords?


In most programing languages that I know you cannot declare a variable with name that is also a key word.

For example in Java:

public class SomeClass
{
    Class<?> clazz = Integer.class; // OK.
    Class<?> class = Integer.class; // Compilation error.
}

But it's very easy to figure out what is what. Humans reading it will not confuse variable name with class declaration and compiler will most likely not confuse it too.

Same thing about variable names like 'for', 'extends', 'goto' or anything from Java key words if we are talking about Java programming language.

What is the reason that we have this limitation?


Solution

  • What is the reason that we have this limitation?

    There are two reasons in general:

    Anyhow, while neither of these reasons is a total "show stopper", they would be sufficient to cause most people attempting a new programming language design / implementation to reject the idea.

    And that of course is the real reason that you (almost) never see languages where keywords can be used as identifiers. Programming language designers nearly always reject the idea ...

    (In the case of Java, there was a conscious effort to make the syntax accessible to people used to the C language. C doesn't support this. That would have been a 3rd reason ... if they were looking for one.)


    There is one interesting (semi-) counter example in a mainstream programming language. In early versions of FORTRAN, spaces in identifiers were not significant. Thus

        I J = 1
    

    and

        IJ = 1
    

    meant the same thing. That is cool (depending on your "taste" ...). But compare these two:

        DO 20 I = 10, 1, -2
    

    versus

        DO 20 I = 10
    

    One is an assignment, but the other one is a "DO loop" statement. As a reader, would you notice this?