StrictMath.absExact(long) in Java

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

Syntax:

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

This method takes one argument of type long as its parameter. This method returns the mathematical absolute value of a long value if it is exactly representable as a long, throwing ArithmeticException if the result overflows the positive long-range.

Parameters: One parameter is required for this method.

a: the argument whose absolute value is to be determined.

Returns: the absolute value of the argument, unless overflow occurs.

Throws:

ArithmeticException - if the argument is Long.MIN_VALUE

Approach 1: When no exceptions.

Java

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

        long a = -17889001;
        System.out.println(StrictMath.absExact(a));
    }
}

Output:

17889001


Approach 2: ArithmeticException

Java

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

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


Output:

Exception in thread "main" java.lang.ArithmeticException: Overflow to represent absolute value of Long.MIN_VALUE at java.base/java.lang.Math.absExact(Math.java:1439) at java.base/java.lang.StrictMath.absExact(StrictMath.java:1203)


No comments:

Post a Comment