Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 7 underscore in numeric literals

Tags:

java

java-7

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?

like image 437
xdevel2000 Avatar asked Jun 02 '11 09:06

xdevel2000


People also ask

Can we use underscore in int in Java?

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 which of the following usage of underscore is incorrect?

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.

How do you write an underscore 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.

What is the maximum number of underscore character?

Explanation: Theoretically, there is no limit on the number of underscores. 17) Java uses UTF-16 Unicode format to represent characters.


1 Answers

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:

  • OpenJDK - Project Coin - PROPOSAL: Underscores in Numbers (Version 2)
  • Joe Darcy's blog - Project Coin: Project Coin: Literal Grammar Hackery
like image 196
Colin Hebert Avatar answered Oct 13 '22 12:10

Colin Hebert