![]() |
VOOZH | about |
The java.lang.Math.negateExact() is a built-in function in Java that returns the negation of the argument, throwing an exception if the result overflows the specified datatype, either long or int, depending on which data type has been used on the method argument.
Why does it Overflow?
It throws an error when a data type int, which has a minimum value of -2147483648 and a maximum value of 2147483647. So, if we negate -2147483648, the result would be 2147483648, which is already beyond the maximum value.
Examples:
Input : 12
Output : -12
Input : -2
Output : 2
int Math.negateExact(int num)
long Math.negateExact(long num)
Example 1: In this example, we will see the working of negateExact() method.
-10 12
Explanation: Here in this example, the values 10 and -12 are negated to -10 and 12. Because the result are within the valid int range, that is why no exception is thrown.
Example 2: The program below demonstrates the overflow of negateExact() method.
Output:
Exception in thread "main" java.lang.ArithmeticException: integer overflowExplanation: Here in this example, the value Integer.MIN_VALUE is -2147483648. And we are trying to negate it. So, it results in a number that is outside the allowed range for integers. So, negateExact() throws an exception.
Important Points: