Java Math negateExact() Method
Example
Change the sign of different numbers:
System.out.println(Math.negateExact(15));
System.out.println(Math.negateExact(-32));
System.out.println(Math.negateExact(7));
System.out.println(Math.negateExact(-25));
Try it Yourself »
Definition and Usage
The negateExact()
method returns an integer with equal value and opposite
sign to another integer and throws an exception if an overflow occurs. This prevents incorrect results that
can occur from the overflow.
An overflow occurs when the integer is equal to Integer.MIN_VALUE
or Long.MIN_VALUE
, the largest negative integer, because it does not have a positive
equivalent.
Syntax
One of the following:
public static int negateExact(int x)
public static long negateExact(long x)
Parameter Values
Parameter | Description |
---|---|
x | Required. An integer to negate. |
Technical Details
Returns: | An int or long value
representing an integer with equal value and opposite sign to another integer. |
---|---|
Throws: | ArithmeticException - If the negation causes an
overflow. |
Java version: | 1.8+ |
❮ Math Methods