StrictMath.negateExact(long) in Java

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

Syntax:

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

This method takes one argument of type long as its parameter. This method returns the negation of the argument, 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 negate

Returns: the result.

Throws:

ArithmeticException - if the result overflows a long.

Approach 1: When no exceptions.

Java

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

        long a = 1991;
        System.out.println(StrictMath.negateExact(a));
    }
}

Output:

-1991


Approach 2: ArithmeticException 

Java

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

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


Output:

Exception in thread "main" java.lang.ArithmeticException: long overflow at java.base/java.lang.Math.negateExact(Math.java:1063) at java.base/java.lang.StrictMath.negateExact(StrictMath.java:924)



StrictMath.negateExact(int)


No comments:

Post a Comment