The left-shift, right-shift, and zero-fill-right-shift operators <<, >>, and >>> shift the individual bits of an integer by a specified integer amount.
Example:
x << 3;
y >> 1;
z >>> 2;
In the first example, the individual bits of the integer variable x are shifted to the left three places (so it is multiplied by 2^{3 }i.e. 8). In the second example, the bits of yare shifted 1 place to the right, so it is divided by 2. Finally, the third example shows z being shifted to the right two places, with zeros shifted into the two leftmost places (it is divided by 4 and its sign is converted to positive value if it was negative earlier) .
The number being shifted in this case is the decimal 7, which is represented in binary as 0111. The first right-shift operation shifts the bits two places to the right, resulting in the binary number 0001, or decimal 1. The next operation, a left-shift, shifts the bits one place to the left, resulting in the binary number 1110, or decimal 14. The last operation is a zero-fill-right-shift, which shifts the bits one place to the right, resulting in the binary number 0011, or decimal 3.
With positive numbers, there is no difference between the two operators right-shift operator and zero-fill-right-shift operator, they both shift zeros into the upper bits of a number. The difference arises when we start shifting negative numbers. The negative numbers have the high-order bit set to 1. The right-shift operator preserves the high-order bit and effectively shifts the lower 31 bits to the right. This behavior yields results for negative numbers similar to those for positive numbers. That is, -8 shifted right by one results in -4. The zero-fill-right-shift operator, on the other hand, shifts zeros into all the upper bits, including the high-order bit. When this shifting is applied to negative numbers, the high-order bit becomes 0 and the number becomes positive.
Here is the Java Example for left-shift, right-shift, and zero-fill-right-shift operators
class ShiftOperators
{
public static void main (String args[ ] )
{
int x = 7 ;
System.out.println ("x = " + x) ;
System.out.println ("x >> 2 = " + (x >> 2) ) ;
System.out.println ("x << 1 = " + (x << 1) ) ;
System.out.println ("x >>> 1 = " + (x >>> 1) ) ;
}
}