Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Operators

Java shift operators

Reference for Java shift operators <<, >> and >>>: signed and unsigned right shift, how the shift distance is masked, and typical uses and pitfalls.

The shift operators move the bits of an integer left or right. << shifts left and fills with zeros, which multiplies by a power of two (until overflow). >> is the signed (arithmetic) right shift: it copies the sign bit into the vacated positions, so negative numbers stay negative. >>> is the unsigned (logical) right shift: it always fills with zeros.

The left operand is promoted to int or long. The result type is that promoted type, not the type of the shift distance.

Java
int a = 1 << 4;      // 16
int b = -16 >> 2;    // -4
int c = -16 >>> 28;  // 15

Try it

Java Left, signed right and unsigned right

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Distance masking and packing bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
value << distance
value >> distance
value >>> distance
Operator Name Fill bits
<< left shift zeros on the right
>> signed right shift copies of the sign bit
>>> unsigned right shift zeros on the left

The compound forms <<=, >>= and >>>= also exist.

Usage notes

  • Distance is masked. For an int only the low 5 bits of the distance are used (x << 32 is x); for a long, the low 6 bits. A negative distance therefore wraps rather than shifting the other way.
  • Overflow. 1 << 31 is Integer.MIN_VALUE. Shifts do not check for lost bits; use Math.multiplyExact if overflow matters.
  • Division by shifting rounds toward negative infinity for negative numbers (-7 >> 1 is -4), whereas / truncates toward zero (-7 / 2 is -3). Do not replace division with shifts for signed values.
  • >>> on byte and short is misleading. The value is promoted to int with sign extension first, so the result does not behave as an 8-bit unsigned shift. Mask with & 0xFF before shifting.
  • The result type follows the promoted left operand, so byte << int gives an int and needs a cast to store back into a byte (compound assignment casts automatically).
  • Prefer readable alternatives (Math.pow, Integer.rotateLeft, ByteBuffer) unless you really handle bit fields.