Bitwise vs Logical Operators: & vs &&, | vs ||
You'll learn when to use bitwise operators versus their logical counterparts, and how they behave differently with boolean values.
The Core Difference
Java has two sets of similar-looking operators that do very different jobs:
- Bitwise operators (
&,|,^) work on individual bits of integer types - Logical operators (
&&,||) work exclusively with boolean expressions
Here's the twist: the single-character bitwise operators (&, |) can also work with boolean values, but they behave differently than their double-character cousins.
The Key Behavioral Difference
When used with booleans:
&&and||use short-circuit evaluation — they stop evaluating as soon as the result is determined&and|always evaluate both operands — no short-circuiting
boolean a = false;
boolean b = true;
// Logical AND with short-circuit
boolean result1 = a && b; // Evaluates a, sees false, stops (b never checked)
// Bitwise AND with booleans
boolean result2 = a & b; // Evaluates both a AND b, then combines them
When Each Context Applies
Bitwise context (bit manipulation):
int flags = 0b1010;
int mask = 0b0011;
int combined = flags | mask; // Bitwise OR on integers → 0b1011
Boolean context (logic operations):
boolean isValid = (x > 0) && (x < 100); // Logical AND, short-circuits
boolean hasFlag = (status & 0x01) != 0; // Bitwise used to test a bit
Key Takeaway: Use & and | for bit manipulation on integers; use && and || for boolean logic with short-circuit evaluation. When using & or | with booleans, remember both sides always execute.