Java Program to multiply integers and check for overflow


To check for Integer overflow, we need to check the Integer.MAX_VALUE with the multiplied integers result, Here, Integer.MAX_VALUE is the maximum value of an integer in Java.

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

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

Example

 Live Demo

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

Output

Value1: 9898
Value2: 6784
Multiplication Result: 67148032

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

int val1 = 9898;
int val2 = 6784;

Now we will cast and multiply them to a long.

long mul = (long)val1 + (long)val2;

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

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

679 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements