简体   繁体   中英

Java Integer Max Range multiplication

Integer num = 2147483647;
Integer res =  num * num;
System.out.println(res);

The Out put for above is 1. Am not sure why. Can someone please explain.

Thanks in advance.

This is supposed to demonstrate why result = 1:

    long x = Integer.MAX_VALUE;
    long y = Integer.MAX_VALUE;
    long res = x * y;
    System.out.println(Long.toHexString(res));

prints

3fffffff00000001

if we cast res to int we will get 1

It's because of Integer overflow. Java has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive) and your result(res) is beyond Integer max range.

this because of the flag value
0: iconst_0
1: istore_1

As the limit is out of range for Integer it will set the flag of 1 for more about how it works use this link

That's because it overflows the range of integer and even long which is between -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

You should try using BigInteger if that's the case like:

String num = "2147483647";
BigInteger mult = new BigInteger(num);
System.out.println(mult.multiply(mult));

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