Search code examples
javafloating-pointhexambiguity

Java Hexadecimal Floating Point Literal Ambiguity


In Java specification, it says the following:

For hexadecimal floating-point literals, at least one digit is required (in either the whole number or the fraction part), and the exponent is mandatory, and the float type suffix is optional. The exponent is indicated by the ASCII letter p or P followed by an optionally signed integer.

As I understand, the exponent indicating letter has to be p or P to resolve ambiguity with the hexadecimal digit e or E. Why does it then say that the suffix indicating type (float vs double) is optional, when using it would introduce ambiguity with letters d, D, f, F, which are also hexadecimal digits?


Solution

  • According to the grammar:

    DecimalFloatingPointLiteral:
      Digits . [Digits] [ExponentPart] [FloatTypeSuffix] 
      . Digits [ExponentPart] [FloatTypeSuffix] 
      Digits ExponentPart [FloatTypeSuffix] 
      Digits [ExponentPart] FloatTypeSuffix
    
    HexadecimalFloatingPointLiteral:
      HexSignificand BinaryExponent [FloatTypeSuffix]
    

    the optional FloatTypeSuffix must follow the mandatory BinaryExponent for a hex floating point number.

    If you add an f or a d without a BinaryExponent, it's a decimal floating point number.