JDK 15 RF(pre)R of JDK-8241374: add Math.absExact

Joe Darcy joe.darcy at oracle.com
Sat Mar 28 20:34:56 UTC 2020


Hello,

Please review the initial proposed wording of the spec for

     JDK-8241374: add Math.absExact

The eventual wording needs to be replicated four times 
(Math.absExact(int), Math.absExact(long), StrictMath.absExact(int), 
StrictMath.absExact(long)) so I want to get the wording agreed to before 
presenting it in quadruplicate.

The other "exact" methods mention overflow so I wanted the spec to 
absExact to include both "exact" and "overflow" in its description.

Tests will follow in subsequent review iterations.

Thanks,

-Joe

diff -r c5d90e8d4a46 src/java.base/share/classes/java/lang/Math.java
--- a/src/java.base/share/classes/java/lang/Math.java    Sat Mar 28 
11:00:09 2020 -0400
+++ b/src/java.base/share/classes/java/lang/Math.java    Sat Mar 28 
10:17:39 2020 -0700
@@ -1369,6 +1369,32 @@
      }

      /**
+     * 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 and 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 absent overflow
+     * @throws ArithmeticException if the argument is {@link 
Integer#MIN_VALUE}
+     * @see Math#abs(int)
+     * @since 15
+     */
+    public static int absExact(int a) {
+        if (a == Integer.MIN_VALUE)
+            throw new ArithmeticException("Cannot represent " +
+                                          "absolute value of " +
+                                          "Integer.MIN_VALUE");
+        else
+            return abs(a);
+    }
+
+    /**
       * Returns the absolute value of a {@code long} value.
       * If the argument is not negative, the argument is returned.
       * If the argument is negative, the negation of the argument is 
returned.



More information about the core-libs-dev mailing list