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
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:”);
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.
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=17 now input named first is turned into 17
second=1000 now second becomes 8
now first become 9.