English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java program to check integer overflow

To check for Integer overflow, we need to check Integer.MAX_VALUE, which 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.

Example

public class Demo {
   public static void main(String[] args) {
      int val1 = 9898989;
      int val2 = 6789054;
      System.out.println("Value1: "+val1);
      System.out.println("Value2: "+val2);
      long sum = (long)val1 + (long)val2;
      if (sum > Integer.MAX_VALUE) {
         throw new ArithmeticException("Overflow!");
      }
      //Display the sum
      System.out.println("Sum: "+(int)sum);
   }
}

Output Result

Value1: 9898989
Value2: 6789054
Sum: 16688043

In the above example, we used the following two integers-

int val1 = 9898989;
int val2 = 6789054;

Now, we will cast and add it to a 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!");
}