简体   繁体   中英

Primitives data types overflow in Java

int num=Integer.MAX_VALUE*Integer.MAX_VALUE;

Why does this line not give an error of incompatibility in Java because the result is overflow the limit of int ?

Can someone elaborate?

The multiplication operator * allows this. Section 15.17.1 of the JLS states:

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.

In short, with int values, overflow is allowed and is not an error. However, some IDEs may flag this line as a warning (IntelliJ appears to warn about this). But this compiles, and when I print out num , I get 1 , which is the result of the overflow.

Mathematically, define x to be Integer.MAX_VALUE + 1, or 2 31 . Then num is (x - 1) 2 , or (x 2 -2x + 1). In Java, when this overflow occurs, it's as if the result is taken (mod 2 32 ), which evaluates to 1.

The Java language specification gives a precise meaning for calculations that overflow the data type: any operation on ints for example uses the 32 least significant bits of the result. There is no ambiguity, and no reason to throw an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM