编程语言
首页 > 编程语言> > 为什么Java SE 1.7中的数字文字中的下划线在Octal和Hexadecimal中有不同的规则? Octal文字是否违反了规则?

为什么Java SE 1.7中的数字文字中的下划线在Octal和Hexadecimal中有不同的规则? Octal文字是否违反了规则?

作者:互联网

根据oracle doc下划线不能放在一个数字的开头即可.但是当涉及Octal Number时,我们可以在开头放下下划线.这不奇怪吗?

int x1 = 0x_52;            // Invalid; cannot put underscores at the beginning of a number
int x2 = 0_52;             // OK (octal literal)

解决方法:

规则是:

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

对于带有基数前缀的文字,对于十六进制/二进制,表示用于表示整数的数字有什么不同:

… 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.

对于Octal来说,规则是不同的:

In a decimal or octal literal, the integer is denoted by all the digits in the literal before any type suffix. Therefore, underscores may not appear before the first digit or after the last digit in the numeral. Underscores may appear after the initial 0 in an octal numeral (since 0 is a digit that denotes part of the integer) and after the initial non-zero digit in a non-zero decimal literal.

参考:https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1

标签:java,literals
来源: https://codeday.me/bug/20190701/1346232.html