0

Why does the following work?

int a=1_2_3_4;
System.out.println(a);   // 1234
paidedly
  • 1,413
  • 1
  • 13
  • 22

1 Answers1

4

Numeric literals are specified in JLS 3.10.1.

A decimal numeral is either the single ASCII digit 0, representing the integer zero, or consists of an ASCII digit from 1 to 9 optionally followed by one or more ASCII digits from 0 to 9 interspersed with underscores, representing a positive integer.

[...]

A hexadecimal numeral consists of the leading ASCII characters 0x or 0X followed by one or more ASCII hexadecimal digits interspersed with underscores, and can represent a positive, zero, or negative integer.

[...]

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

[...]

A binary numeral consists of the leading ASCII characters 0b or 0B followed by one or more of the ASCII digits 0 or 1 interspersed with underscores, and can represent a positive, zero, or negative integer.

If you're asking why the underscores don't have to be in groups of three digits for decimal literals, different cultures group numbers differently - and certainly for hex and binary literals, depending on the usage, you could want all kinds of different obvious groupings.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • But what is the rationale behind making such literals valid?. Isn't it better to let such literals with underscores not compile? – paidedly Jun 13 '15 at 07:04
  • 1
    One benefit is to make long numbers more readable by using underscore to indicate grouping; or to indicate structure. – Brett Walker Jun 13 '15 at 07:07
  • @paidedly: it can aid readability - particularly of large numbers, similar to the way that numbers in print often have their digits grouped in 3's or 4's with a comma or period (both depending on your culture). C++14 has added a similar feature, using a single quote character instead of an underscore to be able to group/separate digits within a numeric literal. – Michael Burr Jun 13 '15 at 07:07