Shift Operators (<<, >>, >>> Unsigned Right Shift)
1Concept
Left shift << multiplies by powers of 2. Signed right shift >> divides by 2 preserving the sign bit. Unsigned right shift >>> shifts zeros into the high-order bit, useful for binary data.
2Architecture Diagram
5 << 1 ---> 10 (Multiply by 2) -8 >> 1 ---> -4 (Signed right shift, preserves 1 bit) -8 >>> 1---> 2147483644 (Unsigned right shift, zero fills high bit)
3Code Example
Core Java
public class BitShiftDemo {
public static void main(String[] args) {
int val = 16;
System.out.println("16 << 2 (16 * 4): " + (val << 2));
System.out.println("16 >> 2 (16 / 4): " + (val >> 2));
int neg = -16;
System.out.println("-16 >> 2 (Signed): " + (neg >> 2));
System.out.println("-16 >>> 2 (Unsigned): " + (neg >>> 2));
}
}4Expected Output
16 << 2 (16 * 4): 64 16 >> 2 (16 / 4): 4 -16 >> 2 (Signed): -4 -16 >>> 2 (Unsigned): 1073741820
5Key Takeaways
- ✓Unsigned right shift >>> is unique to Java and essential for cryptographic & binary packet processing.
- ✓Left shifting an integer past 31 bits wraps mod 32 in Java.
- ✓Bit shifting is significantly faster than standard division in low-level bytecode.