➗ Operators & Expressions · Beginner

Shift operators in Java

<<, >> (sign-extending) and >>> (zero-fill).

🧩 The mystery1 << 31 is a huge negative number. 1 << 32 is... 1. Shift operators hide some of Java's strangest results.

Left shift multiplies by 2ⁿ

x << n moves every bit n places to the left and fills the gap with zeros. Each place doubles the value, as long as no bits fall off the top.

3 << 1    // 110   = 6
3 << 2    // 1100  = 12
1 << 10   // 1024

>> keeps the sign

x >> n moves bits to the right and copies the sign bit into the gap, so negative numbers stay negative. It divides by 2ⁿ, rounding down.

20 >> 2    // 5
-16 >> 2   // -4
🔮 Predict it

Your turn

What does this print?

System.out.println(5 << 3);
System.out.println(40 >> 3);
  1. 40 5
  2. 15 13
  3. 8 5
Show the answer

5 << 3 is 5 × 2³ = 40, and 40 >> 3 is 40 / 2³ = 5.

>>> fills with zeros

>>> (unsigned right shift) fills the gap with zeros, clearing the sign bit, so a negative number turns positive. There's no <<<: left shifts always fill with zeros anyway.

// -16 is 0xFFFFFFF0
-16 >>> 28   // 1111 = 15
🔮 Predict it

Your turn

-1 is all 32 bits set to 1. What does this print?

System.out.println(-8 >> 1);
System.out.println(-1 >>> 28);
  1. -4 15
  2. 4 15
  3. -4 -1
Show the answer

>> keeps the sign: -8 >> 1 is -4. >>> brings in zeros: shifting thirty-two 1-bits right by 28 leaves four 1s, 1111 = 15.

⚠️ The trap

Shifting by 32 or more

For an int, only the lowest 5 bits of the distance are used, so the distance is effectively taken mod 32. 1 << 32 is really 1 << 0, which is 1. Need 2³²? Use a long: 1L << 32 (longs use the distance mod 64).

1 << 32    // 1, not 4294967296
1L << 32   // 4294967296
💼 In the real world

In real projects

Shifts power graphics, hashing and network code: (rgb >> 16) & 0xFF extracts the red channel from a color. Java's own HashMap spreads hash codes with h ^ (h >>> 16).

Key takeaways

  1. x << n is x × 2ⁿ (if nothing overflows)
  2. >> keeps the sign: -16 >> 2 is -4
  3. >>> fills with zeros: negative becomes positive
  4. int shifts use distance % 32: 1 << 32 is 1
🤯 Did you know?

C has no >>> operator. Java added it because Java has no unsigned integer types, so it needed a separate way to shift right while filling with zeros.

Practice questions

What does this print?

System.out.println(3 << 2);
System.out.println(20 >> 2);
  1. 12 5
  2. 6 10
  3. 12 10
  4. 32 5
Check your answer

12 5. 3 << 2 is 3 × 4 = 12, and 20 >> 2 is 20 / 4 = 5.

What does this print?

System.out.println(-16 >> 2);
System.out.println(-16 >>> 28);
  1. -4 -1
  2. -4 15
  3. 4 15
  4. -4 1
Check your answer

-4 15. >> keeps the sign, so -16 >> 2 is -4. -16 is 0xFFFFFFF0; >>> 28 brings in zeros and leaves the top four 1-bits, 1111, which is 15.

Next: an if/else squeezed into one expression, the ternary operator, and its sneaky type rules.