Thursday, 8 January 2015

Java Right Shift Operator

In Java, >> is called the right shift operator. It moves the bits in a variable to the right. >> 1 moves the bits one place, >> 2 moves them two places and so on. If you start off with a value such as decimal 15, which is binary 1111, >> 1 changes it to binary 111 or decimal 7. >> 2 moves all the bits two places to the right and converts it to binary 11 or decimal 3. You can see what I mean in the example below:
 
Java > cat prog77.java
public class prog77
{
public static void main (String args[])
  {
  int x = 15;
  System.out.println("x = " + x);
  int y = x >> 1;
  System.out.println("x >> 1 = " + y);
  y = x >> 2;
  System.out.println("x >> 2 = " + y);
  y = x >> 3;
  System.out.println("x >> 3 = " + y);
  y = x >> 4;
  System.out.println("x >> 4 = " + y);
  }
}
Java > javac prog77.java
Java > java prog77
x = 15
x >> 1 = 7
x >> 2 = 3
x >> 3 = 1
x >> 4 = 0
Java >