How to use BitWise shift operator in Java?

They are called shift operators and they operate by shifting the number of bits being specified as an operand in the operation.


   >> ---> Right shift Operator
  << ---> Left Shift Operator
  >>> ---->  Right bit with zero fill operator.

The first two maintain the MSB when shifting thereby they maintain the sign of the operand. Whereas the third one (zero filled) operator fills the MSB with zeros thats why the special name.

When you say,

  
int x = 5 >> 2; // 0000 0101 gets shifted to two positions in the right and the sign bit is maintained. 
int x = -5 >> 2; // now you get to know the difference as the result would still be negative
int x = 5 << 2; // 0000 0101 gets shifted to two positions to the left
int x = 5 >>> 2; // 2 positions to the right by filling the MSBs zeros and thereby losing the sign bits!

See the program below for an example.

<
public class ShiftOperatorDemo {
    public static void main(String[] args) {
        int x = 5;
        System.out.println("x is : "+x+", binaryString : "+Integer.toBinaryString(x));
        x = x >> 2;
        System.out.println("x >> 2 is : "+x+", binaryString : "+Integer.toBinaryString(x));
        x = 5 << 2;
        System.out.println("5 << 2 is : "+x+", binaryString : "+Integer.toBinaryString(x));
        x = -5 << 2;
        System.o ut.println("-5 << 2 is : "+x+", binaryString : "+Integer.toBinaryString(x));
        x = 5 >>> 2;
        System.out.println("5 >>> 2 is : "+x+", binaryString : "+Integer.toBinaryString(x));
    }    
}

Output is :
x is : 5, binaryString : 101
x >> 2 is : 1, binaryString : 1
5 << 2 is : 20, binaryString : 10100
-5 << 2 is : -20, binaryString : 11111111111111111111111111101100
5 >>> 2 is : 1, binaryString : 1

NOTE: We do NOT have an operator like “<<<” in Java

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*