Close

Java - Math.negateExact() Examples

Java Java API 


Class:

java.lang.Math

java.lang.Objectjava.lang.Objectjava.lang.Mathjava.lang.MathLogicBig

Methods:

public static int negateExact(int a)

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

Parameters:
a - the value to negate
Returns:
the result
Throws:
java.lang.ArithmeticException - if the result overflows an int
Since:
1.8



public static long negateExact(long a)

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

Parameters:
a - the value to negate
Returns:
the result
Throws:
java.lang.ArithmeticException - if the result overflows a long
Since:
1.8


Examples


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




See Also