Since version 7, Java has improved literal number formatting by allowing underscore in numbers. It makes reading numbers easy in the application source code.
For example, if we have to read the number “1000000“, then how much more convenient is it to read at first sight? Not much, right?? We have a habit of reading numbers in 10,00,000 format. The good news is that java has started supporting writing numbers in this format. Well, not exactly this but a matching format using underscores. For example, we can write the same number as 10_000_000.
1. Writing Numeric Literals with Underscores
Underscores can appear anywhere between digits in a numerical literal. We can use the underscores in all literal types:
Note that consecutive underscores are allowed. ’10___00′ is a valid number.
//Supported in byte byte improvedByte = 0b0010_0101; //Supported in int int improvedInt = 10_00_000; //Supported in long long improvedLong = 10_00_000l; //Supported in float float improvedFloat = 10_00_000.16f; //Supported in double double improvedDouble = 10_00_000.56d; //consecutive underscores int value = 10__00;
2. Where are underscores not allowed?
Note a few important things regarding places where we cannot place the underscore.
- Underscores can be placed only between digits. We cannot put an underscore next to the decimal separator ‘dot’.
- To put an underscore at the last of the number is not allowed. ‘1000_’ is NOT a valid number. It will generate compile time error.
- In Java, an underscore in front of the variable name is allowed. Be careful when you put an underscore at the start of the number. It is a variable, not a number.
- Before or after the
//adjacent to decimal point float value = 10_.12F; float value1 = 10._12F; //adjacent to F or L float value2 = 10.12F_; float value3 = 10_.12_F; //at start or end int value = 10_; int value = _10;
This short Java tutorial taught us to use underscores between digits in java numerical literals. This feature helps to separate groups of digits in numeric literals, which can improve the readability of your code.
Happy Learning !!