Home >Java >javaTutorial >How can we check underflow in Java?

How can we check underflow in Java?

WBOY
WBOYforward
2023-09-10 15:37:021204browse

How can we check underflow in Java?

Underflow occurs when the value assigned to a variable is less than the minimum allowed value of the variable. If an underflow occurs in Java, the JVM does not throw an exception and it is the programmer's responsibility to handle the underflow situation.

Example

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<strong> </strong>new ArithmeticException("Underflow occurred!");
      }
      System.out.println("The sum of two numbers : " + (int)sum);
   }
}

Output

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

The above is the detailed content of How can we check underflow in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete