SCJP Study Guide:
Fundamentals


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
XyzWs SCJP Study Guide: Shift Operators

Shift Operators


Shift operators are applied only to integer types.

  • x << k : shift the bits in x, k places to the left
  • x >> k : shift the bits in x, k places to the right filling in with the highest bit on the left hand side
  • x >>> k : shift the bits in x, k places to the right and fill in with 0

Shift Left

The << operator shifts x left by a number of bits computed as described below.

The high-order bits outside the range of the result type of x are discarded, the remaining bits are shifted left, and the low-order empty bit positions are set to zero.


Shift Right


The >> operator shifts x right by a number of bits computed as described below.

The low-order bits of x are discarded, the remaining bits are shifted right, and the high-order empty bit positions are set to zero if x is non-negative and set to one if x is negative.

Unsigned Shift Right

The >>> operator shifts x right by a number of bits computed as described below.

The low-order bits of x are discarded, the remaining bits are shifted right, and the high-order empty bit positions are set to zero.


Shift Count


The number of bits to shift is computed as follows:

  • If the promoted type of the left-hand operand is int, the shift count is given by the low-order five bits of count. In other words, the shift count is computed from count & 0x1F. The shift distance actually used is therefore always in the range 0 to 31, inclusive.
  • If the promoted type of the left-hand operand is long, the shift count is given by the low-order six bits of count. In other words, the shift count is computed from count & 0x3F. The shift distance actually used is therefore always in the range 0 to 63, inclusive.

If the resulting shift count is zero, the shift operators simply return the value of x. Shift operations never cause overflows.

What is the Value for 12<<-10?

The binary 00000000 00000000 00000000 00001100 is binary number for 12 and 11111111 11111111 11111111 11110110 is for -10. First, we have op1 = 00000000 00000000 00000000 00001100; Second op2 = 0xfffffff6 & 0x1f = 0x16 (22); The result of op1 << op2 is 0x3000000 (50331648).

 


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |