浮点数的二进制数字提升

Binary Numeric Promotion for Floats

在 5.6.2 的 JLS 中。二进制数字提升:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

If either operand is of type double, the other is converted to double.

Otherwise, if either operand is of type float, the other is converted to float.

Otherwise, if either operand is of type long, the other is converted to long.

Otherwise, both operands are converted to type int.

这让我很困惑,因为两者 http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.htmlhttps://alvinalexander.com/java/java-int-double-float-mixed-type-division-arithmetic-rules

说明

All floating point values (float and double) in an arithmetic operation (+, −, *, /) are converted to double type before the arithmetic operation in performed.

据我了解,根据 JLS,将 1 个浮点数和 1 个整数相加会得到一个浮点数。但是,根据其他来源,将 1 个浮点数和 1 个整数相加会导致 double?

当消息来源提出与 JLS 相悖的声明时,很可能是错误的。在这种情况下,以下演示了 JLS 描述的行为:

    Number n = 1 + 0.1f;
    System.out.println(n instanceof Float); // true
    System.out.println(n instanceof Double); // false