![]() |
VOOZH | about |
In Java, bitwise shift operators are used to move the bits of a number to the left or right. The right shift operators move bits toward the right side, which effectively divides the number by powers of two.
4
Explanation:
Java provides two types of right shift operators:
The signed right shift operator (>>) shifts bits to the right while preserving the sign bit (most significant bit).
value >> shiftCount
Example: Signed Right Shift with Positive Number
4
Explanation:
Example: Signed Right Shift with Negative Number
-4
Explanation: The sign bit (1) is preserved during right shift, so the result remains negative.
The unsigned right shift operator (>>>) shifts bits to the right but always fills 0 on the left, regardless of the sign.
value >>> shiftCount
Example: Unsigned Right Shift with Positive Number
4
Explanation: For positive numbers, >> and >>> behave the same.
Example: Unsigned Right Shift with Negative Number
1073741820
Explanation: Zeros are filled from the left, changing the sign and resulting in a large positive number.
Note: We Should Also Know about Bitwise Left Shift Operator in java
| Feature | >> (Signed Right Shift) | >>> (Unsigned Right Shift) |
|---|---|---|
| Definition | Shifts bits to the right while preserving the sign bit. | Shifts bits to the right and fills the leftmost bits with 0. |
| Sign Handling | Keeps the sign of the number (positive/negative). | Ignores the sign and always inserts 0. |
| Use Case | Used when maintaining the sign of the number is important. | Used when working with raw binary values. |
| Result with Negative Numbers | Result usually remains negative. | Result becomes positive because zeros are inserted. |