Underscores (_
) in numeric literals are one of Java 7’s features. Any numeric literal, such as int
, byte
, short
, float
, long
, or double
, can have underscores between its digits.
When you use underscores in numeric literals, you may separate them into groups for better readability.
Underscores can only be between digits and numerals.
There are no underscores allowed adjacent to decimal places, the L/F suffix, or the radix prefix. As a result, 10_.32
, 8_L
, and 0x _343
are incorrect and will result in a compilation error.
Between numbers, multiple underscores are permitted. Therefore, 10___1239
is an acceptable number.
At the end of a literal, you can’t use underscores. As a result, 543_
is invalid, resulting in a build time error.
When an underscore is placed before a number literal, it is interpreted as an identifier rather than a numeric literal. For example: int _10=0;
, int x = _10;
.
When expecting a string with numbers, underscores can’t be used. For example, Integer.parseInt("10__90")
, throws java.lang. NumberFormatException
.
public class Main{public static void main(String[] args) {// single underscore between digitslong ssn = 132_43_6543L;// multiple underscores between digitslong ssnMultipleUnderscores = 132_43_654____3L;// underscore in floating pointfloat floatingPoint = 10.32_5F;// underscores between byteslong hexadecimalBytes = 0xFF_EC_DE_5E;// underscores between wordslong hexadecimalWords = 0xCAFE_BABE;// underscores in binarybyte byteInBinary = 0b0010_0101;// underscores in additionint add = 12_3 + 4_5_6;}}
The following syntax with underscores is invalid and will lead to compilation errors.
long ssnInvalid = 132_43_6543L_;
long ssnInvalid = _132_43_6543L;
float floatingPointInvalid = 10._32_5F;
float floatingPointInvalid = 10_.32_5F;
Integer.parseInt("23_32");