Shift Operators in Java

In this class, We discuss Shift Operators in Java.

The reader should have prior knowledge of bitwise operators. Click here.

Shift Operators:

Left Shift <<

Right Shift >> Holding sign

Right Shift >>> Unsigned

Example:

int a= 10, b;

b= a<<1;

Here 1 means shift bits left side one time.

b=a<<2 means shift bits left side 2 times.

a=10, the binary value of 10 is 001010.

In our example, we are showing 6 bits. But in the system, 32 bits are assigned.

Left shift place zero in the least significant bit position.

The least significant bit is moved to the 2nd position.

The actual bit in the second position is moved to 3rd position.

Similarly, each bit is moved to one position left.

After leaving Shift one time, the output is saved in the variable b.

System.out.println(b); will display 20.

Important: Initial a = 10. After the left Shift, the value is 20.

one left Shift will increase the value multiplied by 2.

a>>2 will have a value of 40.

Each left shift operation will double the value.

Right Shift:

The right Shift starts from the most significant bit.

a=10, b;

b = a>>1 will right shift one bit.

The most significant bit will be copied to maintain the sign.

The most significant bit is moved to the next position, and so on.

The right shift operation will make the value divisible by 2.

a=10;

b = a>>1 will have a value of 5.

b= a>>2 will have a value of 2.

right, Shift two times.

First time 10/2 = 5

The second time 5/2 = 2.5, but the Shift maintains the floor value.

The floor value of 2.5 is 2

Similarly, a floor value of -2.5 is -3.

The division maintains the floor value all the time.

Right Shift >>>

This right shift operation will place zero in the most significant bit position.

After that, Shift the most significant bit to one bit right, and so on.

Here we are not maintaining the sign of the number.