English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
To check for Integer overflow, we need to use the result of the subtracted integer to check Integer.MAX_VALUE. Here, Integer.MAX_VALUE is the maximum value of integers in Java.
Let's look at an example where an integer is subtracted, and if the result is greater than Integer.MAX_VALUE, an exception will be thrown.
The following is an example of how to check for Integer overflow.
public class Demo { public static void main(String[] args) { int val1 = 9898999; int val2 = 8784556; System.out.println("Value1: "+val1); System.out.println("Value2: "+val2); long sub = (long)val1 - (long)val2; if (sub > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); } //Display the subtraction result System.out.println("Subtraction Result: "+(int)sub); } }
Output Result
Value1: 9898999 Value2: 8784556 Subtraction Result: 1114443
In the above example, we use the following two integers-
int val1 = 9898999; int val2 = 8784556;
Now, we convert it to subtraction.
long sub = (long)val1 - (long)val2;
If the result is greater than the maximum value, an exception is thrown.
If (sub > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); }