Common Pitfalls: Precedence and Sign Extension
You'll learn: The two most common mistakes when working with bitwise operators—operator precedence surprises and unexpected sign extension behavior.
Operator Precedence Traps
Bitwise operators have lower precedence than comparison operators, which leads to subtle bugs. When you write x & MASK == VALUE, Java doesn't evaluate it as you might expect.
The comparison MASK == VALUE happens first, producing a boolean, then Java tries to perform x & boolean—a type error!
What you meant: (x & MASK) == VALUE
What Java sees: x & (MASK == VALUE) ← compilation error
Always use parentheses around bitwise operations when combined with comparisons or arithmetic operators. The precedence hierarchy is:
- Arithmetic (
*,/,%, then+,-) - Shift operators (
<<,>>,>>>) - Comparisons (
<,>,<=,>=) - Equality (
==,!=) - Bitwise (
&,^,|) - Logical (
&&,||)
Sign Extension: The Hidden Gotcha
When you shift or promote negative values (especially byte or short), Java performs sign extension—it fills new bits with copies of the sign bit to preserve the value.
byte b = -1; // In binary: 11111111 (8 bits)
int i = b; // Sign-extended: 11111111111111111111111111111111 (32 bits)
This catches beginners off-guard when using bitwise operations on small integer types. If you shift >> a negative byte, those 1-bits propagate, maintaining negativity. Use >>> (unsigned right shift) if you want zero-fill behavior.
Key Takeaway: Always parenthesize bitwise operations in complex expressions, and remember that negative values get sign-extended when promoted to larger integer types, filling with 1-bits instead of zeros.