Write Java program to demonstrate the example of the right shift (>>) operator


This is a Java program that demonstrates the right shift operator.

  • The program first declares an integer variable num and initializes it to the value 0xff (which is equivalent to 255 in decimal or 11111111 in binary).
  • It then uses the right shift operator (>>) to shift the bits of num three places to the right. This means that the value of num is divided by 2^3 (which is 8), and any remainders are discarded.
  • The result of the right shift operation is stored back in num.
  • Finally, the program outputs the value of num before and after the right shift using the printf method.

Note that the right shift operator can be used to perform division by a power of 2, which is faster than using the division operator (/) when working with large numbers. However, it should be used with caution as it can also lead to unexpected results when used with negative numbers.

Source Code

import java.util.Scanner;
public class RightShift_Operator
{
	public static void main(String[] args)
	{
		int num = 0xff;
		System.out.printf("Number before right shift: %04X\n", num);	
		num = (num >> 3);//shifting 3 bits right
		System.out.printf("Number after right shift: %04X\n", num);
	}
}

Output

Number before right shift: 00FF
Number after right shift: 001F