Java Language The Shift Operators (<<, >> and >>>)


Example

The Java language provides three operator for performing bitwise shifting on 32 and 64 bit integer values. These are all binary operators with the first operand being the value to be shifted, and the second operand saying how far to shift.

  • The << or left shift operator shifts the value given by the first operand leftwards by the number of bit positions given by the second operand. The empty positions at the right end are filled with zeros.

  • The '>>' or arithmetic shift operator shifts the value given by the first operand rightwards by the number of bit positions given by the second operand. The empty positions at the left end are filled by copying the left-most bit. This process is known as sign extension.

  • The '>>>' or logical right shift operator shifts the value given by the first operand rightwards by the number of bit positions given by the second operand. The empty positions at the left end are filled with zeros.

Notes:

  1. These operators require an int or long value as the first operand, and produce a value with the same type as the first operand. (You will need to use an explicit type cast when assigning the result of a shift to a byte, short or char variable.)

  2. If you use a shift operator with a first operand that is a byte, char or short, it is promoted to an int and the operation produces an int.)

  3. The second operand is reduced modulo the number of bits of the operation to give the amount of the shift. For more about the mod mathematical concept, see Modulus examples.

  4. The bits that are shifted off the left or right end by the operation are discarded. (Java does not provide a primitive "rotate" operator.)

  5. The arithmetic shift operator is equivalent dividing a (two's complement) number by a power of 2.

  6. The left shift operator is equivalent multiplying a (two's complement) number by a power of 2.

The following table will help you see the effects of the three shift operators. (The numbers have been expressed in binary notation to aid vizualization.)

Operand1Operand2<<>>>>>
0b000000000000101100b00000000000010110b00000000000010110b0000000000001011
0b000000000000101110b00000000000101100b00000000000001010b0000000000000101
0b000000000000101120b00000000001011000b00000000000000100b0000000000000010
0b0000000000001011280b10110000000000000b00000000000000000b0000000000000000
0b0000000000001011310b10000000000000000b00000000000000000b0000000000000000
0b0000000000001011320b00000000000010110b00000000000010110b0000000000001011
...............
0b100000000000101100b10000000000010110b10000000000010110b1000000000001011
0b100000000000101110b00000000000101100b11000000000001010b0100000000000101
0b100000000000101120b00000000001011000b11100000000000100b00100000000000100
0b1000000000001011310b10000000000000000b11111111111111110b0000000000000001

There examples of the user of shift operators in Bit manipulation