What is Math.negateExact() in Java?
The negateExact method takes a single argument, changes the sign of the passed value, and returns it.
The arguments will be either int or long. The negateExact method is a static method present in the Math class.
Syntax
public static long negateExact(long a);
public static int negateExact(int a);
Arguments
a: The value of thesignto be changed (int/long).
Return value
This method reverses the sign of the value and returns it.
The negateExact method is equivalent to:
- (argument1)
Example
import java.lang.Math;class NegateExactTest {public static void main(String cmdArgs[]) {int a = 20;int negationA = Math.negateExact(a);System.out.print("The negation of "+ a + " is ");System.out.println(negationA);int b = -10;int negationB = Math.negateExact(b);System.out.print("The negation of "+ b + " is ");System.out.println(negationB);long la = -20;long lNegationA = Math.negateExact(la);System.out.print("The negation of "+ la + " is ");System.out.println(lNegationA);long lb = 10;long lNegationB = Math.negateExact(lb);System.out.print("The negation of "+ lb + " is ");System.out.println(lNegationB);}}
In the code above:
-
We created four variables,
aandb, of theintandlatype, andlbof thelongtype. -
We called
negateExacton all of the created variables. This will apply negation to the variable and return the value with the opposite sign.
The negateExact method will throw ArithmeticException if:
-
The argument is
intand thenegationoverflows theintvalue. -
The argument is
longand thenegationoverflows theintvalue.
Example
For example, consider the argument is int. The ArithmeticException will be thrown if the negation of the int argument is lesser than the minimum value or greater than the maximum value that the int type can hold.
import java.lang.Math;class NegateExactTest {public static void main(String cmdArgs[]) {try{int a = Integer.MIN_VALUE;int negate = Math.negateExact(a);}catch(Exception e){System.out.println(e);}}}
In the code above, we created a variable, a of the int type. We assigned the minimum value an integer can hold to the variable a.
When we call the negateExact method with a as an argument, we will get ArithmeticException because the negate of a is greater than the value an integer can hold.