Open In App

Java Math negateExact() method

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. It throws an error when a data type int which has a minimum value of -2147483648 and the maximum value of 2147483647. So if we negate -2147483648 the result would be 2147483648 which already beyond the maximum value.

Syntax:



int negateExact(int num)
long negateExact(long num)

Parameters: The function accepts a single parameter as shown above and explained below:

Return Value: The function 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



Examples:

Input : 12
Output : -12

Input : -2
Output : 2 

Program 1: The program below demonstrates the working of negateExact() method.




// Java program to demonstrate working
// of java.lang.Math.negateExact() method
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
  
        int y = 10;
        System.out.println(Math.negateExact(y));
  
        int x = -12;
        System.out.println(Math.negateExact(x));
    }
}

Output:

-10
12

Program 2: The program below demonstrates the overflow of negateExact() method.




// Java program to demonstrate overflow
// of java.lang.Math.negateExact() method
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
  
        int y = Integer.MIN_VALUE;
        System.out.println(Math.negateExact(y));
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: integer overflow
    at java.lang.Math.negateExact(Math.java:977)
    at Gfg1.main(File.java:12)

Article Tags :