StrictMath.absExact(int) in Java

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

Syntax:

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

This method takes one argument of type int as its parameter. This method returns the mathematical absolute value of an int value if it is exactly representable as an int, throwing ArithmeticException if the result overflows the positive int 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 Integer.MIN_VALUE

Approach 1: When no exceptions

Java

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

        int a = -178;
        System.out.println(StrictMath.absExact(a));
    }
}

Output:

178


Approach 2: ArithmeticException 

Java

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

        int a = Integer.MIN_VALUE;
        System.out.println(StrictMath.absExact(a));
    }
}


Output:

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


No comments:

Post a Comment