Shift Operator Example: Right Shift in Java

Java Programming Language Operators in java (Article) Operators in java (Program)

1571

Program:

 
public class OperatorExample {   
    public static void main(String args[])
    {  
    System.out.println(10>>2); 
    System.out.println(20>>2); 
    System.out.println(20>>3);  
    }
} 

Output:

2
5
2

Explanation:

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:

  • The first operation 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.
  • The second operation 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.
  • The third operation 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.


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.