Bitwise operators
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Logical operators like && and || combine whole boolean conditions, whereas bitwise operators work on all 32 bits of an int (or 64 bits of a long) in parallel in a single CPU cycle. Understanding how each operator combines or shifts bits is the foundation of bit manipulation.
AND, OR, XOR and NOT
A bitwise operator works on the individual bits of numbers: & (and), | (or), ^ (xor), ~ (not), << (shift left) and >> (shift right).
Java has four core bitwise operators that line up two integers bit-by-bit (from bit 0 to bit 31) and apply a truth table to each column independently.
Example 1 · Truth Table in Action: &, |, ^, and ~ on 12 (1100) and 10 (1010)
public class BitwiseOperatorsDemo { private static String pad4(int x) { return String.format("%4s", Integer.toBinaryString(x & 0b1111)).replace(' ', '0'); }
public static void main(String[] args) { int a = 0b1100; // 12 int b = 0b1010; // 10
System.out.println("a = " + pad4(a) + " (" + a + ")"); System.out.println("b = " + pad4(b) + " (" + b + ")"); System.out.println("a & b = " + pad4(a & b) + " (" + (a & b) + ")"); System.out.println("a | b = " + pad4(a | b) + " (" + (a | b) + ")"); System.out.println("a ^ b = " + pad4(a ^ b) + " (" + (a ^ b) + ")"); System.out.println("~a = " + ( ~a ) + " (low 4 bits: " + pad4(~a) + ")"); }}a = 1100 (12) b = 1010 (10) a & b = 1000 (8) a | b = 1110 (14) a ^ b = 0110 (6) ~a = -13 (low 4 bits: 0011)
What this code does
a & bkeeps only bit 3 where both1100and1010have1, giving1000(8).a | bsets bits 3, 2, and 1 where either operand has1, giving1110(14).a ^ bkeeps bits 2 and 1 where1100and1010differ, giving0110(6).
- For
a = 12(1100) andb = 10(1010):a & bis1000(8),a | bis1110(14), anda ^ bis0110(6). - Bitwise AND (
a & b): Result bit is1only if both bits are1(1 & 1 = 1; otherwise0). Think of&as a filter/mask: ANDing with0clears a bit to0; ANDing with1preserves the original bit. - Bitwise OR (
a | b): Result bit is1if at least one bit is1(0 | 0 = 0; otherwise1). Think of|as a setter: ORing with1forces a bit to1; ORing with0preserves the original bit. - Bitwise XOR (
a ^ b, exclusive OR): Result bit is1if the two bits are different (1 ^ 0 = 1,0 ^ 1 = 1, while0 ^ 0 = 0and1 ^ 1 = 0). Think of^as a toggle: XORing with1flips a bit; XORing with0preserves it. - Bitwise NOT (
~a, complement): Unary operator that flips every bit (0↔1). In two's complement,~aalways equals-a - 1.
Left and right shifts
Shift operators slide all bits of a number left or right by k positions:
public class Shifts { public static void main(String[] args) { System.out.println(5 << 1); // 5 * 2 System.out.println(1 << 3); // only bit 3 set System.out.println(40 >> 2); // 40 / 4 System.out.println(-8 >> 1); // sign bit copied in System.out.println(1 << 32); // distance masked: 32 & 31 = 0 System.out.println(1L << 32); // long: 2^32 }}10 8 10 -4 1 4294967296
- Left shift (
x << k): Slides all bits k positions to the left and fills the rightmost k bits with0s. Shifting left by 1 doubles a number, and in generalx << kmultipliesxby 2ᵏ (as long as it does not overflow). In particular,1 << kcreates a number with only bit k set (2ᵏ). - Signed (arithmetic) right shift (
x >> k): Slides all bits k positions to the right and fills the leftmost k bits with copies of the sign bit (bit 31). For non-negativex,x >> kdividesxby 2ᵏ (floor division).
int are masked with & 31 (0..31), so 1 << 32 is NOT 0—it evaluates to 1 << (32 & 31) == 1 << 0 == 1! Whenever k can reach 31 or higher, shift a 64-bit long literal: 1L << k.>> versus >>>
Why does Java have both >> and >>>? Because when x is negative, bit 31 is 1 (shown after the code).
Example 2 · Left Shift (<<), Signed Right Shift (>>), and Unsigned Right Shift (>>>)
public class ShiftOperatorsDemo { public static void main(String[] args) { int pos = 13; // 0000...00001101 System.out.println("13 << 2 = " + (pos << 2) + " (13 * 4)"); System.out.println("13 >> 1 = " + (pos >> 1) + " (13 / 2)");
int neg = -16; System.out.println("-16 >> 2 = " + (neg >> 2) + " (sign bit preserved)"); System.out.println("-16 >>> 2 = " + (neg >>> 2) + " (0s shifted into top bits)"); System.out.println("-1 >> 10 = " + (-1 >> 10)); System.out.println("-1 >>> 31 = " + (-1 >>> 31)); }}13 << 2 = 52 (13 * 4) 13 >> 1 = 6 (13 / 2) -16 >> 2 = -4 (sign bit preserved) -16 >>> 2 = 1073741820 (0s shifted into top bits) -1 >> 10 = -1 -1 >>> 31 = 1
What this code does
- For
-1(32 ones),-1 >> 10shifts 10 copies of the sign bit1into the left, so all 32 bits remain1(-1). -1 >>> 31shifts 31 zeros into the left of 32 ones, leaving a single1at bit 0 (1).
x >> k(arithmetic shift) copies that1sign bit into the new leftmost positions (sign extension), keeping negative numbers negative. For example,-8 >> 1is-4, and-1 >> 5is still-1(all 32 bits stay1).x >>> k(unsigned / logical shift) always fills the leftmost k positions with0s, regardless of the sign bit! So-1 >>> 1shifts a0into bit 31 and produces0111...111=Integer.MAX_VALUE(2147483647). That is also why(lo + hi) >>> 1computes a binary-search midpoint safely even iflo + hioverflows into a negativeint!
Precedence traps
Here is the most common bug in Java bit manipulation: bitwise operators &, ^, and | have LOWER precedence than comparison operators ==, !=, <, >!
Example 3 · Operator Precedence Traps: + vs << and == vs &
public class PrecedenceTrapDemo { public static void main(String[] args) { int x = 10;
int withoutParens = x + 1 << 2; int withParens = x + (1 << 2); System.out.println("x + 1 << 2 = " + withoutParens); System.out.println("x + (1 << 2) = " + withParens);
boolean isEven = ((x & 1) == 0); System.out.println("Is 10 even? " + isEven);
System.out.println("1 << 31 = " + (1 << 31)); System.out.println("1L << 31 = " + (1L << 31)); }}x + 1 << 2 = 44 x + (1 << 2) = 14 Is 10 even? true 1 << 31 = -2147483648 1L << 31 = 2147483648
What this code does
- Arithmetic
+and-have higher precedence than<<and>>, sox + 1 << 2evaluatesx + 1first (11 << 2 = 44). 1 << 31shifts1into the sign bit of a 32-bitint, producingInteger.MIN_VALUE(-2147483648), whereas1L << 31shifts a 64-bitlongand produces+2147483648.
If you write if (x & 1 == 0) without parentheses, Java parses it as if (x & (1 == 0))—which compares 1 == 0 (false), tries to compute int & boolean, and fails to compile! Even worse, if (a & b != c) when a is a boolean or in expressions like int ans = x + 1 << 2; (where + has higher precedence than <<, so x + 1 << 2 means (x + 1) << 2, not x + (1 << 2)!) will silently compute the wrong value. Golden rule: always wrap bitwise and shift sub-expressions in parentheses, such as if ((x & 1) == 0) and x + (1 << k).
Fix the error
Fix the precedence bug
The compiler rejects each program. Choose the line that fixes it.
Round 1 of 2
Check whether x is even.
Error
EvenCheck.java:4: error: bad operand types for binary operator '&' first type: int second type: boolean
Next step
Check your understanding
10 quick questions