Moshe9362 - 1 year ago 34

Java Question

first, sorry about my bad English...

today i tried to check if Integer.MAX_VALUE*Integer.MAX_VALUE

`System.out.println("long*long= "+Long.MAX_VALUE*Long.MAX_VALUE);`

System.out.println("int*int= "+Integer.MAX_VALUE*Integer.MAX_VALUE);

System.out.println("double*double= "+Double.MAX_VALUE*Double.MAX_VALUE);

System.out.println("float*float= "+Float.MAX_VALUE*Float.MAX_VALUE);

System.out.println("short*short= "+Short.MAX_VALUE*Short.MAX_VALUE);

the results:

long*long= 1

int*int= 1

double*double= Infinity

float*float= Infinity

short*short= 1073676289

why is that? if float^2=Infinity, so long^2 should also be Infinity... and 1 is clearly a mistake...

anyone have any idea? tnx

Answer

For seeing how integers multiply, use the binary notation. For simplicity's sake I use a 4 bit signed integer (where the MAX is 7), but the principle is the same for byte, short, int and long.

```
0111 x 0111
----
0111
0111
0111
-------
110001
The columns from right to left:
1) 1 => 1
2) 1+1 => 10 => 0 and carry 1c into 3)
3) 1+1+1+1c => 100 => 0 and carry 1c into 5) (sic! 5)
4) 1+1 => 10 => 0 and carry 1c into 5)
5) 1+1c+1c => 11
```

Higher order bits are irrelevant because truncated.

This isn't even a peculiarity of Java - it is the consequence of two's complement arithmetic modulo^(number of bits).

Source (Stackoverflow)