Question
What is the difference between the >>> and >> operators in Java?
Answer
In Java, the ">>" and ">>>" operators are both bitwise shift operators used to shift the bits of an integer data type. However, they differ in how they handle the sign bit during the shifting process.
public class ShiftOperatorsExample {
public static void main(String[] args) {
int signed = -8; // in binary: 11111111 11111111 11111111 11111000
int unsigned = signed >> 2; // Output: 11111111 11111111 11111111 11111110 (remains negative)
int unsignedShift = signed >>> 2; // Output: 00111111 11111111 11111111 11111110 (treated as positive)
System.out.println("Signed Shift: " + unsigned);
System.out.println("Unsigned Shift: " + unsignedShift);
}
}
Causes
- The ">>" operator is the signed right shift operator, which shifts bits to the right and fills the leftmost bits with the sign bit (0 for positive numbers, 1 for negative numbers).
- The ">>>" operator is the unsigned right shift operator, which shifts bits to the right and fills the leftmost bits with zeros, regardless of the original sign of the number.
Solutions
- Use ">>" when you want to maintain the sign of the number during shifting, for example, when dealing with signed integers.
- Use ">>>" when you need to shift bits and discard the sign, especially for treating the integer as an unsigned value.
Common Mistakes
Mistake: Assuming that both operators behave the same regardless of the sign of the number.
Solution: Always remember that ">>" preserves the sign bit, while ">>>" does not.
Mistake: Using the unsigned right shift operator on negative numbers expecting a negative result.
Solution: Understand that ">>>" treats the number as unsigned, hence the leftmost bits will be filled with zeros.
Helpers
- Java shift operators
- bitwise operators in Java
- unsigned right shift operator Java
- signed right shift operator Java
- difference between >> and >>> in Java