Summary
Add a companion set of absolute value methods for int
and long
which throw an exception on the most negative value, whose absolute value is not representable in the same format.
Problem
It is surprising, but true that Math.abs(Integer.MIN_VALUE) equals Integer.MIN_VALUE, a negative value; the some relationship holds for Long.MIN_VALUE. Having absolute value methods which threw exceptions for these exceptional cases would help remove bugs for an easy to overlook case.
Solution
Add absExact
methods for int
and long
to java.lang.Math
and java.lang.StrictMath
.
Specification
Equivalent methods are added to java.lang.Math
and java.lang.StrictMath
:
/**
+ * Returns the mathematical absolute value of an {@code int} value
+ * if it is exactly representable as an {@code int}, throwing
+ * {@code ArithmeticException} if the result overflows the
+ * positive {@code int} range.
+ *
+ * <p>Since the range of two's complement integers is asymmetric
+ * with one additional negative value, the mathematical absolute
+ * value of {@link Integer#MIN_VALUE} overflows the positive
+ * {@code int} range, so an exception is thrown for that argument.
+ *
+ * @param a the argument whose absolute value is to be determined
+ * @return the absolute value of the argument, unless overflow occurs
+ * @throws ArithmeticException if the argument is {@link Integer#MIN_VALUE}
+ * @see Math#abs(int)
+ * @since 15
+ * @see Math#absExact(long)
+ */
+ public static int absExact(int a)
/**
+ * Returns the mathematical absolute value of an {@code long} value
+ * if it is exactly representable as an {@code long}, throwing
+ * {@code ArithmeticException} if the result overflows the
+ * positive {@code long} range.
+ *
+ * <p>Since the range of two's complement integers is asymmetric
+ * with one additional negative value, the mathematical absolute
+ * value of {@link Long#MIN_VALUE} overflows the positive
+ * {@code long} range, so an exception is thrown for that argument.
+ *
+ * @param a the argument whose absolute value is to be determined
+ * @return the absolute value of the argument, unless overflow occurs
+ * @throws ArithmeticException if the argument is {@link Long#MIN_VALUE}
+ * @see Math#abs(long)
+ * @since 15
+ */
+ public static long absExact(long a)
- csr of
-
JDK-8241374 add Math.absExact
- Resolved