How can we check an underflow occurs in Java?

When a value is assigned to a variable that is less than the minimum allowed value for that variable, then an underflow occurs. There is no exception thrown by the JVM if an underflow occurs in Java and it is the responsibility of a programmer to handle the underflow conditions.


public class UnderlowTest {
   public static void main(String[] args) {
      int num1 = -2147483648;
      int num2 = -1;
      System.out.println("Number 1: " + num1);
      System.out.println("Number 2: " + num2);
      long sum = (long)num1 + (long)num2;
      if(sum < Integer.MIN_VALUE) {
         throw new ArithmeticException("Underflow occurred!");
      System.out.println("The sum of two numbers : " + (int)sum);


Number 1: -2147483648
Number 2: -1
Exception in thread "main" java.lang.ArithmeticException: Underflow occurred!
        at UnderlowTest.main(

Updated on: 03-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started