Versions Compared

Key

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

...

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.)

...

When the operands are different types, multiple conversions can occur. For example, when E1 is an int and E2 is either a long, a float, or a double, E1 is widened from type int to the type of E2 (before the "op"), followed by a narrowing conversion from the type of E2 back to type int (after the "op" but before the assignment).

...

In this noncompliant code example, a variable of type int (big) is multiplied by a value of type float (one). In this case, numeric promotions require that big is promoted to the type float before the multiplication occurs, resulting in loss of precision. (See NUM13-J. Avoid loss of precision when converting primitive integers to floating-point.)

...

This noncompliant code example shows integer promotion resulting from the use of the bit-wise OR operator. The 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 result to contain a value other than the concatenation of the four array elements.

Code Block
bgColor#ffcccc
byte[] b = new byte[4];
...
int result = 0;
for (int i = 0; i < 4; i++) {
  result = ((result << 8) | b[i]);
} 

Compliant Solution (Left Shift)

...

Code Block
bgColor#ccccff
byte[] b = new byte[4];
...
int result = 0;
for (int i = 0; i < 4; i++) {
  result = ((result << 8) | (b[i] & 0xff));
} 

Noncompliant Code Example (Compound Addition and Assignment)

...

This compliant solution applies the compound assignment operator to an int, which does not require widening and subsequent narrowing. Consequently, i gets the value 0x7fffffff.

Code Block
bgColor#ccccff
int i = -1;
i >>>= 1;

...