在前缀和数字之间使用下划线时不会出错

No error when underscore used between prefix and number

以下代码:

int i = 0_10;
System.out.println(i);

产生输出:

8

javadocs里面写着我们不能放下划线 在数字 的开头,如示例 int x5 = 0x_52; 中那样,会产生错误 illegal underscore.

然而,在这段代码中,0是八进制数的前缀,我们可以看到输出是8。但是没有产生错误。

为什么不报错? java 是否将其 partially 视为八进制,而 partially 不是?

因为 JLS says:

Underscores are allowed as separators between digits that denote the integer.

(我的重点)0x_52中的下划线不是数字之间.

是的,一个数字是八进制的指示符只是它以 0 开头(后面没有跟 x),这有点奇怪。它造成了无尽的混乱,但它(0一个数字,因此0_10符合JLS规则。

它确实继续明确说明:

In a hexadecimal or binary literal, the integer is only denoted by the digits after the 0x or 0b characters and before any type suffix. Therefore, underscores may not appear immediately after 0x or 0b, or after the last digit in the numeral.

In a decimal or octal literal, the integer is denoted by all the digits in the literal before any type suffix.

注意区别。 (为清楚起见:通过“类型后缀”,他们谈论的是 l/L 表示“long”,f/F 表示“float” "等)

Does java treat it partially as octal, and partially not?

没有。 0 是数字的一部分,也是八进制数字的指示符。这是 1970 年代 C 的一个奇怪的符号想法,当 Gosling 设计它以使用类似于 1990 年代 C 的语法时,Java 继承了它。

值得注意的是,当他们最终 正式将八进制添加到 JavaScript 时(另一种语言也使用类似的语法),这种奇怪的符号已经引起了足够的麻烦,他们使用 0o 作为前缀。 (在 2015 规范之前,JavaScript 中没有正式的八进制形式,尽管在 2009 规范中注意到一些实现已经完成了 C 的事情。从 2009 规范开始,它们不允许在严格模式,2015 规范引入了 0o。[在 2015 规范中,他们还在松散模式下 要求 在浏览器中 要求 ,因为兼容性原因。])