Page 106 - CA_Blue( J )_Class9
P. 106

•  Left Shift (<<): This operator shifts bits to the left by the specified number of positions, filling the rightmost bits
                     with 0s. It effectively multiplies the number by 2 for each shift position.
                     Example:
                         int a = 5; // binary: 0101
                         int result = a << 1; // result: 1010 (10 in decimal)
                  •  Right Shift (>>): This operator shifts bits to the right by the specified number of positions. For positive numbers,
                     it fills the leftmost bits with 0s (logical right shift), while for negative numbers, it fills them with 1s (arithmetic
                     right shift), preserving the sign.
                     Example:
                         int a = 5; // binary: 0101
                         int result = a >> 1; // result: 0010 (2 in decimal)
                  •  Unsigned Right Shift (>>>): This operator shifts bits to the right and fills the leftmost bits with 0s, regardless of
                     the number’s sign.
                     Example:
                         int a = -5; // binary: 1111...1011 (in 32-bit representation)
                         int result = a >>> 1; // result is a positive value after the shift


                   Program 20     Write a program to demonstrate the use of bitwise operators.

                     1  public class BitwiseOperators

                     2  {
                     3      public static void main(String[] args)

                     4      {
                     5          int a = 5; // binary: 0101

                     6          int b = 3; // binary: 0011
                     7

                     8          System.out.println("a & b (AND): " + (a & b));
                     9          System.out.println("a | b (OR): " + (a | b));

                    10          System.out.println("a ^ b (XOR): " + (a ^ b));
                    11          System.out.println("~a (NOT): " + (~a));

                    12          System.out.println("a << 1 (Left Shift): " + (a << 1));
                    13          System.out.println("a >> 1 (Right Shift): " + (a >> 1));

                    14          System.out.println("a >>> 1 (Unsigned Right Shift): " + (a >>> 1));
                    15      }

                    16  }













                   104    Touchpad Computer Applications-IX
   101   102   103   104   105   106   107   108   109   110   111