mackanmorre
mackanmorre

Reputation: 145

Why in one case multiplying big numbers gives a wrong result?

This might seem simple but I don't have any answer. When I write:

 System.out.println (100 * 1000 * 10000 * 100000);
 System.out.println (100 * 1000 * 10000 * 100000.0);

it returns these values:

276447232
1.0E14

I understand that this has something to do with maximum values of some data types. But I would just like a clear answer as to why it returns these exact values for both equations. If someone can explain this to me I will be very appreciative.

The first return doesn't match the maximum value for int datatype, that's why I'm confused. And the second return I'm assuming is a double or float value, but I'm not sure.

Upvotes: 2

Views: 1505

Answers (1)

Ortomala Lokni
Ortomala Lokni

Reputation: 62496

In the expression

System.out.println (100 * 1000 * 10000 * 100000);

The parameter is an int and the result exceeds the maximum value admissible for an int which is 2147483647. This is what we call an overflow. According to the Java Language Specification

If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format.

Taking the N low-order bits of a number is equivalent to computing the remainder of the division of this number by 2^N. In our case, N=32 because int are stored on 32 bits. This why Jon Skeet answered by saying

100000000000000 % (2^32) is 276447232.

In the expression

System.out.println (100 * 1000 * 10000 * 100000.0);

The product of the three first factor 100 * 1000 * 10000 gives 1_000_000_000 which is less than the maximum int value. The last multiplication leads to a Binary Numeric Promotion which means, in this case, that 1_000_000_000 is converted (promoted) to double and then multiplied by 100000.0.

Upvotes: 6

Related Questions