Reputation: 1043
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.
Upvotes: 1
Views: 1360
Reputation: 136102
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
Upvotes: 1
Reputation: 37083
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));
Upvotes: 0
Reputation: 2655
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
Upvotes: 0
Reputation: 29316
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.
Upvotes: 0