Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java multiplication between int and longs gives 0

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?

like image 976
user1071840 Avatar asked Feb 16 '23 12:02

user1071840


1 Answers

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;
like image 80
Jon Skeet Avatar answered Feb 20 '23 10:02

Jon Skeet