## Bitwise Operators in Java Example

**Bitwise Operators in Java Example**

In Most of the Interviews, interviewers ask this question frequently and those can answer the question that who have good knowledge in java. This is also frequently asked question in C and C++. People think these are easy question but I warn you it is easy only when third variable is applied but when people asked without applying third variable I is most difficult question. Mostly Fresher’s are confused to give answer and in hassle they give Answer for Swapping two numbers without using third variable is using Arithmetical operator. But Guys now you think foolishly it is totally wrong. Mostly interviewer expects from you that you have to answer swapping two number with using Bitwise operator.

Do not worry with simple Logic and approach you can find it is easy framework.

**Code for Swapping two numbers using bitwise operator**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Public class swap_two // define the class name { Public static void main (String args[]) { // define the main Int first=8, second =9; //Define the Integer inputs System.out.println(“the two numbers befor swapping are:”); System.out.println(“First number”+first); // Represents the first Integer value System.out.println(“Second number”+second); // Represents the second Integer value first= first^second; // means first+second second= first^second; // means first-second first= first^second; // means first-second System.out.println(“the two numbers After swapping are:”); System.out.println(“First number”+first); System.out.println(“Second number”+second); } } |

**Explanation of the code**

For swapping two numbers here we use XOR as a bitwise operator for understanding this code firstly understand XOR gate. The algebraic expression of the XOR gate is so now truth table is :

XOR gate give you Zero if inputs are same and give one if input are different.

**Illustration**

For Explaining XOR we used two numbers 8 and 9 and apply the Bitwise XOR operation between them.

Binary of 8 = 1000

Binary of 9 = 1001

================================

8^9 = 0001

## **Explanation**

Starting from the right, the right most bit of 8 was 0 and that of 9 was also 1.

Since both the bits were different , hence result was 1.

Similarly for 0^0 we got 0, for 0^1 we got 1, for 1^1 we got 0 and for 1^0 we got 1.

So now see the code the input value for first integer is first=8 and second=9;

The binary value for respective integer is first=8= 1000 and second=9=1001

Firstly code change the input in binary values

first= first^second;

first=8^9

first=1000^1001

first=10001

first=17 now input named first is turned into 17

second= first^second;

second=17^9;

second=10001^1001

second=1000 now second becomes 8

first= first^second;

first=10001^1000

first=1001

now first become 9.