Home / Programs / Shift Operator Example: Right Shift in Java
🚀 Programming Example

Shift Operator Example: Right Shift in Java

👁 1,701 Views
💻 Practical Program
📘 Step Learning

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.

💻 Program Code

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

                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

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.

🔥 Practice suggestion

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.