Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double Integer value overflow

Tags:

java

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?

like image 626
impossible Avatar asked May 23 '26 16:05

impossible


1 Answers

(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
like image 102
Eran Avatar answered May 25 '26 06:05

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!