What is Math.multiplyExact() in Java?

The multiplyExact method in Java multiples the two passed arguments and returns the product of the arguments as a result. The arguments will be either int or long.

The multiplyExact method is a static method present in the Math class.

Syntax

public static long multiplyExact(long a,long b);

public static int multiplyExact(int a, int b);

Arguments

  • a: First value (int/long).
  • b: Second value(int/long).

Return value

The methhod returns the product of a and b.

Example

import java.lang.Math;
class MultiplyExactTest {
public static void main(String cmdArgs[]) {
int a = 10;
int b = 10;
int product = Math.multiplyExact(a, b);
System.out.print("The product of "+ a + " and " + b + " is ");
System.out.println(product);
long la = 100000000l;
long lb = 100000000l;
long lproduct = Math.multiplyExact(la, lb);
System.out.print("The product of "+ la + " and " + lb + " is ");
System.out.println(lproduct);
}
}

In the code above:

  • We created four variables, a and b, of the int, la, and lb of the long type.

  • We called the Math.multiplyExact method with a and b as arguments. This will return the product of a and b as a result.

  • Again, we called the Math.multiplyExact method with la and lb as arguments. This will return the product of la and lb as a result.


The multiplyExact method will throw ArithmeticException if:

  • The arguments are int and the product overflows the int value.

  • The arguments are long and the product overflows the long value.

Example

For example, consider if the two arguments are int. The ArithmeticException will be thrown if the product of the two int arguments is less than the minimum value or greater than the maximum value that the int type can hold.

import java.lang.Math;
class MultiplyExactTest {
public static void main(String cmdArgs[]) {
try{
int a = Integer.MAX_VALUE;
int b = 2;
int product = Math.multiplyExact(a, b);
}catch(Exception e){
System.out.println(e);
}
}
}

In the code above, we created two variables, a and b, of the int type. We assigned the maximum value an integer can hold to the variable a, and 2 to the variable b.

When we call the multiplyExact method with a and b as arguments, we will get ArithmeticException, because the product of a and b is greater than the value an integer can hold.

Free Resources