Java Program to add integers and check for overflow


To check for Integer overflow, we need to check the Integer.MAX_VALUE with the added integers result, Here, Integer.MAX_VALUE 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 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!");
      }
      // displaying sum
      System.out.println("Sum: "+(int)sum);
   }
}

Output

Value1: 9897988
Value2: 8798798
Sum: 18696786

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

int val1 = 9897988;
int val2 = 8798798;

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 an exception is thrown.

If (sum > Integer.MAX_VALUE) {
   throw new ArithmeticException("Overflow!");
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

561 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements