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


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 :

Bitwise Operators in Java Example


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


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


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=17 now input named first is turned into 17

second= first^second;



second=1000 now second becomes 8

first= first^second;



now first become 9.