package com.kartik.tutorials;
public class SwapTest {
public
static void main(String[] args) {
Swap aSwap=new Swap();
int a = 2; //0010 in binary
int b = 4; //0100 in binary
aSwap.swapMethod(a,b);
}
}
public class Swap{
private int a;
private int b;
public void swapMethod(int first,int second){
a=first;
b=second;
System.out.println("value of a and b before
swapping, a: " + a +" b: " + b);
a=a^b;
b=a^b;
a=a^b;
System.out.println("value of a and b after swapping
using XOR bitwise operation, a: " + a +" b: " + b);
}
}
Ex-plain:
A B A^B (A XOR B)
0 0 0 (zero
because operands are same)
0 1 1
1 0 1 (one
because operands are different)
1 1 0