数字之间的下划线

Underscore between digits

错误地添加了下划线,如下所示:

int i = 1_5;

但没有编译错误。为什么会这样?输出即将到来,就好像下划线被忽略了一样。那为什么Java有这样的功能呢?

参见Underscores in Numeric Literals

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.

你没有给出一个很好的例子,因为即使不将数字分隔为 1_5,15 也是可读的。但是以数字为例:100000000000,不数数字很难说出它是什么,所以你可以这样做:

100_000_000_000

这样更容易识别号码。

在你的例子中,尝试:

int i = 1_5;
System.out.println(i); //Prints 15

这是新功能,自 Java 7 起有效。它提高了文字值的可读性。

根据 Mala Gupta 的 OCA_Java_SE_7_Programmer_I_Certification_Guide_Exam_1Z0-803:

注意数字文字值中下划线的使用。这里有一些 规则:

1) You can’t start or end a literal value with an underscore.

2) You can’t place an underscore right after the prefixes 0b, 0B, 0x, and 0X, which are used to define binary and hexadecimal literal values.

3) You can place an underscore right after the prefix 0, which is used to define an octal literal value.

4) You can’t place an underscore prior to an L suffix (the L suffix is used to mark a literal value as long).

5) You can’t use an underscore in positions where a string of digits is expected.

有效示例:

long baseDecimal = 100_267_760;
long octVal = 04_13;
long hexVal = 0x10_BA_75;
long binVal = 0b1_0000_10_11;

无效示例:

int intLiteral = _100;
int intLiteral2 = 100_999_;
long longLiteral = 100_L;