Checking whether the result of a bitwise operation is greater than zero may yield unexpected results.

It is more robust to check whether the result of the bitwise operation is non-zero.

In the following example, the expression assigned to variable bad is not a robust way to check that the nth bit of x is set. With the given values of x (all bits are set) and n, the expression x & (1<<n) has the value -2147483648, and the variable bad is assigned false, even though the 31st bit of x is, in fact, set.

In the following example, the expression assigned to variable good is a robust way to check that the nth bit of x is set. With the given values of x and n, the variable good is assigned true.

  • Java Language Specification: Integer Bitwise Operators &, ^, and |.