Java multiplyExact() in Math
Last Updated :
03 Apr, 2023
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
import java.lang.Math;
class Gfg1 {
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));
}
}
|
java
import java.lang.Math;
class Gfg2 {
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 {
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." );
}
}
}
|
Output:
Overflow occurred.
Share your thoughts in the comments
Please Login to comment...