Add Integers and Check for Overflow in Java



In this article, we will add integers and check for overflow using Java. 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.

Problem Statement

Write a Java program to add integers and check for overflow ?

Input

a = 9897988
b = 8798798

Output

Value1: 9897988
Value2: 8798798
Sum: 18696786

Steps to add integers and check for overflow

Following are the steps to add integers and check for overflow ?

  • We will start by initializing the two integer values, a and b.
  • Print both integer values and convert the integers to long and add them to store the result.
  • Check if the result exceeds Integer.MAX_VALUE.
  • Suppose the result is greater than Integer.MAX_VALUE, throw an Exception i.e., ArithmeticException.
  • If there is no overflow, cast the result back to int and display the sum.

Java program to add integers and check for overflow

Below is the Java program to add integers and check for overflow ?

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

Code Explanation

In this program, two integer values a and b are initialized. These values are converted to long to prevent overflow during addition. After adding, the result is compared with Integer.MAX_VALUE to detect overflow. If the result exceeds the maximum value of an integer, an exception is thrown. Otherwise, the sum is displayed by casting it back to an int.

Updated on: 2024-09-18T21:55:48+05:30

986 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements