My first thought was, it’s because of NaN
(Not-a-number) values, i.e. if the input is NaN
it should get returned without any change. But this seems to be not a requirement as harold’s test has shown that the JVM’s internal optimization does not preserve the sign of NaNs (unless you use StrictMath
).
The documentation of Math.abs says:
In other words, the result is the same as the value of the expression:
Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)
So the option of bit manipulations was known to the developers of this class but they decided against it.
Most probably, because optimizing this Java code makes no sense. The hotspot optimizer will replace its invocation with the appropriate FPU instruction once it encountered it in a hotspot, in most environments. This happens with a lot of java.lang.Math
methods as well as Integer.rotateLeft
and similar methods. They might have a pure Java implementation but if the CPU has an instruction for it, it will be used by the JVM.