Why Int overflow is occured this code?
[code]
val randomList = List(scala.util.Random.nextInt(), scala.util.Random.nextInt(), scala.util.Random.nextInt(), scala.util.Random.nextInt())
var listSum = 0
for (value <- randomList) {
listSum = value
println("value = " value)
println("listSum = " listSum)
println("\n")
}
println("sum is " listSum)
[Result]
value = 2078728151 listSum = 2078728151
value = -1367097617 listSum = 711630534
value = 1543963641 listSum = -2039373121
value = -1351834340 listSum = 903759835
sum is 903759835
randomList: List[Int] = List(2078728151, -1367097617, 1543963641, -1351834340)
listSum: Int = 903759835
CodePudding user response:
In Scala Int
is 4 bytes long, so the greatest Integer is 2**(32-1)-1, which happens to be
Int.MaxValue = 2147483647
Any value above that is going to be Int.MinValue = -2147483648
or greater.
It is the same in any other language