Skip to main content

Bitwise in java. Example program of bitwise program.

First let see what is bit-wise operator and example program for bit-wise operator. be ready with  concentrated mind.

---------------------------------------------------------------------------------------------------------------

CONTENT
  1. What is bit-wise.
  2. Example program.
  3. Explanation of example program
  4. Output of example program.
  5. Task :)
---------------------------------------------------------------------------------------------------------------

What is bit-wise operator?

        Bit-wise operator are used for controlling and interaction with hardware and also for manipulating data at the bit level.

There are six bit-wise operators.

 Operator Description
      &
       |
      ^
      ~
    <<
    >>
   >>>
   <<=
   >>=
 >>>=
Bit-wise AND
Bit-wise OR.
Bit-wise Ex-OR.
One's complement
left shift
Right shift.
Zero fill right shift
Left shift assignment.
Right shift assignment.
Zero fill right shift assignment.

Example:
                
x=4, y=5

 Operator Description
      x&y
       x|y
      x^y
      ~x
    x<<2
    x>>2
   x<<=2
   x>>=2
        4
        5
        1
       -5
       16
        1
       16
        1

know more about operator.
know more about bit-wise operator.

Example java program for bit-wise operator.

    import java.io.*;
    class test
    {
        public static void main(String args[])
            {
                int a=60;
                int b=13;
                int c=0;
                c=a&b;
                System.out.println("a&b=" +c);
                c=a^b;
                System.out.println("a^b=" +c);
                c=a/b;
                System.out.println("a/b=" +c);
                c=~a;
                System.out.println("~a=" +c);
                c=a<<2;
                System.out.println("a<<2=" +c);
                c=a>>>2;
                System.out.println("a>>>2=" +c);
            }
    }

Explanation:
  • Using import keyword we are getting access to java.io package which is the collection of classes required for input and output changes or manipulation.
  • class test refer to the complied file of our source code.
  • public static void main(String arg[]) refers to add a method tho the program.
  • int a, int b, int c is declaring the variable and initialize with a number.
  • then bit-wise operation is declared.
  • System.out.println is used to display the given in output screen(make sure S in System is capital)
  • All the STATEMENT should end with semicolon.

Output:
        a&b=73
        a|b=49
        a^b=4
        ~a=-61
        a<<2=240
        a>>2=15


Complete the task:
choose any other value to a and b in the program and try to get the output. Mention your output in the command below.

Comments