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.
- In Java, bitwise shift operators are used to move the bits of a number to the left or right.
- The right shift operators shift bits toward the right side of a number’s binary representation.
class GFG {
public static void main(String[] args) {
int num = 16; // Binary: 10000
int result = num >> 2;
System.out.println(result);
}
}
Output
4
Explanation:
- 16 in binary is 10000.
- Right shifting by 2 positions gives 00100, which is 4.
- The operator fills leftmost bits based on the sign of the number.
Java provides two types of right shift operators:
Signed Right Shift
The signed right shift operator (>>) shifts bits to the right while preserving the sign bit (most significant bit).
- If the number is positive, 0 is filled on the left.
- If the number is negative, 1 is filled on the left (sign extension).
Syntax
value >> shiftCount
Example: Signed Right Shift with Positive Number
class GFG {
public static void main(String[] args) {
int a = 16;
System.out.println(a >> 2);
}
}
Output
4
Explanation:
- Binary of 16 -> 00010000
- After right shift by 2 -> 00000100 (which is 4)
Example: Signed Right Shift with Negative Number
class GFG {
public static void main(String[] args) {
int a = -8;
System.out.println(a >> 1);
}
}
Output
-4
Explanation: The sign bit (1) is preserved during right shift, so the result remains negative.
Unsigned Right Shift Operator
The unsigned right shift operator (>>>) shifts bits to the right but always fills 0 on the left, regardless of the sign.
- Does not preserve the sign bit
- Converts negative numbers into large positive values
Syntax
value >>> shiftCount
Example: Unsigned Right Shift with Positive Number
class GFG {
public static void main(String[] args) {
int a = 16;
System.out.println(a >>> 2);
}
}
Output
4
Explanation: For positive numbers, >> and >>> behave the same.
Example: Unsigned Right Shift with Negative Number
class GFG {
public static void main(String[] args) {
int a = -16;
System.out.println(a >>> 2);
}
}
Output
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
Differences between >> and >>>
| 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. |