Versions Compared

Key

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

...

Code Block
bgColor#ffcccc
static int countOneBits(long value) {
  int bits = 0;
  while (value != 0) {
    bits += value & 1L;
    value >>= 1; // Signed right- shift, by one
  }
  return bits;
}

...

In this noncompliant code example, the programmer intends to shift a byte value two bits to the right (with zero fill). However, the JLS specifies that the left operand must be promoted to either type int or type long (int, in this case); this promotion performs sign extension. Because of the promotion, the result of the shift for negative input values will be a large positive number, and the programmer could find this result surprising.

Code Block
bgColor#ffcccc
byte b = /* Initialize */;
int result = b >>> 2;

...

This noncompliant code example tries to shift the value -1 by increasing the value of i until, after 32 iterations, the programmer believes the result would become 0. The loop actually never terminates because an attempt to shift a value of type int by 32 bits results in the original value (that is, −1) rather than the expected value 0 [Bloch 2005] . This is because only the least significant 5 bits of i are considered when the shift occurs, and when i reaches the value 32, the 5 least significant bits have the value 0.

...