Using underscores in big numbers makes them easier to read.
You can use any number of underscores between two digits in numeric literals.
For example, an int literal 99999 can be written as 9_9999, 999_99, 9999_9, 99___999.
The use of underscores is also allowed in octal, hexadecimal, and binary formats.
You cannot use underscores in the beginning or end of a numeric literal.
You cannot use underscores with prefixes such as 0x for hexadecimal format and 0b for binary format, and suffixes such as L for long literal and F for float literal.
You CAN use underscores after the first zero in an int literal in octal format. For example, write 02654 as 0_2654.
The following examples show the invalid uses of underscores in numeric literals:
Literal | Error |
---|---|
_1969; | An error. Underscore in the beginning |
1969_; | An error. Underscore in the end |
0x_DEAD; | An error. Underscore after prefix 0x |
0_xDEAD; | An error. Underscore inside prefix 0x |
9999_L; | An error. Underscore with suffix L |
9999_.0919; | An error. Underscore before decimal |
9999._0919; | An error. Underscore after decimal |
The following examples show the valid uses of underscores in numeric literals:
x1 = 99_999; // Underscore in deciaml format x2 = 99__999; // Multiple consecutive underscores x3 = 03_123; // Underscore in octal literal x4 = 0b0111_1011_0001; // Underscore in binary literal x5 = 0x7_B_1_E; // Underscores in hexadecimal literal b1 = 1_2_7; // Underscores in decimal format d1 = 99_999.09_19; // Underscores in double literal
public class Main { public static void main(String[] args) { int x1 = 99_999; // Underscore in deciaml format int x2 = 99__999; // Multiple consecutive underscores int x3 = 03_123; // Underscore in octal literal int x4 = 0b0111_1011_0001; // Underscore in binary literal int x5 = 0x7_B_1_E; // Underscores in hexadecimal literal byte x6 = 1_2_7; // Underscores in decimal format double x7 = 99_999.09_19; // Underscores in double literal System.out.println(x1);// w w w .j a va 2 s . c o m System.out.println(x2); System.out.println(x3); System.out.println(x4); System.out.println(x5); System.out.println(x6); System.out.println(x7); } }