Friday, September 16, 2016

Integer overflow

Integer overflow in JVM can lead to negative, zero and positive values, i.e. can everything:
scala> val x = 1 + (Int.MaxValue - 1) / 2
x: Int = 1073741824
scala> x * x
res16: Int = 0
scala> val x = 1 + (Int.MaxValue - 5) / 2
x: Int = 1073741822
scala> x * x
res18: Int = 4
scala> val x = 1 + (Int.MaxValue - 6) / 2
x: Int = 1073741821
scala> x * x
res19: Int = -2147483639
The check for overflow due to multiplication divide back and check if get the same result. Summation overflow can be checked by the sign of result. The other option is to use double and long.