Java Program to Illustrate the Use of Various Bitwise Operators

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this Java program, we will have a glance at a program in java to illustrate the use of various bitwise operator.

Java Program to Illustrate the Use of Various Bitwise Operators

import java.util.Scanner;

public class Exmp

{

  public static void main(String[] args)

   {

       int m, n, x, a;

       Scanner s = new Scanner(System.in);

       System.out.print("Enter First number:");

       m = s.nextInt();

       System.out.print("Enter Second number:");

       n = s.nextInt();

       while(true)

       {

           System.out.println("");

           System.out.println("Enter 1 for Right Shift by 2:");

           System.out.println("Enter 2 for Left Shift by 2:");

           System.out.println("Enter 3 for Bitwise AND:");

           System.out.println("Enter 4 for Bitwise OR by 2:");

           System.out.println("Enter 5 for Bitwise Exclusive OR:");

           System.out.println("Enter 6 for Bitwise NOT:");

           System.out.println("Enter 7 to Exit:");

           System.out.println("");

           System.out.print("Option:");

           x = s.nextInt();

           switch(x)

           {

               case 1:

               a = m << 2;

               System.out.println("Result after left shift by 2:"+a);

               break;

 

               case 2:

               a = n >> 2;

               System.out.println("Result after right shift by 2:"+a);  

               break;

 

               case 3:

               a = m & n;

               System.out.println("Result after bitwise AND:"+a); 

               break;

 

               case 4: 

               a = m | n;

               System.out.println("Result after bitwise OR:"+a);

               break;

 

               case 5:

               a = m ^ n;

               System.out.println("Result after bitwise Exclusive OR:"+a);

               break;   

 

               case 6:

               a = ~ m;

               System.out.println("Result after bitwise NOT:"+a);

               break;   

 

               case 7:

               System.exit(0);

           }

       }

    }

}

Output:

Enter First number:5

Enter Second number:6

Enter 1 for Right Shift by 2:

Enter 2 for Left Shift by 2:

Enter 3 for Bitwise AND:

Enter 4 for Bitwise OR by 2:

Enter 5 for Bitwise Exclusive OR:

Enter 6 for Bitwise NOT:

Enter 7 to Exit:

Leave a Comment

Your email address will not be published. Required fields are marked *