StrictMath.subtractExact(long, long) in Java

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

Syntax:

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

This method takes two arguments of type long as its parameters. This method returns the difference 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 to subtract from the first.

Returns: the result.

Throws:

ArithmeticException - if the result overflows a long.

Approach 1: When no exceptions.

Java

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

        long x = 10190, y = 1919;
        System.out.println(StrictMath.subtractExact(x, y));
    }
}

Output:

8271


Approach 2: ArithmeticException

Java

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

        long x = Long.MIN_VALUE, y = 1919;
        System.out.println(StrictMath.subtractExact(x, y));
    }
}


Output:

Exception in thread "main" java.lang.ArithmeticException: long overflow at java.base/java.lang.Math.subtractExact(Math.java:890) at java.base/java.lang.StrictMath.subtractExact(StrictMath.java:789)



StrictMath.subtractExact(int, int)


No comments:

Post a Comment