StrictMath.multiplyExact(long, int) in Java

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

Syntax:

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

This method takes two arguments one of type long and another of type int 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 StrictMathmultiplyExactlongint {
    public static void main(String[] args) {

        long x = 15699;
        int y = 99;
        System.out.println(StrictMath.multiplyExact(x, y));
    }
}

Output:

1554201


Approach 2: ArithmeticException

Java

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

        long x = Long.MAX_VALUE;
        int y = 899;
        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.Math.multiplyExact(Math.java:925) at java.base/java.lang.StrictMath.multiplyExact(StrictMath.java:819)



Some more multiplyExact() Methods of StrictMath class.


StrictMath.multiplyExact(int, int)


StrictMath.multiplyExact(long, long)


No comments:

Post a Comment