Bitwise Operator

package programs; 

public class BitwiseOperator {

  public static void main(String[] args) {

          int a=10,b=12;

          int And =  a&b;

          int Or =  a|b;

          int xor =  a^b;

          int left =  a<<b;

          int right =  a>>b;

          int  three = a>>>b;

          System.out.println("10 & 12  =" +And);

          System.out.println("10 | 12  =" +Or);

          System.out.println("10 ^ 12  =" +xor);

          System.out.println("10 << 12  =" +left);

          System.out.println("10 >> 12  =" +right);

          System.out.println("10 >>> 12  =" +three);

  }

} 

Output :

10 & 12 =8

10 | 12 =14

10 ^ 12 =6

10 << 12 =40960

10 >> 12 =0

10 >>> 12 =0


Explanation :


1. The code defines a class named "BitwiseOperator."

2. The public static void main(String[] args) method is the main entry point of the program.

3. Two integer variables, a and b, are declared and initialized with the values 10 and 12, respectively.

4. The following bitwise operations are performed:
  • int And = a & b;: The bitwise AND operation (&) compares each bit of a with the corresponding bit of b and sets the corresponding bit in the result to 1 if both bits are 1; otherwise, it sets the bit to 0.
  •  int Or = a | b;: The bitwise OR operation (|) compares each bit of a with the corresponding bit of b and sets the corresponding bit in the result to 1 if either of the bits is 1.
  • · int xor = a ^ b;: The bitwise XOR operation (^) compares each bit of a with the corresponding bit of b and sets the corresponding bit in the result to 1 if the bits are different (one is 1, and the other is 0); otherwise, it sets the bit to 0.
  • · int left = a << b;: The bitwise left shift operation (<<) shifts the bits of a to the left by b positions, effectively multiplying a by 2^b.
  • · int right = a >> b;: The bitwise right shift operation (>>) shifts the bits of a to the right by b positions, effectively dividing a by 2^b (this is an arithmetic shift, which preserves the sign bit).
  • · int three = a >>> b;: The unsigned right shift operation (>>>) is similar to the right shift (>>), but it fills the leftmost positions with zeros, effectively dividing a by 2^b while treating the number as unsigned (no sign bit is preserved).
5. The results of the bitwise operations are printed to the console using System.out.println.

Comments

Popular posts from this blog

Installing MySQL and MySQL Workbench

Java Program to Check Palindrome Number

Scenario : 1