當分配給變數的值小於該變數的最小允許值時,就會發生下溢。如果 Java 中發生下溢,JVM 不會拋出異常,且程式設計師有責任處理下溢情況。
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); } }
Number 1: -2147483648 Number 2: -1 Exception in thread "main" java.lang.ArithmeticException: Underflow occurred! at UnderlowTest.main(UnderlowTest.java:9)
以上是我們如何在Java中檢查下溢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!