带下划线的Java数字字面量

Java允许你在数字字面量中使用下划线。此功能是Java 7中引入的。例如, 该功能使你可以分隔数字字面量中的数字组, 这可以提高源代码的可读性。
以下几点很重要:
你不能在数字的开头或结尾使用下划线。

Ex. int a = _10; // Error, this is an identifier, not a numeric literal Ex. int a = 10_; // Error, cannot put underscores at the end of a number

【带下划线的Java数字字面量】你不能在浮点文字中的小数点附近使用下划线。
Ex. float a = 10._0; // Error, cannot put underscores adjacent to a decimal point Ex. float a = 10_.0; // Error, cannot put underscores adjacent to a decimal point

你不能在F或L后缀之前使用下划线
Ex. long a = 10_100_00_L; // Error, cannot put underscores prior to an L suffix Ex. float a = 10_100_00_F; // Error, cannot put underscores prior to an F suffix

你不能在需要一串数字的位置使用下划线。
数字字面量示例中的下划线
public class UnderscoreInNumericLiteralExample { public static void main(String[] args) { // Underscore in integral literal int a = 10_00000; System.out.println("a = "+a); // Underscore in floating literal float b = 10.5_000f; System.out.println("b = "+b); // Underscore in binary literal int c = 0B10_10; System.out.println("c = "+c); // Underscore in hexadecimal literal int d = 0x1_1; System.out.println("d = "+d); // Underscore in octal literal int e = 01_1; System.out.println("e = "+e); } }

输出:
a = 1000000 b = 10.5 c = 10 d = 17 e = 9

    推荐阅读