StrictMath.decrementExact(long) in Java

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

Syntax:

long java.lang.StrictMath.decrementExact(long a)

This method takes one argument of type long as its parameter. This method returns the argument decremented by one, throwing an exception if the result overflows a long. The overflow only occurs for the minimum value.

Parameters: One parameter is required for this method.

a: the value to decrement.

Returns: the result.

Throws:

ArithmeticException - if the result overflows a long.

Approach 1: When no exceptions.

Java

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

        long a = 1881919;
        System.out.println(StrictMath.decrementExact(a));
    }
}

Output:

1881918


Approach 2: ArithmeticException 

Java

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

        long a = Long.MIN_VALUE;
        System.out.println(StrictMath.decrementExact(a));
    }
}


Output:

Exception in thread "main" java.lang.ArithmeticException: long overflow at java.base/java.lang.Math.decrementExact(Math.java:1025) at java.base/java.lang.StrictMath.decrementExact(StrictMath.java:894)


No comments:

Post a Comment