Open In App

Java Math negateExact() Method

Last Updated : 09 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Syntax of negateExact() Method

int Math.negateExact(int num)

long Math.negateExact(long num)

  • Parameter: num: The number we want to negate.
  • Returns: It returns the value -num.
  • Exception Throws: It throws an ArithmeticException if negating the value causes an overflow.

Examples of Java Math negateExact() Method

Example 1: In this example, we will see the working of negateExact() method.

Java
// Java program to show how negateExact() works
import java.lang.Math;

public class Geeks {
    
    public static void main(String[] args) {
        int a = 10;
        int b = -12;

        System.out.println(Math.negateExact(a));  
        System.out.println(Math.negateExact(b));  
    }
}

Output
-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.

Java
// Java program to demonstrate overflow with negateExact()
import java.lang.Math;

public class Geeks {
    
    public static void main(String[] args) {
        int min = Integer.MIN_VALUE;

        System.out.println(Math.negateExact(min));
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: integer overflow

Explanation: 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:

  • This method works for both int and long.
  • It is safer than using the - operator when dealing with boundary values.
  • This method throws an exception only in the case of overflow.

Practice Tags :

Similar Reads