Java Math multiplyExact()

The syntax of the multiplyExact() method is:

Math.multiplyExact(num1, num2)

Here, multiplyExact() is a static method. Hence, we are accessing the method using the class name, Math.


multiplyExact() Parameters

The multiplyExact() method takes two parameters.

  • num1 - value which is multiplied with num2
  • num2 - value which is multiplied with num1

Note: The data type of both values should be either int or long.


multiplyExact() Return Value

  • returns the product of num1 and num2

Example 1: Java Math multiplyExact()

import java.lang.Math;

class Main {
  public static void main(String[] args) {

    // create int variable
    int a = 5;
    int b = 6;

    // multiplyExact() with int arguments
    System.out.println(Math.multiplyExact(a, b));  // 30

    // create long variable
    long c = 7236L;
    long d = 1721L;

    // multiplyExact() with long arguments
    System.out.println(Math.multiplyExact(c, d));  // 12453156
  }
}

In the above example, we have used the Math.multiplyExact() method with the int and long variables to calculate the product of the respective numbers.


Example 2: Math multiplyExact() Throws Exception

The multiplyExact() method throws an exception if the result of the multiplication overflows the data type. That is, the result should be within the range of the data type of specified variables.

import java.lang.Math;

class Main {
  public static void main(String[] args) {

    // create int variable
    // maximum int value
    int a = 2147483647;
    int b = 2;

    // multiplyExact() with int arguments
    // throws exception
    System.out.println(Math.multiplyExact(a, b));
  }
}

In the above example, the value of a is the maximum int value and the value of b is 2. When we multiply a and b,

  2147483647 * 2
=> 4294967294    // out of range of int type     

Hence, the multiplyExact() method throws the integer overflow exception.


Recommended Tutorials