分配参数类型对整数溢出的影响

The effect of assigning parameter types on integer overflow

我很难理解 java 在以下场景中的行为。例如,我有一个 multiply 方法,它简单地将两个 int 值相乘并将结果打印到屏幕。

private static void multiply() {

    int firstValue = Integer.MAX_VALUE;
    int secondValue = 2;                   //double secondValue=2 

    double result = firstValue * secondValue;

    System.out.println("Result is: " + result);
}

并且由于整数溢出,结果为-2。然而,这里的计算结果被分配给一个双精度值,它接受的值比 firstValue 和 secondValue 的乘积大得多。

我对这个问题的问题是;

1-虽然结果赋给了double,但为什么会发生Integer溢出?

2- 当我把secondValue的类型改成double(评论里有提到),结果是正确的。当其中一个乘法器的类型更改为 double 时,为什么 Java 表现不同?

这是意料之中的,因为当您将 2 个整数相乘时,结果只是一个整数。当您使用 double 作为字段之一时,它与其他方式一起使用,结果将被视为 double 值。接收者数据类型在这里无关紧要

Java不支持target type casting

private static void multiply() {

    int firstValue = Integer.MAX_VALUE;
    int secondValue = 2;
    double one = 1.0;
    double result = one * firstValue * secondValue;

    System.out.println("Result is: " + result);
}

Target Type casting 表示将 result 的值转换为它必须分配给的变量的类型。
所以它不知道必须将结果分配给 double 变量。在这种情况下,int 是最大的数据类型,因此表达式以 int 数据类型计算。
如果将它与 double 相乘,则表达式按 double 类型计算,答案正确。

两个 int 相乘的结果是 int,它可能溢出也可能不溢出,这取决于乘法的值。一旦产生这个结果,它只会在可能发生溢出后被提升为 double

如果其中一个操作数是 double,乘法的结果将是 double,这允许比 int.[=16 大得多的范围=]