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,
aandb, of theint,la, andlbof thelongtype. -
We called the
Math.multiplyExactmethod withaandbas arguments. This will return the product ofaandbas a result. -
Again, we called the
Math.multiplyExactmethod withlaandlbas arguments. This will return the product oflaandlbas a result.
The multiplyExact method will throw ArithmeticException if:
-
The arguments are
intand theproductoverflows theintvalue. -
The arguments are
longand theproductoverflows thelongvalue.
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.