Java Program to add long integers and check for overflow


To check for Long overflow, we need to check the Long.MAX_VALUE with the added long result. Here, Long.MAX_VALUE is the maximum value of Long type in Java.

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

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

Example

 Live Demo

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

Output

Value1: 80989
Value2: 87567
Addition Result: 168556

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

long val1 = 80989; long val2 = 87567;

Now we will perform addition.

long sum = val1 + val2;

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

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

493 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements