Everything is fine when I declare
String a;
but it says Syntax error on token "1", invalid VariableDeclaratorId when I do this
String 1;
I guess it must be very trivial but I don't get it.
Everything is fine when I declare
String a;
but it says Syntax error on token "1", invalid VariableDeclaratorId when I do this
String 1;
I guess it must be very trivial but I don't get it.
The parser can't distinguish it from the int literal, so it's disallowed.
The rules for identifiers in the Java language specification state that you cannot start an identifier with a number.
Well, first of all, it's because it's written in the Java language Specification.
But, maybe that this example will help you more:
String 1 = "toto"
System.out.println(1 + 2)
What should be the output?
Because 1
is also a value (which, among others, you can assign) the parser cannot know what you mean.
Consider the following snippet:
int 1 = 10;
int a = 1; // what is the value of a ? 1 or 10?
Therefore, starting a variable name with a number is dissallowed. You can use _1
instead if you really want (note that it is difficult to read though)
Not only the parser would have a great deal of effort distinguishing between an int
literal and a variable (if not totally impossible) but you could end up with strange situations like:
int 1 = 999;
System.out.println(1);
// output: 1 or 999
Basically this doesn't make much sense.
Because 1
is a value. What will someone make of this :
String 1 = "6";
String s = 1 + "00"; // With value "100" or "600"?
Similarly, true
, false
, null
cannot be variable names.
It works on my machine too: public static void main(String args[]) { String l = "one"; } I am on jdk1.7