Let’s learn shift operator in java.
Shift operator in java
A shift operator basically used to perform bit manipulation on a number by shifting bits of first operand right/left.
- Signed left shift operator or bitwise left shift operator (<<)
- Signed right shift operator or bitwise right shift operator (>>)
- Unsigned right shift operator or bitwise zero fill right shift operator (>>>)
Signed left shift operator (<<)
Signed left shift operator shifts bits of the number to left to a specified number of positions. For example b << 2 means to shift bits of b towards left 2 positions.
Consider an example 9 << 2. So the binary format of 9 is 1 0 0 1.
Now we apply bitwise left shift operator to above binary number, left shift operator shifts this number by 2 bits.
Here shifting by 2 bits means; we have 1 0 0 1 it adds or appends two more zeros. That is 1 0 0 1 0 0 = 36. Let’s see java program.
public class LeftShiftOperatorDemo { public static void main(String[] args) { int b = 9; System.out.println((b << 2)); } }
Output:
36
Sign bit right shift (>>)
Sign bit right shift operator shifts bits of the number to right to a specified number of positions. For example b >> 2 means to shift bits of b towards right 2 positions.
Consider an example 9 >> 2. So the binary format of 9 is 1 0 0 1.
Now we apply right shift operator to above binary number, right shift operator removes 2 bits to our right.
Here removing 2 bits means; remove 0 and 1 in 1 0 0 1. There will be two vacant space to the our left. Remaining is 0 0 1 0 = 2. Let’s see java program.
public class RightShiftOperatorDemo { public static void main(String[] args) { int b = 9; System.out.println(b >> 2); } }
Output:
2
Unsigned right shift operator or bitwise zero fill right shift operator (>>>)
Bitwise zero fill right shift operator shifts bits of the number to right to a specified number of positions. For example b >>> 2 means to shift bits of b towards right 2 positions.
Bitwise zero fill right shift operator is same as signed right shift operator. Bitwise zero fill right shift operator can be applied to both positive and negative number; output always be a positive number. Now let’s see java program.
public class UnsignedRightShiftDemo { public static void main(String[] args) { int a = 9; int b = -1; System.out.println(a >>> 2); System.out.println(b >>> 10); } }
Output:
2
4194303
Also read – polymorphism in java