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.
// 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)
Recommended Posts:
- Java.math.BigInteger.probablePrime() method in Java
- Java.math.BigInteger.modInverse() method in Java
- Java Math log() method with example
- Java Math exp() method with Example
- Java Math asin() method with Example
- Math floorMod() Method in Java
- Java Math incrementExact() method
- Java Math decrementExact() method
- Java Math round() method with Example
- Math floorDiv() method in Java
- Java Math min() method with Examples
- Java Math expm1() method with Example
- Java Math getExponent() method with Example
- Math fma() method in Java with Examples
- Java Math getExponent() method with Example
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.



