Skip to lesson

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)

BitwiseOperatorsDemo.javaJava
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) + ")");    }}
Output
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 & b keeps only bit 3 where both 1100 and 1010 have 1, giving 1000 (8).
  • a | b sets bits 3, 2, and 1 where either operand has 1, giving 1110 (14).
  • a ^ b keeps bits 2 and 1 where 1100 and 1010 differ, giving 0110 (6).
  • For a = 12 (1100) and b = 10 (1010): a & b is 1000 (8), a | b is 1110 (14), and a ^ b is 0110 (6).
  • Bitwise AND (a & b): Result bit is 1 only if both bits are 1 (1 & 1 = 1; otherwise 0). Think of & as a filter/mask: ANDing with 0 clears a bit to 0; ANDing with 1 preserves the original bit.
  • Bitwise OR (a | b): Result bit is 1 if at least one bit is 1 (0 | 0 = 0; otherwise 1). Think of | as a setter: ORing with 1 forces a bit to 1; ORing with 0 preserves the original bit.
  • Bitwise XOR (a ^ b, exclusive OR): Result bit is 1 if the two bits are different (1 ^ 0 = 1, 0 ^ 1 = 1, while 0 ^ 0 = 0 and 1 ^ 1 = 0). Think of ^ as a toggle: XORing with 1 flips a bit; XORing with 0 preserves it.
  • Bitwise NOT (~a, complement): Unary operator that flips every bit (0 ↔ 1). In two's complement, ~a always equals -a - 1.

Left and right shifts

Shift operators slide all bits of a number left or right by k positions:

Shifts.javaJava
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    }}
Output
10
8
10
-4
1
4294967296
  • Left shift (x << k): Slides all bits k positions to the left and fills the rightmost k bits with 0s. Shifting left by 1 doubles a number, and in general x << k multiplies x by 2ᵏ (as long as it does not overflow). In particular, 1 << k creates 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-negative x, x >> k divides x by 2ᵏ (floor division).
In Java, shift distances on a 32-bit 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 (>>>)

ShiftOperatorsDemo.javaJava
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));    }}
Output
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 >> 10 shifts 10 copies of the sign bit 1 into the left, so all 32 bits remain 1 (-1).
  • -1 >>> 31 shifts 31 zeros into the left of 32 ones, leaving a single 1 at bit 0 (1).
  • x >> k (arithmetic shift) copies that 1 sign bit into the new leftmost positions (sign extension), keeping negative numbers negative. For example, -8 >> 1 is -4, and -1 >> 5 is still -1 (all 32 bits stay 1).
  • x >>> k (unsigned / logical shift) always fills the leftmost k positions with 0s, regardless of the sign bit! So -1 >>> 1 shifts a 0 into bit 31 and produces 0111...111 = Integer.MAX_VALUE (2147483647). That is also why (lo + hi) >>> 1 computes a binary-search midpoint safely even if lo + hi overflows into a negative int!

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 &

PrecedenceTrapDemo.javaJava
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));    }}
Output
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 >>, so x + 1 << 2 evaluates x + 1 first (11 << 2 = 44).
  • 1 << 31 shifts 1 into the sign bit of a 32-bit int, producing Integer.MIN_VALUE (-2147483648), whereas 1L << 31 shifts a 64-bit long and 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.

public class EvenCheck {
public static void main(String[] args) {
int x = 12;
if (x & 1 == 0) {
System.out.println("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