Java Math.multiplyExact() method
In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided arguments. As this method takes in integer values and also returns the product which is an integer, this method throws an exception if the product value exceeds the range of int datatype. multiplyExact method is declared as static, so object creation is not necessary to implement this method.
SYNTAX:
This is the syntax of the multiplyExact method when integers are taken as the parameters.
public static int multiplyExact (int x, int y)
This is the syntax of the multiplyExact method when double values are taken as the parameters.
public static double multiplyExact (double x, double y)
Parameters: x,y are the parameters. These can be of integer or double datatypes.
This method returns an integer value if the parameters provided are integer values. In the same way, it returns a double value if the corresponding parameters are double values.
NOTE:
This method throws an ArithmeticException, if the produced result overflows with the range of int datatype.
We should import the java.lang package in the java program.
Let’s look the implementation of the multiplyExact() Method in java
import java.io.*;
import java.lang.Math;
class MultiplyExactDemo
{
public static void main (String args [])
{
System.out.println (“The implementation of the multiplyExact method by taking integer parameters”);
int p = 23, q = 10;
System.out.println (“The product of two integer values is” +Math.multiplyExact(p, q));
System.out.println (“The implementation of the multiplyExact method by taking integer parameters”);
long r =10, s = 5;
System.out.println (“The product of two long values is” +Math.multiplyExact(r, s));
} //main
} //MultiplyExactDemo
OUTPUT:
The implementation of the multiplyExact method by taking integer parameters
The product of two integer values is 230
The implementation of the multiplyExact method by taking integer parameters
The product of two long values is 50
Let’s look into another example for implementing the multiplyExact Method which throws an exception.
import java.io.*;
import java.lang.Math;
class MultiplyExactDemo
{
public static void main (String args [])
{
System.out.println (“The implementation of the multiplyExact method by taking integer parameters”);
int p = Integer.MAX_VALUE;
int q = 10;
System.out.println (“The product of two integer values is” +Math.multiplyExact(p, q));
} //main
} //MultiplyExactDemo
OUTPUT:
Runtime Error:
Exception in thread “main” java. lang. ArithmeticException: integer overflow
at java. lang. Math. multiplyExact (Math. java: 867)
at MultiplyExactDemo.main(File. java: 13)