简体   繁体   中英

Double Integer value overflow

I am trying to understand the behavior of the code below which I wrote to experiment on calculation overflow.

public static void main(String[] args) {

    System.out.println(getSomeValue());
    System.out.println(getFixedSomeValue());
}

private static double getSomeValue() {
    return (2500000 - 0) * 250000 * (200 + 310);
}

private static double getFixedSomeValue() {
    return (double) (2500000 - 0) * 250000 * (200 + 310);
}

output:

-9.9787264E8
3.1875E14

What I have understood is: It can be because of Integer overflow as:

Double.MAX_VALUE = 1.7976931348623157E308
Integer.MAX_VALUE = 2147483647

I don't understand why the values differ? When the return type of method is double, shouldn't it automatically cast it to double?

(2500000 - 0) * 250000 * (200 + 310) is an expression comprised of int literal and numeric operators, so it is evaluated using integer operators and the result is an int , and therefore overflows (since it is limited to Integer.MAX_VALUE ). The overflown result is converted to double before the method returns, but that's too late.

When you add (double) at the beginning, you cast (2500000 - 0) to double and avoid the numeric overflow, since now all the operators are floating point operators that result in double value. This is similar to writing

return (2500000.0 - 0) * 250000 * (200 + 310)
               ^ decimal point = double literal rather than int

Yes and no. Upon return it casts it to double but the calculations are done in integer format which upon reaching the max value it starts from the min value again. So if you do INT_MAX + 1 you will get INT_MIN and that is why you are getting a negative result in double.

When the return type of method is double, shouldn't it automatically cast it to double?

It does, just not perhaps where you mean.

private static double getSomeValue() {
    return (2500000 - 0) * 250000 * (200 + 310);
}

is the same as:

private static double getSomeValue() {
    int e = (2500000 - 0) * 250000 * (200 + 310);
    return (double) e;
}

ie the expression is evaluated using int , and then cast to double at the very end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM