Add Long Integers and Check for Overflow in Java



In this article, we will add two long integers in Java and check if the sum causes an overflow, which happens when the result exceeds the maximum value that a long data type can hold, defined by the Long class as Long.MAX_VALUE. If the sum goes beyond this limit, an exception will be thrown to handle the overflow. Otherwise, the sum will be displayed as the result.

Steps to add long integers and check for overflow

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

  • First, we will define two long integers val1 and val2.
  • After that, we will add these two integers and store the result in a variable.
  • Check if the sum exceeds the Long.MAX_VALUE. If so, throw an ArithmeticException.
  • If there's no overflow, display the result of the addition.

Java program to add long integers and check for overflow

The following is an example showing how to check for Long overflow ?

public class Demo {
   public static void main(String[] args) {
      long val1 = 80989;
      long val2 = 87567;
      System.out.println("Value1: "+val1);
      System.out.println("Value2: "+val2);
      long sum = val1 + val2;
      if (sum > Long.MAX_VALUE) {
         throw new ArithmeticException("Overflow!");
      }
      System.out.println("Addition Result: "+sum);
   }
}

Output

Value1: 80989
Value2: 87567
Addition Result: 168556

Code Explanation

In the above program, we first define two long values val1 and val2, and then calculate their sum. The sum is stored in the variable sum. To detect overflow, we use a condition that checks if the sum becomes negative, which would indicate that the result has wrapped around due to exceeding Long.MAX_VALUE. If this happens, an ArithmeticException with the message "Overflow!" is thrown. Otherwise, the program prints the result of the addition. This method of checking for overflow by detecting a negative sum is common when dealing with primitive long values in Java, as long values that overflow result in a negative number.

Updated on: 2024-10-16T16:29:42+05:30

879 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements