Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The Java language allows platforms to use available floating point hardware that can provide floating point support with mantissas and/or exponents that contain more bits than the standard Java primitive type double, thus enabling those platforms to (in the absence of the strictfp modifier). Consequently, these platforms can represent a superset of the values that can be represented by the standard floating point types. Floating point computations on such platforms can produce different results than would be obtained if the floating point computations were restricted to the standard representations of float and double. According to the JLS, Section 15.4, "FP-Strict Expressions"

...

An expression is strict when any of the containing classes, methods, or interfaces is declared to be a strictfp. Constant expressions containing floating point operations are also evaluated strictly. All compile-time constant expressions are by default, strictfp.

The strict Strict behavior cannot be inherited by a subclass that extends a strictfp superclass. An overriding method can independently choose to be strictfp when the overridden method is not or vice versa.

...

Code Block
bgColor#ccccff
strictfp class Example {
  public static void main(String[] args) {
    double d = Double.MAX_VALUE;
    System.out.println("This value \"" + ((d * 1.1) / 1.1) + "\" cannot be represented as double.");
  }
}

Noncompliant Code Example

On platforms whose native floating point hardware provides greater precision than double, the JIT is permitted to use floating point registers to hold values of type float or type double (in the absence of the strictfp modifier), even though the registers support values with greater mantissa and/or exponent range than that of the primitive types. Consequently, conversion from float to double can cause an effective loss of precision, magnitude, or both.

Code Block
bgColor#FFcccc

class Example {
  public static void main(String[] args) {
    float f = Float.MAX_VALUE;
    float g = Float.MAX_VALUE;
    double d = f * g;
    System.out.println("d might not be equal to " + (f * g));
  }
}

The lost precision or magnitude would also have been lost if the value were stored to memory, for example to a field of type float.

Risk Assessment

Failure to use the strictfp modifier can result in implementation-defined behavior, with respect to the accuracy of floating point operations.

...