Java multiplyExact()方法
在Java中,multiplyExact()是Math类中的一个内置静态方法,接受两个参数并返回它们的乘积作为结果。该方法可以接受整数或长整数类型的值。需要注意的一点是,如果产生的结果超过整数的大小,可能会引发异常。
在了解Java中multiplyExact()方法的功能之后,一个可能会闪现在人们脑海中的问题是我们也可以使用“*”运算符相乘两个操作数,那么为什么我们需要multiplyExact()方法。我们将回答这个问题,并且使用示例来探索multiplyExact()方法。
Java中的multiplyExact()方法
对于两个或更多值的简单乘法操作,我们可以依靠“*”运算符,但是使用multiplyExact()方法无法将其他类型的值相乘,除了整数和长整数之外。此外,它只接受两个参数。
在进入示例程序之前,让我们讨论multiplyExact()方法的语法 −
语法
public static Type multiplyExact(Type val1, Type val2);
在这里,’ Type ‘指定了整数或长整数数据类型。
要在我们的Java程序中使用multiplyExact()方法,我们需要使用以下命令导入Math类:
import java.lang.Math;
注意, multiplyExact() 是 Math 类的一个静态方法,调用此方法时不需要对象,而是使用类名后跟点(.)运算符。
示例
在以下示例中,我们将使用 multiplyExact() 方法来计算整数值的乘积。
import java.lang.Math;
public class Example1 {
public static void main(String args[]) {
int a = 12, b = 34;
System.out.printf("Product of a and b is: ");
// performing the first multiplication
System.out.println(Math.multiplyExact(a, b));
int c = 78, d = 93;
System.out.printf("Product of c and d is: ");
// performing the second multiplication
System.out.println(Math.multiplyExact(c, d));
}
}
输出
Product of a and b is: 408
Product of c and d is: 7254
示例
在此示例中,我们将使用multiplyExact()方法来计算long类型值的乘积。
import java.lang.Math;
public class Example2 {
public static void main(String args[]) {
long val1 = 1258, val2 = 304;
System.out.printf("Product of val1 and val2 is: ");
System.out.println(Math.multiplyExact(val1, val2));
long val3 = 478, val4 = 113;
System.out.printf("Product of val3 and val4 is: ");
System.out.println(Math.multiplyExact(val3, val4));
}
}
输出
Product of val1 and val2 is: 382432
Product of val3 and val4 is: 54014
示例
以下示例展示了如果结果超过整数变量的大小时将会输出的内容。
import java.lang.Math;
public class Example3 {
public static void main(String args[]) {
int val1 = 1258526920;
int val2 = 1304;
System.out.printf("Product of val1 and val2 is: ");
// this line will throw an exception
System.out.println(Math.multiplyExact(val1, val2));
}
}
输出
Product of val1 and val2 is: Exception in thread "main" java.lang.ArithmeticException: integer overflow
at java.base/java.lang.Math.multiplyExact(Math.java:992)
at Example3.main(Example3.java:7)
示例
我们可以使用try和catch块以更专业的方式处理异常。
import java.lang.Math;
public class Example4 {
public static void main(String args[]) {
try {
int val1 = 1258526920;
int val2 = 1304;
System.out.println(Math.multiplyExact(val1, val2));
}
catch(ArithmeticException exp) { // to handle the exception
System.out.println("Calculation produced too big result");
}
}
}
输出
Calculation produced too big result
结论
我们在本文中介绍了multiplyExact()方法,它是Math类的一个内置静态方法。在下一节中,我们通过示例程序讨论了它的实际应用。此外,我们还发现了如何处理由结果溢出引起的异常。