-4

My understanding is that a long in java has a max value of 2^63-1. Any ideas why when storing 50000^2=2500000000 in a long I get -1794967296 considering 2500000000 is less than 2^63-1? Thanks

    long l = 50000 * 50000;
    System.out.println(l);

I expect the output to be 2500000000, but the actual output is -1794967296.

yonSon
  • 3
  • 4

1 Answers1

1

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. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.

You are multiplying two integers that overflow, then store the result in a long, which won't help.

You either have to explicitly use long literals:

 long l = 50000L * 50000L;
 long l = 50000L * 50000; // this also works

or cast to long before multiplying:

 long l = ((long) 50000) * ((long)50000);
 long l = ((long) 50000) * 50000; // this also works

See the spec to see why it is enough to only explicitly use one long literal or one casting to long.

Behrang
  • 46,888
  • 25
  • 118
  • 160