Multiplication of two ints overflowing to result in a negative number

前端 未结 5 1224
离开以前
离开以前 2020-12-01 21:27

Consider this snippet from the Java language specification.

class Test {
    public static void main(String[] args) {
        int i = 1000000;
        System         


        
5条回答
  •  星月不相逢
    2020-12-01 22:01

    The reasons why integer overflow occurs have already been explained in other answers.

    A practical way to ensure long arithmetic in calculations is to use numeric literals with l suffix that declare the literals as long.

    Ordinary integer multiplication that overflows:

    jshell> 100000 * 100000
    $1 ==> -727379968
    

    Multiplication where one of the multiplicands has l suffix that does not overflow:

    jshell> 100000 * 100000l
    $1 ==> 1000000000000
    

    Note that longs are also prone to overflow, but the range is much greater, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

提交回复
热议问题