Question
What happens when you perform a right shift operation on a negative number in Java?
int num = -8; int shifted = num >> 1; // shifted will be -4
Answer
In Java, right shifting a negative number behaves differently compared to a positive number due to the way negative integers are represented in memory. Negative numbers are stored using two's complement notation. When a right shift operation is performed, Java uses an arithmetic right shift for signed numbers, which preserves the sign bit.
int num = -8; // Binary representation: 11111111 11111111 11111111 11111000
int shifted = num >> 1; // Result: -4, Binary: 11111111 11111111 11111111 11111100
Causes
- Negative numbers in Java are represented in two's complement form.
- The sign bit (leftmost bit) remains unchanged during an arithmetic right shift, ensuring the result retains its negative sign.
Solutions
- Use the logical right shift operator (>>>) if you want to shift bits right while filling the leftmost bits with zeros for a non-negative result.
- For operations that require consistent results regardless of the sign, consider using the absolute value of the number before shifting.
Common Mistakes
Mistake: Confusing arithmetic right shift (>>) with logical right shift (>>>) for negative numbers.
Solution: Always verify the type of right shift needed based on whether the number is signed or unsigned.
Mistake: Assuming that right shift will always halve the value of the number.
Solution: Understand that right shifting a negative number results in a lesser negative number, not exactly half.
Helpers
- Java right shift negative number
- Java bit manipulation
- two's complement Java
- arithmetic right shift Java
- Java right shift operator