No Unnecessary Bit Operation

ID

java.no_unnecessary_bit_operation

Severity

critical

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

redundancy, reliability, suspicious-operator

Description

Reports a bitwise expression whose operand is the identity value for the operator applied, so the operation cannot change the result. x & -1, x | 0 and x ^ 0 all evaluate to x, and the compound assignments x &= -1, x |= 0 and x ^= 0 leave x exactly as it was.

Rationale

Integral values are stored in two’s complement, so -1 has every bit set: masking with it keeps every bit and hands back the original value untouched. The literal 0 has no bit set, so neither | nor ^ can flip anything. Either the expression is dead weight the reader still has to decode, or the constant is simply wrong — a mask meant to be narrower, or a named flag that was renamed away and left a bare 0 behind.

The mirror-image constants are deliberately not reported, because they are not identities and are often intentional: x & 0 always evaluates to 0, and x | -1 always evaluates to -1.

class Registers {

  int keepAll(int value) {
    return value & -1;   // FLAW -- every bit survives the mask
  }

  int setNoBit(int value) {
    return value | 0;    // FLAW -- no bit is set
  }

  int narrow(int value) {
    value &= -1;         // FLAW -- the compound form of the same no-op
    return value;
  }

  int clear(int value) {
    return value & 0;    // OK -- collapses to zero, a real effect
  }

  int keepLowBit(int value) {
    return value & 1;    // OK -- keeps the low bit only
  }
}

Remediation

Drop the operation and use the operand directly. If the constant was meant to be a real mask, correct it to the intended value — check whether a named constant was renamed or removed and left the literal behind.

© 2026 Xygeni. All rights reserved