# Bitwise right shift operators in Java

#### Bitwise right shift operators in Java

In C/C++ there is only one right shift operator ‘>>’ which should be used only for positive integers or unsigned integers. Use of right shift operator for negative numbers is not recommended in C/C++, and when used for negative numbers, output is compiler dependent (See this). Unlike C++, Java supports following two right shift operators.

1) >> (Signed right shift) In Java, the operator ‘>>’ is signed right shift operator. All integers are signed in Java, and it is fine to use >> for negative numbers. The operator ‘>>’ uses the sign bit (left most bit) to fill the trailing positions after shift. If the number is negative, then 1 is used as a filler and if the number is positive, then 0 is used as a filler. For example, if binary representation of number is 10….100, then right shifting it by 2 using >> will make it 11…….1.
See following Java programs as example ‘>>’

class Test {
public static void main(String args[]) {
int x = -6;
System.out.println(x>>1);
int y = 6;
System.out.println(y>>1);
}
}

Output:

-3
3

2) >>> (Unsigned right shift) In Java, the operator ‘>>>’ is unsigned right shift operator. It always fills 0 irrespective of the sign of the number.

class Test {
public static void main(String args[]) {
// x is stored using 32 bit 2's complement form.
// Binary representation of -1 is all 1s (111..1)
int x = -1;
System.out.println(x>>>40);
System.out.println(x>>>42);
System.out.println(x>>>43);
}
}

Output:

16777215
4194303
2097151