如果两个值具有不同的数据类型,Java 会自动将其中一个值提升为两种数据类型中较大的一个吗?

If two values have different data types, Java will automatically promote one of the values to the larger of the two data types?

规则说如果两个值具有不同的数据类型,Java 会自动将其中一个值提升为两种数据类型中较大的一个?

在下面的代码中,分配给 y 的值大于 x 的值。因此,考虑到规则,打印的值应该是 "Float" 但它打印的是“Double。你能问问为什么它打印 Double 而不是 Float 吗?

    Double x = 3.21; 

    Float y = 4.1f;

    Object o  = (x*y);

    System.out.println( o.getClass().getSimpleName() ); // prints out Double

变量的值无关紧要。他们的类型很重要。 double 是 8 字节类型,float 是 4 字节类型。因此,要将 doublefloat 相乘,您可以将较小类型 (float) 的变量提升为较大类型 (double)。

如果您将 DoubleFloat 相乘,它们将被拆箱为 doublefloat。为了将 doublefloat 相乘,float 将提升为 double,并且会发生 double 乘法。

由于结果存储在 Object 中,因此 double 结果将被装箱到 Double.

"Larger" 不是指“>”值,而是(简而言之)指可以包含更多信息的数据类型,例如Double 优于 Float,Long 优于 Int。

这在此处记录:https://docs.oracle.com/javase/specs/jls/se13/html/jls-5.html#jls-5.6.2

您误解了 "larger" 在短语 "the larger of the two data types" 中的意思。如果是"the larger of the two values",那你的理解就对了。

大型数据类型是一种占用更多内存的数据类型。 double 占用 64 位,而 float 占用 32 位,因此 double 是较大的数据类型。

请注意,此行为(二进制数字提升)仅适用于数字类型,不能真正用 "If two values have different data types, Java will automatically promote one of the values to the larger of the two data types" 等单一规则来描述。例如,short 乘以 byte 得到 int。这在 Java 语言规范中有完整规定。

有关详细信息,请参阅 section 5.6.2 in the Java Language Specification