开发者

In java, why I can declare a variable named "a" but not "1" ?

Everything is fine when I declare

String a;

but it says 开发者_StackOverflow社区Syntax error on token "1", invalid VariableDeclaratorId when I do this

String 1;

Why is that?


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)


The rules for identifiers in the Java language specification state that you cannot start an identifier with a number.


The parser can't distinguish it from the int literal, so it's disallowed.


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.


I think you can. It compiles on my machine.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜