简体   繁体   中英

Java - Multiplication not working as expected

the below code gives me -1894967296 as result but this is not expected. What is exactly happening? I can't figure it out. The result has to be 2400000000 as per my calculator :(

import java.util.List;
import java.util.ArrayList;
public class Calculate{
     public static void main(String []args){
        int result = 1;
        List<Integer> integer = new ArrayList<Integer>();
        integer.add(100);
        integer.add(200);
        integer.add(300);
        integer.add(400);
        for (Integer value : integer) {
            result *= value;
        }
        System.out.println(result);
     }
}

When I debug, it works correctly till the third iteration.

Update:

As per the answers, the int primitive type range has been exceeded but what will happen to the int variable? It will be defaulted to some value?

The largest number Java can store in an int is 2^31 - 2147483648

2400000000 is larger than that so "wraps around".

You need to use a 64 bit data type such as long .

2400000000 is too large to store in an int. It would be more appropriate to use a long which has a minimum value of -2^63 and maximum value of 2^63 - 1 which your number is well within the range of.

The expected result 2400000000 > Integer.MAX_VALUE . So, use long instead of int to store result.

Use BigInteger instead of int because the int is limited

Java doc:

int : By default, the int data type is a 32-bit signed two's complement integer, which has a > minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.

That's what most programmer call Pillage. You shouldn't save a long value inside a small variable, don't expect an Int to save a value 2^31+. For what you want to do there's a long

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