When we must use a _
to separate digits in a number I don't understand the following case in which I can't use it:
In positions where a string of digits is expected
(as documented in the JDK7 guide here)
Some examples?
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.
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.
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.
Explanation: Theoretically, there is no limit on the number of underscores. 17) Java uses UTF-16 Unicode format to represent characters.
You don't have to use "_", you can. And examples given in the proposal are credit card numbers, phone numbers, or simply numbers for which it makes sense to have a separator in the code.
For the "In positions where a string of digits is expected" it's simply in places where it's supposed to start (or end) with a digit. Here are some examples.
Note that according to this proposal, underscores can only be placed between digits. They cannot be placed by themselves in positions where a string of digits would normally be expected:
int x1 = _52; // This is an identifier, not a numeric literal.
int x2 = 5_2; // OK. (Decimal literal)
int x2 = 52_; // Illegal. (Underscores must always be between digits)
int x3 = 5_______2; // OK. (Decimal literal.)
int x4 = 0_x52; // Illegal. Can't put underscores in the "0x" radix prefix.
int x5 = 0x_52; // Illegal. (Underscores must always be between digits)
int x6 = 0x5_2; // OK. (Hexadecimal literal)
int x6 = 0x52_; // Illegal. (Underscores must always be between digits)
int x6 = 0x_; // Illegal. (Not valid with the underscore removed)
int x7 = 0_52; // OK. (Octal literal)
int x7 = 05_2; // OK. (Octal literal)
int x8 = 052_; // Illegal. (Underscores must always be between digits)
Resources:
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