I was wondering how does Java handle the intermediate values while evaluating a mathematical expression specially when the intermediate values exceeds their storage size. For an example,
int a = 1103515245;
int x = 1013904223;
int c = 2531011;
x = (a*x + c) & 0x7FFFFFFF; // to make sure x will remain a positive integer.
Now, my question is while computing a*x
, its value exceeds integer range (even during the addition it could happen), how this is taken care by Java Compiler?
Thank you.
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.
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format.
This is in contrast to C, which famously does not assume a two's-complement architecture and treats overflow of signed types as undefined behavior.