Multiply Long Integers and Check for Overflow in Java



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

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

Steps to multiply long integers and check for overflow

Following are the steps to multiply long integers and check for overflow in Java ?

  • Initialize long values by defining two long integers, val1 and val2.
  • Multiply val1 and val2 to get mul.
  • To check for overflow by Comparing mul with Long.MAX_VALUE.
  • We will handle overflow by throwing an Exception that is ArithmaticException if mul exceeds Long.MAX_VALUE.
  • By using the conditional statement if no overflow occurs we will print the result.

Multiply long integers and check for overflow in Java

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

public class Demo {
   public static void main(String[] args) {
      long val1 = 6999;
      long val2 = 67849;
      System.out.println("Value1: "+val1);
      System.out.println("Value2: "+val2);
      long mul = val1 * val2;
      if (mul > Long.MAX_VALUE) {
         throw new ArithmeticException("Overflow!");
      }
      // displaying multiplication
      System.out.println("Multiplication Result: "+(long)mul);
     }
}

Output

Value1: 6999
Value2: 67849
Multiplication Result: 474875151

Code Explanation

We have two big numbers, val1 and val2 that we multiply and store the result in mul. The long data type in Java has a maximum value of Long.MAX_VALUE, so it's important to ensure that the multiplication doesn't exceed this limit, which would cause an overflow.

Directly comparing the result with Long.MAX_VALUE isn't enough because overflow can happen during the multiplication itself, leading to incorrect values. After performing the multiplication, the code checks if mul exceeds Long.MAX_VALUE. If it does, the program throws an ArithmeticException to indicate an overflow. If no overflow occurs, the program successfully prints the multiplication result. 

Updated on: 2024-09-02T19:29:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements