4
private static final int FIRST  = 8;
private static final int SECOND = (4 * 1024 * 1024)/8;
private static final int THIRD = (4 * 1024 * 1024);
private static final long RESULT  = FIRST *SECOND * THIRD;

Why is the product of the 3 coming out to be 0?

user1071840
  • 3,522
  • 9
  • 48
  • 74
  • possible duplicate of [Why do these two multiplication operations give different results?](http://stackoverflow.com/questions/12758338/why-do-these-two-operations-give-different-results) – Rohit Jain Aug 22 '13 at 07:42

1 Answers1

9

Why is the product of the 3 coming out to be 0?

Your multiplication is being done in int arithmetic, and it's overflowing, with a result of 0. You're basically doing 224 * 224, i.e. 248 - and the bottom 32 bits of that results are all 0. The fact that you assign the result of the operation to a long doesn't change the type used to perform the operation.

To perform the arithmetic using 64-bit integer arithmetic, just change an operand to be long:

private static final long RESULT  = (long) FIRST * SECOND * THIRD;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Oh, so as long as even one operand is of the higher precision each of the operands will be converted to match that, and since in this case my result is long..things will give expected results. Cool..Thanks – user1071840 Aug 22 '13 at 07:54
  • @user1071840: Yes. See section 15.17 of the JLS for details. – Jon Skeet Aug 22 '13 at 08:03