In Java SE 7 and later versions, numbers in the numeric literal value can contain any number of underscores. For example, this feature allows you to separate numbers in a numeric literal value into groups to improve code readability.
For example, if your code contains many numbers, you can use underscores to divide these numbers into three groups, the same as using punctuation marks (commas or spaces) as separators.
The following example shows some other ways to use underscores in a numeric literal:
long creditCardNumber = 1234_5678_9012_3456L;long socialSecurityNumber = 999_99_9999L;float pi = 3.14_15F;long hexBytes = 0xFF_EC_DE_5E;long hexWords = 0xCAFE_BABE;long maxLong = 0x7fff_ffff_ffff_ffffL;byte nybbles = 0b0010_0101;long bytes = 0b11010010_01101001_10010100_10010010;
You can only place the underline between numbers. The underline cannot be placed in the following places:
The position near the decimal point in the starting or ending floating point number.
F
Or
L
The place where a string of numbers is expected to be placed before the suffix.
The following example shows the valid and invalid underline positions (highlighted) in the numeric literal value ):
float pi1 = 3_.1415F; // Invalid; cannot put underscores adjacent to a decimal pointfloat pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal pointlong socialSecurityNumber1 = 999_99_9999_L; // Invalid; cannot put underscores prior to an L suffixint x1 = _52; // This is an identifier, not a numeric literalint x2 = 5_2; // OK (decimal literal)int x3 = 52_; // Invalid; cannot put underscores at the end of a literalint x4 = 5_______2; // OK (decimal literal)int x5 = 0_x52; // Invalid; cannot put underscores in the 0x radix prefixint x6 = 0x_52; // Invalid; cannot put underscores at the beginning of a numberint x7 = 0x5_2; // OK (hexadecimal literal)int x8 = 0x52_; // Invalid; cannot put underscores at the end of a numberint x9 = 0_52; // OK (octal literal)int x10 = 05_2; // OK (octal literal)int x11 = 052_; // Invalid; cannot put underscores at the end of a number
This article is translated from the Oracle official documentation workshop!