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:



  • num – This parameter specifies the number whose negation has to be returned.

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
    }
}

chevron_right


Output:

-10
12

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
    }
}

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.