← Back to Chapters

Java Shift Operators

? Java Shift Operators

? Quick Overview

Shift operators in Java are used to shift the bits of a number left or right. They work directly on the binary representation of integers and are commonly used in low-level programming, performance optimization, and bit manipulation.

? Key Concepts

  • << Left Shift
  • >> Signed Right Shift
  • >>> Unsigned Right Shift
  • Works only on integer data types
  • Based on binary (base-2) values

? Syntax / Theory

Java provides three shift operators. They move bits to the left or right and fill empty positions depending on the operator type.

  • a << n → Shifts bits left by n positions
  • a >> n → Shifts bits right, preserving sign
  • a >>> n → Shifts bits right, fills with zero

? Code Examples

? View Code Example
// Demonstrating Java shift operators
public class ShiftOperators {
public static void main(String[] args) {
int a = 8;
System.out.println(a << 1);
System.out.println(a >> 1);
System.out.println(a >>> 1);
}
}

?️ Live Output / Explanation

Output

16
4
4

Left shift doubles the value. Right shift divides the value by 2. Unsigned right shift behaves the same for positive numbers.

✅ Tips & Best Practices

  • Use shift operators only with integer types
  • Prefer readability over micro-optimizations
  • Be careful with negative numbers
  • Unsigned shift is useful for binary data

? Try It Yourself

  • Shift a negative number and observe the result
  • Try multiple left shifts and compare values
  • Convert numbers to binary before shifting