📜  Java Math multipleExact()(1)

📅  最后修改于: 2023-12-03 15:01:31.547000             🧑  作者: Mango

Java Math multipleExact()

The multipleExact() method of Math class in Java returns the product of two arguments, computed as if by the long multiplication algorithm, and checked for overflow.

The method signature is as follows:

public static long multiplyExact(long x, long y)

The multiplyExact() method takes two long values as parameters and returns their product as a long value. If the multiplication of the two values overflows the range of a long, an ArithmeticException is thrown.

Syntax
public static long multiplyExact(long x, long y)

Parameter(s):

  • x - the first value to be multiplied.
  • y - the second value to be multiplied.

Return Value:

  • This method returns the product of two arguments.
Examples

Here are some examples to demonstrate the usage of the multiplyExact() method:

long a = 10L;
long b = 11L;
try {
    long result = Math.multiplyExact(a, b);
    System.out.println("Result: " + result);
} catch (ArithmeticException e) {
    System.out.println("Overflow occurred!");
}

Here, the multiplyExact() method is used to compute the product of a and b, and the result is stored in the result variable. If an overflow occurs, an ArithmeticException is thrown and the message "Overflow occurred!" is displayed.

Conclusion

The multiplyExact() method of Math class is useful when we need to multiply two long values and check for overflow. It helps us to avoid runtime errors due to overflow while performing multiplication.