VOOZH about

URL: https://www.geeksforgeeks.org/java/shift-operator-in-java/

⇱ Shift Operator in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shift Operator in Java

Last Updated : 22 Jan, 2026

Shift operators in Java are bitwise operators that shift the binary bits of a number left or right. They work directly on binary data and are commonly used for fast arithmetic operations and low-level bit manipulation.

Shift Operators in Java

Java provides the following three shift operators:

1. Signed Left Shift Operator (<<)

The left shift operator shifts the bits of a number to the left by a specified number of positions. Zeros are added to the right side.

Syntax:

left_operand << number


Output
Original value of a: 64
i and b: 256 0

Explanation:

  • a << 2 shifts the bits of a two positions to the left, effectively multiplying it by 4.
  • The result is stored in i as an int, preserving the full value.
  • When the same result is cast to byte and stored in b, overflow occurs because a byte has a limited range.
  • The output highlights the difference between shifting into an int and casting back to a byte.

2. Signed Right Shift Operator (>>)

The right shift operator shifts bits to the right. The sign bit (MSB) is copied to fill vacant positions, preserving the number’s sign.

Syntax:

left_operand >> number


Output
2

Explanation:

  • number >> 2 shifts the bits of number two positions to the right.
  • The right shift discards the two least significant bits and fills the left side with the sign bit.
  • For 8 (1000 in binary), shifting right by 2 results in 2 (0010), which is printed

Output
b = 0xf1

Explanation:

  • A hex array stores hexadecimal characters (0–f).
  • The byte b is assigned a hexadecimal value (0xf1).
  • (b >> 4) & 0x0f extracts the upper 4 bits, and b & 0x0f extracts the lower 4 bits.
  • These values are used as indexes in the hex array to print the byte in hexadecimal format.

3. Unsigned Right Shift Operator (>>>)

The unsigned right shift operator shifts bits to the right and fills the leftmost bits with 0, regardless of the sign.

Syntax:

left_operand >>> number


Output
2
1073741822

Explanation:

  • For positive numbers, >> and >>> behave the same.
  • For negative numbers, >>> fills leftmost bits with 0, producing a large positive value.

4. Unsigned Left Shift Operator in Java

Java does not provide an unsigned left shift operator (<<<) because:

  • Left shift operations (<<) always insert 0 bits.
  • Logical and arithmetic left shifts are identical in Java.

Related Articles

Comment
Article Tags:
Article Tags: