Prasanna Kumar - 6 months ago 37

Java Question

I think much explanation is not required, why below calculation gives result as 1?

`int a = 2147483647;`

int b = 2147483647;

int c = a * b;

long d = a * b;

double e = a * b;

System.out.println(c); //1

System.out.println(d); //1

System.out.println(e); //1.0

Answer

The binary representation of the integer number 2147483647 is as following:

```
01111111 11111111 11111111 11111111
```

Multiplying this with itself results in the number 4611686014132420609 whose binary representation is:

```
00111111 11111111 11111111 11111111 00000000 00000000 00000000 00000001
```

This is too large for the `int`

type which has only 32 bits. The multiplication of `a * b`

is done as an integer multiplication only, regardless of the variable's type to which the result is assigned (which might do a widening conversion, but only after the multiplication).

So, the result simply cuts off all bits that do not fit into the 32 bits, leaving only the following result:

```
00000000 00000000 00000000 00000001
```

And this simply is the value 1.

If you want keep the information, you must do the multiplication with the `long`

type which has 64 bits:

```
long a = 2147483647;
long b = 2147483647;
long mult = a * b;
System.out.println((int) mult); // 1
System.out.println(mult); // 4611686014132420609
System.out.println((double) mult); // 4.6116860141324206E18
```

If you need more bits for a calculation you might consider `BigInteger`

(for integral numbers) or `BigDecimal`

(for decmial numbers).