Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added the phrase "For defense programming purposes"

...

Widening conversions, resulting from integer promotions, preserve the overall magnitude of the number. However, promotions in which the operands are converted from an int to a float or from a long to a double can cause a loss of precision. (See NUM13-J. Avoid loss of precision when converting primitive integers to floating-point for more details.)

These conversions can happen with the following operators: multiplicative can occur when using the multiplicative operators (%, *, /), additive operators (+, -), comparison operators (<, >, <=, >=), equality operators (==, !=), and the integer bitwise operators (&, |, ^).

...

This noncompliant code example shows integer promotion resulting from the use of the bitwise OR operator. Each byte array element is sign-extended to 32 bits before it is used as an operand. If it originally contained the value 0xff, it would contain 0xffffffff [Findbugs 2008]. This would cause causes result to contain a value other than the concatenation of the four array elements.

...

This noncompliant code example performs a compound assignment operation. This operation involves an int value that contains too many significant bits to fit in the 23-bit mantissa of a Java float, causing the widening conversion from int to float to lose precision. The resulting value could surprise many programmersis frequently unexpected.

Code Block
bgColor#FFCCCC
public class Expr {
  public static void main(String[] args) {
    int x = 2147483642; // 0x7ffffffa
    x += 1.0f; // x contains 2147483647 (0x7fffffff) after the computation
  }
}

Compliant Solution (Compound Addition and Assignment)

To be safeFor defense programming purposes, avoid using any of the compound assignment operators on variables of types byte, short, or char. Also, refrain from using a wider operand on the right-hand side. In this compliant solution, all operands are of the Java type double.

...