Versions Compared

Key

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

...

The value to the right of a shift operation must be within the appropriate range for the type of the numeric value to the left of the shift operation. That is, if the left numeric type is a long, the right value must be within the range [0, 63]; otherwise, the right value must be within the range [0, 31].

Arithmetic vs. Logical Shift

The JLS  [JLS 2005] defines the behavior of the arithmetic shift operator as follows:

...

Noncompliant Code Example (Arithmetic vs. Logical)

In this noncompliant code example, method countOneBits loops forever on negative inputs because the >> operator performs an arithmetic shift rather than a logical shift:

...

Compliant Solution (Arithmetic vs. Logical)

This compliant solution uses the logical shift operator >>>, which clears vacated bits (that is, shifts in zero-bits on the left):

...