为什么 1_2_3_4 是 java 中的有效整数文字?
Why is 1_2_3_4 a valid integer literal in java?
为什么以下操作有效?
int a=1_2_3_4;
System.out.println(a); // 1234
在 JLS 3.10.1 中指定了数字文字。
A decimal numeral is either the single ASCII digit 0, representing the integer zero, or consists of an ASCII digit from 1 to 9 optionally followed by one or more ASCII digits from 0 to 9 interspersed with underscores, representing a positive integer.
[...]
A hexadecimal numeral consists of the leading ASCII characters 0x or 0X followed by one or more ASCII hexadecimal digits interspersed with underscores, and can represent a positive, zero, or negative integer.
[...]
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.
[...]
A binary numeral consists of the leading ASCII characters 0b or 0B followed by one or more of the ASCII digits 0 or 1 interspersed with underscores, and can represent a positive, zero, or negative integer.
如果你问为什么下划线不必在十进制文字的三位数字组中,不同的文化对数字进行不同的分组 - 当然对于十六进制和二进制文字,取决于用法,你可能想要各种不同的明显分组。
为什么以下操作有效?
int a=1_2_3_4;
System.out.println(a); // 1234
在 JLS 3.10.1 中指定了数字文字。
A decimal numeral is either the single ASCII digit 0, representing the integer zero, or consists of an ASCII digit from 1 to 9 optionally followed by one or more ASCII digits from 0 to 9 interspersed with underscores, representing a positive integer.
[...]
A hexadecimal numeral consists of the leading ASCII characters 0x or 0X followed by one or more ASCII hexadecimal digits interspersed with underscores, and can represent a positive, zero, or negative integer.
[...]
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.
[...]
A binary numeral consists of the leading ASCII characters 0b or 0B followed by one or more of the ASCII digits 0 or 1 interspersed with underscores, and can represent a positive, zero, or negative integer.
如果你问为什么下划线不必在十进制文字的三位数字组中,不同的文化对数字进行不同的分组 - 当然对于十六进制和二进制文字,取决于用法,你可能想要各种不同的明显分组。