1
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.

Aditya
  • 1,033
  • 3
  • 11
  • 24

4 Answers4

1

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

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.

Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
0

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

Community
  • 1
  • 1
Bhargav Modi
  • 2,605
  • 3
  • 29
  • 49
0

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));
SMA
  • 36,381
  • 8
  • 49
  • 73