Consider the following code:
int maxUploadSize = 20971520; long accountBalance = 1000000000000L; float pi = 3.141592653589F;
Of course most of us feel it’s difficult to read and estimate value of these numbers, e.g. how many zeroes here? How many numbers after the dot?... Sorry, my eyes are tired! So in Java SE 7 and later, you can put underscores between the digits to make the numbers more readable, like this:
int maxUploadSize = 20_971_520; long accountBalance = 1_000_000_000_000L; float pi = 3.141_592_653_589F;
Oh, it looks better right? Generally, you can put any number of underscores anywhere in the numerical literals. However, there are certain places you cannot:
For example, the following table lists some valid and invalid usages of the underscores in numerical literals:
Example | OK or Invalid | Reason |
int a = 12___34; | OK | decimal literal |
int b = 1234_; | Invalid | Cannot put underscores at the end of a number. |
int c = _1234; | Invalid | Cannot put underscores at the beginning of a number. |
long d = 1_000_L; | Invalid | Cannot put underscores before the L suffix. |
long e = 1_000L_; | Invalid | Cannot put underscores at the end of a number. |
float pi1 = 3_.141592F; | Invalid | Cannot put underscores adjacent to a decimal point. |
float pi2 = 3._141592F; | Invalid | Cannot put underscores adjacent to a decimal point. |
int x = 0x123_456; | OK | |
int y = 0_x123; | Invalid | Cannot put underscores in 0x radix prefix. |
int z = 0x_123; | Invalid | Cannot put underscores at the beginning of a number. |
int t = 0_123; | OK | octal literal |
int u = 0_123_456; | OK | octal literal |