subtractExact() long in Java

subtractExact(): This method is available in the Math class of Java.

Syntax:

long java.lang.Math.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.

For Example:

Math.subtractExact(1919199,1981)  => It returns 1917218.

Approach

Java

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

        long x = 1919199, y = 1981;
        System.out.println(Math.subtractExact(x, y));

    }
}

Output:

1917218

No comments:

Post a Comment