Returns the negation of the argument, throwing an exception if the result overflows an int
.
Returns the negation of the argument, throwing an exception if the result overflows a long
.

package com.logicbig.example.math;
public class NegateExactExample {
public static void main(String... args) {
findNegateExact(41);
findNegateExact(357);
findNegateExact(-11);
findNegateExact(0);
findNegateExact(Integer.MIN_VALUE);
}
private static void findNegateExact(int a) {
try {
int negateExact = Math.negateExact(a);
System.out.printf("Math.negateExact(%s) = %s%n", a, negateExact);
} catch (Exception e) {
System.err.println("Error" + e);
}
}
}
Output
Math.negateExact(41) = -41
Math.negateExact(357) = -357
Math.negateExact(-11) = 11
Math.negateExact(0) = 0
Errorjava.lang.ArithmeticException: integer overflow

package com.logicbig.example.math;
public class NegateExactExample2 {
public static void main(String... args) {
findNegateExact(445465);
findNegateExact(912157);
findNegateExact(-3133212);
findNegateExact(0);
findNegateExact(Long.MIN_VALUE);
}
private static void findNegateExact(long a) {
try {
long negateExact = Math.negateExact(a);
System.out.printf("Math.negateExact(%s) = %s%n", a, negateExact);
} catch (Exception e) {
System.out.println("Error:" + e);
}
}
}
Output
Math.negateExact(445465) = -445465
Math.negateExact(912157) = -912157
Math.negateExact(-3133212) = 3133212
Math.negateExact(0) = 0
Error:java.lang.ArithmeticException: long overflow