Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does Java handle the intermediate values while evaluating a long arithmetic expression?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

JLS 15.17.1:

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.

JLS 15.18.2:

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading