BitwiseOperators

Bitwise Operator in Java – Programming Example

In this chapter you will learn:BitwiseOperators

  1. What is bitwise operator?
  2. How bitwise operator works?
  3. Programming example of bitwise operator
 What is bitwise operator?

AND (&), EXCLUSIVE OR (^), INCLUSIVE OR (|) are called a bitwise operator. Bitwise operator is less commonly used in java programming so you need not to dive deeply in bitwise operator. Bitwise operator is just exists in Java but not in use.

Here, we are taking 2 values and their binary value:

Value 1: 45
Binary value of 45 is : 0010 1101

Value 2: 55
Binary Value of 55 is : 0011 0111

Bitwise And (&) Operator

Bitwise And operator compares each bit of both value respectively and set 1 if both value is 1 otherwise set 0 if one of them is 0.

For example:
num3 = num1 & num2;

Let’s understand it as follow:

Num1 = 0010 1101
Num2 = 0011 0111
————————————-
Num3 = 0010 0101

So the num3 holds the value 37 which is equivalent to binary number 0010 0101

 Bitwise EXCLUSIVE OR (^) or XOR

Bitwise exclusive OR (^) operator compares each bit of both value respectively and set 1 if one of them is 1 and other one is 0.

Example
num3 = num1 ^ num2;

Let’s understand it as follow:

Num1= 0010 1101
Num2= 0011 0111
————————————-
Num3= 0001 1010

So, the num3 holds the value 26 which is equivalent to binary number 0001 1010

Bitwise Inclusive OR (|)

Bitwise inclusive OR (|) operator compares each bit of both operands and set 1 if one of them is 1.

Example
num3 = num1 | num2;

Let’s understand it as follow:

Num1= 0010 1101
Num2= 0011 0111
————————————-
Num3= 0011 1111

So, the num3 holds the value 63 which is equivalent to binary number 0011 1111

Programming Example of bit operator in Java

class BitwiseOperator
{
  public static void main(String[] args)
  {
    int num1, num2, num3;
    num1 = 45;
    num2 = 55;
            
    //Using Bitwise AND(&) Operator
    num3 = num1 & num2;
    System.out.println("Result of num1 & num2 is "+num3);
    
    //Using Bitwise Exclusive OR(^) Operator
    num3 = num1 ^ num2;
    System.out.println("Result of num1 ^ num2 is "+num3);
    
    //Using Bitwise Inclusive OR(|) Operator
      num3 = num1 | num2;
      System.out.println("Result of num1 | num2 is "+num3);
  }
}

Output

D:\JavaProgram>javac BitwiseOperator.java

D:\JavaProgram>java BitwiseOperator
Result of num1 & num2 is 37
Result of num1 ^ num2 is 26
Result of num1 | num2 is 63

D:\JavaProgram> __

Summary

In this chapter you have learned what the bitwise operator in java is and how to use them in a program. Bitwise operator is rarely used by java programmer. In the next chapter you will learn about Loop statements in Java.

Leave a Reply

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