2

Why does the output of the following code output 1345094336 instead of 39999800000? And how should i edit it? I believe it has got to do with integer overflow.

public class testC {
    public static void main(String[] args) {
        long product = 199999 * 200000;
        System.out.println(product);
    }
}
Yeo
  • 183
  • 2
  • 11

3 Answers3

4

Multiplication of two ints 199999 * 200000 is 39999800000 which is over than the integer

storage capacity.
          width                     minimum                         maximum

SIGNED
byte:     8 bit                        -128                            +127
short:   16 bit                     -32 768                         +32 767
int:     32 bit              -2 147 483 648                  +2 147 483 647
long:    64 bit  -9 223 372 036 854 775 808      +9 223 372 036 854 775 807

UNSIGNED
char     16 bit                           0                         +65 535

So you need to convert at least one number to long on the multiplication side Either

(long)199999 * 200000
199999 * (long)200000
199999 * 200000L
199999L * 200000
2

The numbers getting multiplied are presumed to be ints, and so that overflows, and setting it to long does not help.Use

long product = (long)199999 * (long)200000;

instead

Jeremy Kahan
  • 3,796
  • 1
  • 10
  • 23
2

You can change below line

long product = 199999 * 200000;

to

long product = 199999 * 200000L;

Since multiple of two integers is an integer and it overflows in this case, you have to make one of them a long.

lakshman
  • 2,641
  • 6
  • 37
  • 63