No error using underscore and prefix

The following code:

int i = 0_10; System.out.println(i); 

outputs the result:

-

It is written in javadocs that we cannot put underscores at the beginning of a number, as in the example int x5 = 0x_52; which causes the illegal underscore error.

However, in this code, 0 is a prefix for octal numbers, since we see that output is 8 . But the error does not occur.

  • The value is i 8 , which means that 0_10 is an octal number and 0 is a prefix.
  • But 0_10 does not cause an illegal flaw error , which means that 0 not a prefix, but part of the number.

Why does this not lead to an error? Does Java treat it partially as octal and partially not?

+5
source share
1 answer

Because JLS says :

Underscores are permitted as delimiters between numbers that represent an integer.

(My emphasis) The underscore at 0x_52 not between the numbers.

Yes, it’s a little strange that the indicator of a number in octal is only that it starts with 0 (it is not followed by x ). And that caused No End Of Confusion, but it ( 0 ) is a digit, and therefore 0_10 complies with JLS rules.

It should be explicit:

In a hexadecimal or binary literal, an integer is indicated by digits only after the characters 0x or 0b and before the suffix of any type. Therefore, underscores may appear immediately after 0x or 0b or after the last digit in a digit.

In decimal or eighth literal, an integer is denoted by all digits in the literal before the suffix of any type.

Note the difference. (For clarity: “type suffix” they talk about l / l for “long”, f / f for “float”, etc.)

Is java partially processed as octal and partially not?

This is not true. 0 is part of the number, as well as an indicator of the number in octal. This is a strange musical notation from C in the 1970s that got Java inherited when Gosling developed it to use syntax similar to C in the 1990s.

It is worth noting that this bizarre notation caused a sufficient problem that when they finally officially added the octal link to JavaScript (another language also uses the same syntax), they used 0o as a prefix instead. (Prior to the 2015 specifications, JavaScript did not have an official octal form, although the 2009 specification made a note that some implementations did case C. In terms of the 2009 specifications, they were not allowed in strict mode, and the 2015 spec introduced 0o . [In the 2015 specification, they also made the old "obsolete" form required by browsers [only] in free mode, for compatibility reasons.])

+2
source

Source: https://habr.com/ru/post/1241888/


All Articles