Overflow in Java/Scala

Pramod Shehan
3 min readOct 2, 2022

Overflow and underflow happen when we assign a value that is out of range of the declared data type of the variable.

If the (absolute) value is too big, we call it overflow, if the value is too small, we call it underflow.

According to the above output, after adding 1 for Integer max value , value is negative value. This is wrong. This is due to overflow error.

Java does not throw an exception when an overflow occurs; that is why it can be hard to find errors resulting from an overflow.

How to Solve overflow issue

  1. Math.addExact()

If we want to throw an exception, we can use Math.addExact for returning the sum.

according to the above image, addExact method is checking result with given integers to check overflow error.

2. Use different data types

The standard Java integer data types are:

  • byte 1 byte -128 to 127
  • short 2 bytes -32,768 to 32,767
  • int 4 bytes -2,147,483,648 to 2,147,483,647
  • long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

according to the above range, long variables can also overflow.

The value range of BigInteger is not restricted, except by the amount of memory available to the JVM.

This is the output of above program.

In Scala, we can use BigInt.

This is the output of above program.

Scala BigInt is using also java.math.BigInteger.