liveBook · Manning

Boolean operation

As explained in 100 Java Mistakes and How to Avoid Them

A Boolean operation combines or transforms truth-valued inputs according to logical rules to produce a truth-valued result.

A Boolean operation combines or transforms truth-valued inputs according to a logical rule. In Java, related bitwise operations apply AND, OR, or XOR to individual bits, while precedence determines how compound expressions are grouped. section 2.1.2 section 2.2

Avoid these common Boolean-operation mistakes:

  • Do not mix arithmetic and bitwise operators without parentheses: addition binds more tightly than bitwise AND, so bits & 0xFF00 + 1 is read as bits & (0xFF00 + 1). section 2.1.2
  • Parenthesize bitwise combinations in conditions: comparison operators bind more tightly than bitwise OR, so flags == (Flags.ACC_PUBLIC | Flags.ACC_FINAL) expresses the intended test. section 2.2
  • Treat bit manipulation as boundary-sensitive: shift counts wrap modulo 32 for int and modulo 64 for long, and the left operand determines the shift result type. section 4.12

Make the grouping explicit

The ambiguous expression `return bits & 0xFF00 | 1;` is clearer as `return (bits & 0xFF00) | 1;`. Parentheses show that the mask is applied before the low bit is set. section 2.1.2

int updateBits(int bits) {
  return bits & 0xFF00 + 1;
}

Inspect the minimal expression whose result changes when arithmetic and bitwise precedence is misunderstood. section 2.1.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains precedence, parentheses, compiler detection, and shift corner cases without deriving Boolean algebra.
Examples
Demonstrates masked-bit updates, flag comparisons, negated instanceof conditions, and least-significant-bit masks.
What it assumes
Assumes Java expression familiarity and teaches the relevant precedence and bit-shift behavior through focused mistakes.
What you can do after
Diagnose precedence and shift errors, then prevent them with parentheses, operand checks, and static-analysis rules.
How it connects
Connects Boolean operations with operator precedence, bit manipulation, bit shifting, flags, masks, and static analysis.

Also explained in

Compare how 4 books explain boolean operation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.