Write Java program to demonstrate the example of the left shift (<<) operator


This is a Java program that demonstrates the left 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 left shift operator (<<) to shift the bits of num three places to the left. This means that the value of num is multiplied by 2^3 (which is 8), and any overflows are truncated.
  • The result of the left shift operation is stored back in num.
  • Finally, the program outputs the value of num before and after the left shift using the printf method.

Note that the left shift operator can be used to perform multiplication by a power of 2, which is faster than using the multiplication 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

public class LeftShift_Operator
{
	public static void main(String[] args)
	{
		int num = 0xff;
		System.out.printf("Number before left shift: %04X\n", num);		
		num = (num << 3); //shifting 3 bits left
		System.out.printf("Number after left shift: %04X\n", num);
	}
}

Output

Number before left shift: 00FF
Number after left shift: 07F8