Underscores in Numeric literals are allowed starting from Java 7, to improve the readability of large numbers.
Underscores in Numeric Literals Java 7
Suppose if you want to represent a large number like 1 trillion in java code, you will represent it as 1000000000000. Until you name the variable name as 1 trillion, developers can’t understand the value just by looking at the number.
How about representing it as 1,000,000,000,000? Yes, this is more readable and based on the number of commas (,), you can easily figure out the value.
Underscores in Numeric Literals
Underscores in Numeric literals is exactly the same concept explained above. But we are not going to separate large numbers by comma (,), but with underscore(_). Since comma already has a significance in Java like for separation of variables, they might have come-up with underscore.
So from Java 7, you can start representing numbers using underscores.
Below are some of valid and invalid scenarios to use underscore(_):
- It should be used only between digits like
long aadharCardNumber = 9632_5874_1236_5478L;
- It cannot be used at the beginning of the number
long hexBytes =0xFF_EC_DE_5E;
long hexBytes = _0xFF_EC_DE_5E;
- It cannot be used at the end of number
float dollarValue = 66.77_5f;
float dollarValue = 66.77_5_f;
- It cannot be used next to a decimal point in floating point number
double petrolPrice = 77.24;
double petrolPrice = 77._24l
- It cannot be used before F(floating) and L(long) suffixes
private static final long serialVersionUID = 4046799913406610513L;
private static final long serialVersionUID = 4046799913406610513_L;
- In positions where a String of digits expected like parsing in wrapper classes
Float pi = Float.parseFloat("3.14");
Float pi = Float.parseFloat("3.1_4"); //throws NumberFormatException
Points to note:
We can use underscores (_) only in between the digits; you cannot place underscores in the following places:
- We can not use beginning or end of a number
- Adjacent to a decimal point in a floating point literal
- Prior to an F or L suffix
- In positions where a string of digits is expected
Happy Learning 🙂