Using underscore in Numeric Literals in Java
When Java was introduced, use of underscore in numeric literals was not allowed but from java version 1.7 onwards we can use ‘_’ underscore symbols between digits of numeric literals. You can place underscores only between digits. Do remember there are certain places where we can not place underscores as listed below as follows:
- At the 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
- We can use underscore symbols only between the digits if we are using else we will get a compile-time error.
Let us discuss illustrations in order to justify the above said as follows:
Illustration 1: Valid usage of underscore in numeric literals
Input : int i = 12_34_56; Output : 123456 Input : double db = 1_2_3.4_5_6 Output : 123.456
Illustration 2: Invalid usage in numeric literals
int i = _12345; // Invalid as this is an identifier, not a numeric literal
double db = 123._456; // Invalid as we cannot put underscores adjacent to a decimal point
double db 123_.456_; // Invalid as we cannot put underscores at the end of a number
Now geek you must be wondering out why it was introduced so basically the the main advantage of this approach is the readability of the code will be improved. At the time of compilation, these underscore symbols will be removed automatically. We can use more than one underscore symbol also between the digits too. For example, the following is a valid numeric literal as shown below:
int x4 = 5_______2; // OK (decimal literal)
Implementation: Make sure before writing code we do have java version 1.7 and onwards as discussed in header itself. In order to check, open terminal and write below command and if not so install latest java version and we are good to go if already updated.
i = 123456 db = 123.456 x4 = 52
This article is contributed by Shivakant Jaiswal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.