The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
In Java, the >>
and >>>
operators are both right shift operators, but they differ in how they handle the sign bit (the leftmost bit) when shifting.
>>
(Signed Right Shift):- It shifts the bits to the right.
- It fills the vacant leftmost bits with the sign bit (the leftmost bit) to preserve the sign of the number.
- If the original number is positive, it fills with 0; if negative, it fills with 1.
Example:
javaint num = -8;
int result = num >> 1; // result is -4
>>>
(Unsigned Right Shift):- It also shifts the bits to the right.
- It fills the vacant leftmost bits with zero, irrespective of the sign bit.
- It effectively treats the number as if it were positive.
Example:
javaint num = -8;
int result = num >>> 1; // result is 2147483644 (because it's treated as if it were a positive number)
In summary, >>
preserves the sign bit during the right shift, while >>>
fills the leftmost bits with zero, treating the number as non-negative.