Java Math negateExact()

The syntax of the negateExact() method is:

Math.negateExact(num)

Here, negateExact() is a static method. Hence, we are accessing the method using the class name, Math.


negateExact() Parameters

The negateExact() method takes a single parameter.

  • num - argument whose sign is to be reversed

Note: The data type of the argument should be either int or long.


negateExact() Return Value

  • returns the value after reversing the sign of the specified argument

Example 1: Java Math.negateExact()

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

    // create int variables
    int a = 65;
    int b = -25;

    // negateExact() with int arguments
    System.out.println(Math.negateExact(a));  // -65
    System.out.println(Math.negateExact(b));  // 25

    // create long variable
    long c = 52336L;
    long d = -445636L;

    // negateExact() with long arguments
    System.out.println(Math.negateExact(c));  // -52336
    System.out.println(Math.negateExact(d));  // 445636
  }
}

In the above example, we have used the Math.negateExact() method with the int and long variables to reverse the sign of respective variables.


Example 2: Math.negateExact() Throws Exception

The negateExact() method throws an exception if the result of the negation overflows the data type. That is, the result should be within the range of the data type of specified variables.

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

    // create a int variable
    // minimum int value
    int a = -2147483648;

    // negateExact() with the int argument
    // throws exception
    System.out.println(Math.negateExact(a));
  }
}

In the above example, the value of a is the minimum int value. Here, the negateExact() method changes the sign of the variable a.

   -(a)  
=> -(-2147483648)
=> 2147483648    // out of range of int type     

Hence, the negateExact() method throws the integer overflow exception.


Recommended Tutorials

Did you find this article helpful?