How to use underscores for numerical literals in Java
- Details
- Written by Nam Ha Minh
- Last Updated on 17 August 2019   |   Print Email
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:
- At the beginning or end of a number.
- Adjacent to a decimal point in a floating point literal.
- Before an F or L suffix.
- In positions where a string of digits is expected.
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 |
Related Tutorials:
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand Java Access Modifiers
- Understand how variables are passed in Java
- Understand Encapsulation in Java
Comments