Binary Right Shift Assign Operator

Binary Right Shift Operator is an efficient way of dividing a number by a power of 2 number, preserving the sign of the original number. Meaning this is a signed operation. We can combine this with assign operation to shorten our code. Below are examples on how we can use Binary Right Shift Assign Operator in java.

Binary Right Shift Assign With Literal

We use >>= for Binary Right Shift Assign Operator in Java. For example:
int a = 16;
a >>= 2;
System.out.println(a);
So we are dividing a by 2 to the power of 2, which is 16 divided by 4, that gives us:
4

And since this is a signed operation, if the variable have a negative value for example:

int a = -16;
a >>= 2;
System.out.println(a);

We get a negative result because it becomes -16 divided by 4, which is:
-4

Binary Right Shift Assign With Another variable

We can use two variables in Binary Right Shift Assign, for exaple:

int a = 33;
int b = 3;
a >>= b;
System.out.println(a);

So this becomes 33 divided by 2 to the power of 3, which is 33 divided by 8 that will result to:
4

Binary Right Shift Assign With An Expression

Lastly, we can use expression not only literals or variables on the right hand side of the operator, for example:
int a = 100;
int b = 3;
a >>= b + 2;
System.out.println(a);
So we evaluate b + 2 which becomes 5. And so we divide 100 by 2 to the power of 5, which is 100 divided by 32, which results to:
3