数字文字中的下划线

时间:2012-01-22 02:40:37

标签: java variables java-7

在官方Java site上,我遇到了这一行

    you cannot place underscores in the following places:

     At the beginning or end of a number...

他们也举了一个例子

int x1 = _52;              // This is an identifier, not a numeric literal

当我在我的代码中使用它时,它没有给出任何编译时错误

long l = _23L;      

我们可以在开头使用_吗?

是什么意思
This is an identifier, not a numeric literal

很抱歉,如果这是一个非常愚蠢的问题,我很长时间没有修改Java基础知识。

编辑:
我使用的是Windows XP和Java 7

java version "1.7.0_02"
Java(TM) SE Runtime Environment (build 1.7.0_02-b13)
Java HotSpot(TM) Client VM (build 22.0-b10, mixed mode, sharing)

5 个答案:

答案 0 :(得分:2)

文字是您在代码中硬编码的任何内容,如:

int x  = 10;
String str = "hello";

10hello是文字。

所以数字文字只不过是具有数值的文字。

标识符是赋予对象,类等的名称,但不能是keywords,如int,boolean,null等。

因此,在上面的例子中,x, str and String是标识符。

SIDE注意:如何定义数字文字与JDK 6到JDK 7不同。因此,有问题的代码只能运行JDK7

答案 1 :(得分:1)

  

当我在我的代码中使用它时,它没有给出任何编译时错误

     

长l = _23L;

这意味着你应该在某个地方有一个名为_23L的长变量。

答案 2 :(得分:1)

我认为您需要重新检查您的测试用例。

当我尝试编译时,我得到了这个,预期的错误。

ariel-2:src boxcat$ javac scratch/misc/ScratchSO.java 
scratch/misc/ScratchSO.java:16: error: cannot find symbol
        long l = _23L;
                 ^
  symbol:   variable _23L
  location: class ScratchSO
1 error

答案 3 :(得分:0)

标识符类似于变量名称或对象名称:http://java.about.com/od/i/g/identifier.htm

答案 4 :(得分:0)

Java 7现在允许在数字文字中使用下划线。

int i = 1_000_000;  // readable.