English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Program to Multiply Integers and Check for Overflow

To check for Integer overflow, we need to check the result of multiplying Integer.MAX_VALUE by an integer, here, Integer.MAX_VALUE is the maximum value of integers in Java.

Let's look at an example where integers are multiplied, and if the result is greater than Integer.MAX_VALUE, an exception will be thrown.

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

Example

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!");
      }
      //Display Multiplication
      System.out.println("Multiplication Result: "+(int)mul);
   }
}

Output Result

Value1: 9898
Value2: 6784
Multiplication Result: 67148032

In the above example, we use the following two integers.

int val1 = 9898;
int val2 = 6784;

Now, we project and double it.

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

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

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