StrictMath.multiplyExact(long, long) in Java

StrictMath.multiplyExact(long, long): This method is available in java.lang.StrictMath class of Java.

Syntax:

long java.lang.StrictMath.multiplyExact(long x, long y)

This method takes two arguments of type long as its parameters. This method returns the product of the arguments, throwing an exception if the result overflows a long.

Parameters: Two parameters are required for this method.

x: the first value.

y: the second value.

Returns: the result.

Throws:

ArithmeticException - if the result overflows a long.

Approach 1: When no exceptions.

Java

public class StrictMathmultiplyExactlong {
    public static void main(String[] args) {

        long x = 15886, y = 1099;
        System.out.println(StrictMath.multiplyExact(x, y));
    }
}

Output:

17458714


Approach 2: ArithmeticException 

Java

public class StrictMathmultiplyExactlong {
    public static void main(String[] args) {

        long x = 1999999999, y = Long.MAX_VALUE;
        System.out.println(StrictMath.multiplyExact(x, y));
    }
}


Output:

Exception in thread "main" java.lang.ArithmeticException: long overflow at java.base/java.lang.Math.multiplyExact(Math.java:949) at java.base/java.lang.StrictMath.multiplyExact(StrictMath.java:834)



Some more multiplyExact() Methods of StrictMath class.


StrictMath.multiplyExact(int, int)


StrictMath.multiplyExact(long, int)


No comments:

Post a Comment