为什么在 Java 中声明非十进制浮点数时不需要 'f'?

Why isn't 'f' necessary when declaring a non-decimal float in Java?

如果在 Java 中声明浮点数时需要 'f' 后缀,因为双精度是默认值,为什么当浮点数是 a 时不使用 'f' 是可以接受的非十进制?

float myFloat = 123.45 // not ok because double is the default
float myFloat = 123.45f // ok because the float is explicit

float myFloat = 123 // ok, but why? isn't it still a double by default?

123 是一个 int 值,默认情况下作为扩大转换提升为 float

int i = 123;
float f = i;

反之则不然

float f = 123;
int i = f; // <-- the compile-time error

19 specific conversions on primitive types are called the widening primitive conversions:

...
int to long, float, or double
...

123 字面值默认为 int,不是双倍的。将 int 文字分配给 float 没有问题,因为这需要扩大原始转换。

将表达式的值赋给变量时,允许进行以下赋值:

JLS 5.2. Assignment contexts :

Assignment contexts allow the value of an expression to be assigned (§15.26) to a variable; the type of the expression must be converted to the type of the variable.

Assignment contexts allow the use of one of the following:

  • an identity conversion (§5.1.1)

  • a widening primitive conversion (§5.1.2)
    ...

JLS 5.1.2. Widening primitive Conversion

19 specific conversions on primitive types are called the widening primitive conversions:

  • byte to short, int, long, float, or double

  • short to int, long, float, or double

  • char to int, long, float, or double

  • int to long, float, or double
    ...