Versions Compared

Key

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

Integer variables are frequently intended to represent either a numeric value or a bit collection. Numeric values should be exclusively operated upon using arithmetic operations, while bit collections should be exclusively operated upon using logical operations. However, it is difficult for an analyzer static analyzers are frequently unable to determine the intended usage use of a particular integer variable.

Performing bitwise and arithmetic operations on the same data suggests confusion as to regarding the purpose of the data stored in the variable. Unfortunately, bitwise operations are frequently performed on arithmetic values as a form of premature optimization. Bitwise operators include the unary operator ~ and the binary operators <<, >>, &, ^, and |. Although such operations are valid and will compile, they can reduce code readability.

...

Left- and right-shift operators are often employed to multiply or divide a number by a power of 2. This compromises code readability and portability for the sake of often-illusory speed gains. The JVM will usually make such optimizations automatically; further, and unlike a programmer, the JVM can optimize for the implementation details of the current platform. In this This noncompliant code example , includes both bit manipulation and arithmetic manipulation are performed on of the integer x that conceptually contains a numeric value. The result is a ( prematurely ) optimized statement that assigns 5x + 1 to x.

...

This noncompliant code example masks off the upper 24 bits of the promoted byte array element before performing the addition. The number of bits required to mask the sizes of byte and int are specified by the JLS. While Although this code calculates the correct result, it violates this guideline by combining bitwise and arithmetic operations on the same data.

...

NUM02-EX0: Bitwise operations may be used to construct constant expressions. As Nevertheless, as a matter of style , we recommend replacing such constant expressions with the equivalent hexadecimal constants; 0x1FFFF in this case.

...

NUM02-EX1: Data that is normally treated arithmetically may be treated with bitwise operations for the purpose of serialization or deserialization. This is often required for reading or writing the data from a file or network socket. It may also be used Bitwise operations are also permitted when reading or writing the data from a tightly packed data structure of bytes.

...