简体   繁体   English

Java Integer最大范围乘法

[英]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. 上面的输出是1.不确定为什么。 Can someone please explain. 有人可以解释一下。

Thanks in advance. 提前致谢。

This is supposed to demonstrate why result = 1: 这应该证明为什么结果= 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 如果我们将res转换为int,我们将得到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. Java的最小值为-2,147,483,648,最大值为2,147,483,647(含),并且您的结果超出了Integer max范围。

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 由于限制是超出范围的Integer它将设置的标志1为进一步了解它是如何工作使用这个链接

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). 这是因为它会溢出整数范围,甚至是-2,147,483,648和最大值2,147,483,647(含)之间的较长范围。

You should try using BigInteger if that's the case like: 如果是这样,您应该尝试使用BigInteger:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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