Java 中 Math 的 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() 方法計算長整型值的乘積。
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 類的內建靜態方法,在下一節中,我們透過示例程式討論了它的實際實現。此外,我們還了解了如何處理由結果溢位引起的異常。