multiplyExact()
方法的语法是
Math.multiplyExact(num1, num2)
在这里,multiplyExact()
是一个静态方法。因此,我们使用类名 Math
来访问该方法。
multiplyExact() 参数
multiplyExact()
方法接受两个参数。
- num1 - 与 num2 相乘的值
- num2 - 与 num1 相乘的值
注意:两个值的数据类型都应该是 int
或 long
。
multiplyExact() 返回值
- 返回 num1 和 num2 的乘积
示例 1:Java Math multiplyExact()
import java.lang.Math;
class Main {
public static void main(String[] args) {
// create int variable
int a = 5;
int b = 6;
// multiplyExact() with int arguments
System.out.println(Math.multiplyExact(a, b)); // 30
// create long variable
long c = 7236L;
long d = 1721L;
// multiplyExact() with long arguments
System.out.println(Math.multiplyExact(c, d)); // 12453156
}
}
在上面的示例中,我们使用 Math.multiplyExact()
方法和 int
及 long
变量来计算相应数字的乘积。
示例 2:Math multiplyExact() 抛出异常
如果乘法结果溢出数据类型,multiplyExact()
方法会抛出异常。也就是说,结果应该在指定变量的数据类型的范围内。
import java.lang.Math;
class Main {
public static void main(String[] args) {
// create int variable
// maximum int value
int a = 2147483647;
int b = 2;
// multiplyExact() with int arguments
// throws exception
System.out.println(Math.multiplyExact(a, b));
}
}
在上面的示例中,a 的值是最大的 int
值,而 b 的值是 2。当我们乘以 a 和 b 时,
2147483647 * 2
=> 4294967294 // out of range of int type
因此,multiplyExact()
方法抛出 integer overflow
异常。
另请阅读