Java Math negateExact() Method
The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long.
Syntax:
- public static int negateExact (int a)
- public static long negateExact (long a)
Parameters:
The parameter ‘a’ represents the value to negate.
Return Value:
The negateExact () method returns the negation of a.
Throws:
The negateExact () method throws:
ArithmeticException- if the result overflows an int or long.
Example 1:
public class JavaMathNegateExactExample1 { public static void main(String[] args) { int a = 34; //returns the negation for a System.out.println("Negation of "+a+" is : "+Math.negateExact(a)); } }
Output:
Negation of 34 is : -34
Example 2:
public class JavaMathNegateExactExample2 { public static void main(String[] args) { long a = -8765; //returns positive value for negative a System.out.println("Negation of "+a+" is : "+Math.negateExact(a)); } }
Output:
Negation of -8765 is : 8765
Example 3:
public class JavaMathNegateExactExample3 { public static void main(String[] args) { Long a = 566l/0l; //throws exception if a is divided by zero System.out.println("Negation of "+a+" is : "+Math.negateExact(a)); } }
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero at com.TutorialAndExamples.JavaMathNegateExactExample3.main(JavaMathNegateExactExample 3.java:5)
Example 4:
public class JavaMathNegateExactExample4 { public static void main(String[] args) { Long a = Long.MIN_VALUE; //throws wxception if a is divided by zero System.out.println("Negation of "+a+" is : "+Math.negateExact(a)); } }
Output:
Exception in thread "main" java.lang.ArithmeticException: long overflow at java.lang.Math.negateExact(Math.java:994) at com.TutorialAndExamples.JavaMathNegateExactExample4.main(JavaMathNegateExactExample 4.java:7)