Can you use underscores in numbers in Java? I saw this code in a blog, and it works, but will it continue to work in the future? Is it a feature or a bug?
long oneBillion = 1_000_000_000L;
Underscores ( _ ) in numeric literals are one of Java 7's features. Any numeric literal, such as int , byte , short , float , long , or double , can have underscores between its digits.
In most of programming language like Java and C/C++ , the number with leading zero are interpreted as octal number. As we know octal numbers are only represented within 0 to 7 digits only. Hence numbers like 05 , 03 , 054 are valid but the numbers like 078 , 0348 , 09 , 08 are tends to invalid.
The following rules govern the formation of numeric literals: A literal must contain at least one digit. A literal must contain no more than one sign character and, if one is used, it must be the leftmost character of the string. A literal must not contain more than one decimal point.
You cannot use underscore at the beginning or end of a number. You cannot use underscore adjacent to a decimal point in a floating point literal. You cannot use underscore in positions where a string of digits is expected.
It's a feature, new in Java 7. You can rely on it remaining. There are some restrictions, though; see the documentation.
Java 7 supports the feature of having underscores in the numeric literals to improve the readability of the values being assigned.
but the underscore usage is restricted to be in between two numeric digits, i.e not at the beginning or ending of the numeric values but should be confined between two digits, should not be as a prefix to l,f used to represent long and float values and not in between radix prefixes also.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With