0% completed
Shift operators in Java move the bits of an integer value to the left or right. They are used for various low-level programming tasks, such as bit manipulation and efficient multiplication or division by powers of two.
Operator | Description | Example |
---|---|---|
<< | Left shift: Shifts bits to the left, filling in zeros from the right. | a << n shifts a left by n positions. |
>> | Right shift: Shifts bits to the right, preserving the sign (sign extension). | a >> n shifts a right by n positions. |
>>> | Unsigned right shift: Shifts bits to the right, filling in zeros from the left (no sign extension). | a >>> n shifts a right by n positions. |
Below is an example demonstrating the left and right shift operations.
Explanation:
<<
):
a
(which is 8) 2 positions to the left, effectively multiplying it by 2² (4).32
.>>
):
a
2 positions to the right, effectively dividing it by 2² (4).2
.Below is an example that demonstrates the unsigned right shift operator on a negative number.
Explanation:
>>>
):
a = -16
, the unsigned right shift operator shifts the bits to the right by 2 positions, filling the leftmost bits with zeros rather than extending the sign bit.These examples illustrate how shift operators move bits in an integer. Experiment with these operators to see how shifting affects values and aids in performing efficient arithmetic operations.
.....
.....
.....