Java Program to check for Integer overflow

Java 8Object Oriented ProgrammingProgramming

To check for Integer overflow, we need to check the Integer.MAX_VALUE, which is the maximum value of an integer in Java.

Let us see an example wherein integers are added and if the sum is more than the Integer.MAX_VALUE, then an exception is thrown.

Example

 Live Demo

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!");
      }
      // displaying sum
      System.out.println("Sum: "+(int)sum);
   }
}

Output

Value1: 9898989
Value2: 6789054
Sum: 16688043

In the above example, we have taken the following two integers −

int val1 = 9898989;
int val2 = 6789054;

Now we will cast and add them to a long.

long sum = (long)val1 + (long)val2;

If the result is more than the maximum value, then a exception is thrown.

if (sum > Integer.MAX_VALUE) {
   throw new ArithmeticException("Overflow!");
}
raja
Published on 12-Nov-2018 10:38:46
Advertisements