Shift Operator Example: Right Shift in Java
This program demonstrates how to use the right shift operator to shift the bits of a number to the right by a specified number of positions.
This program demonstrates how to use the right shift operator to shift the bits of a number to the right by a specified number of positions.
public class OperatorExample {
public static void main(String args[])
{
System.out.println(10>>2);
System.out.println(20>>2);
System.out.println(20>>3);
}
}
2
5
2
This is a Java program that demonstrates the use of the right shift operator (>>). The right shift operator shifts the bits of a number to the right by a specified number of positions, effectively dividing the number by a power of 2.
The program uses the System.out.println() method to print the results of three right shift operations:
10>>2 shifts the bits of the number 10 two positions to the right, resulting in the value 2. This is because 10 in binary is 1010, and shifting it two positions to the right gives 10, which is 2 in decimal.20>>2 shifts the bits of the number 20 two positions to the right, resulting in the value 5. This is because 20 in binary is 10100, and shifting it two positions to the right gives 101, which is 5 in decimal.20>>3 shifts the bits of the number 20 three positions to the right, resulting in the value 2. This is because 20 in binary is 10100, and shifting it three positions to the right gives 10, which is 2 in decimal.When the program is run, it will output the results of these three operations, which are 2, 5, and 2, respectively.
In summary, this program demonstrates how to use the right shift operator to shift the bits of a number to the right by a specified number of positions.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.