The java.lang.Math.multiplyExact() is a built-in math function in java that returns the product of the arguments.It throws an exception if the result overflows an int. As multiplyExact(int a, int b) is static, so object creation is not required.
Syntax:
public static int multiplyExact(int a, int b) public static double multiplyExact(int a, double b) Parameter : a : the first value b : the second value Return : This method returns the product of the arguments. Exception : It throws ArithmeticException - if the result overflows an int
Example: To show the working of java.lang.Math.multiplyExact() method.
java
// Java program to demonstrate working // of java.lang.Math.multiplyExact() method import java.lang.Math;
class Gfg1 {
// driver code
public static void main(String args[])
{
int a = 25 , b = 5 ;
System.out.println(Math.multiplyExact(a, b));
long c = 100 , d = 50 ;
System.out.println(Math.multiplyExact(c, d));
}
} |
Output:
125 5000
java
// Java program to demonstrate working // of java.lang.Math.multiplyExact() method import java.lang.Math;
class Gfg2 {
// driver code
public static void main(String args[])
{
int x = Integer.MAX_VALUE;
int y = 2 ;
System.out.println(Math.multiplyExact(x, y));
}
} |
Output:
Runtime Error : Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.lang.Math.multiplyExact(Math.java:867) at Gfg2.main(File.java:13)
Example:
Java
import java.io.*;
class GFG {
// driver code
public static void main(String[] args)
{
try {
int x = Integer.MAX_VALUE;
int y = 2 ;
int result = Math.multiplyExact(x, y);
System.out.println(x + " * " + y + " = "
+ result);
}
catch (ArithmeticException e) {
System.out.println(
"Overflow occurred." ); // print statement
}
}
} |
Output:
Overflow occurred.