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