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

How can we check underflow in Java?

WBOY
Release: 2023-09-10 15:37:02
forward
1202 people have browsed it

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);
   }
}
Copy after login

Output

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template