Course contentsShow
← Java
Lesson 120 of 2,8703. Operators and ExpressionsFree lesson

Signed Right Shift Operator (>>)

How >> shifts bits right, preserving the sign bit by filling with sign bit value.

What You'll Learn

You'll learn how the >> operator shifts bits to the right while preserving whether a number is positive or negative by copying the sign bit.

What is the Signed Right Shift Operator?

The signed right shift operator (>>) moves all bits in a number to the right by a specified number of positions. Unlike the left shift that fills with zeros, >> preserves the sign bit (the leftmost bit) by filling the empty left positions with copies of it.

Think of it like sliding a row of tiles to the right on a track—the tiles on the right fall off, and new tiles matching the first tile's type fill in from the left.

How It Works

For positive numbers (sign bit = 0), >> fills with zeros from the left:

int x = 16;  // 00000000 00000000 00000000 00010000
int y = x >> 2;  // Shifts right by 2
// Result: 00000000 00000000 00000000 00000100 (which is 4)

For negative numbers (sign bit = 1), >> fills with ones from the left, maintaining negativity:

int x = -16;  // 11111111 11111111 11111111 11110000
int y = x >> 2;  // Shifts right by 2
// Result: 11111111 11111111 11111111 11111100 (which is -4)

Each right shift by one position effectively divides by 2 (rounding toward negative infinity for negative numbers).

Why the Sign Bit Matters

By copying the sign bit, >> maintains the number's sign. This makes it useful for efficiently dividing by powers of two while preserving whether the result should be positive or negative—a behavior consistent with mathematical division.

Key Takeaway: The >> operator shifts bits right while filling empty left positions with copies of the sign bit, preserving the number's positive or negative nature.