Possible Duplicate:
How does XOR variable swapping work?
I found a solution to switching the values of two variables, without creating a third variable, which is as follows:
x ^= y;
y ^= x;
x ^= y;
This is using the exculsive-or operator ("XOR"), in a way other than boolean (I'm assuming it's bitwise?). Having learned some Discrete Mathematics recently, I can understand the usage of the XOR operator with a truth-table:
.......................
x y (x XOR y)
.......................
T T F
T F T
F T T
F F F
The expression (x XOR y)
evaluates to false when both variables are equivalent, and to true otherwise. But WTF when the values are not boolean?
Anyway, if I set x and y equal to int values instead of boolean values, the operations are not very straightforward. So, for example let
x = 3
, and y = 5
:
public class SwitchValues
{
// instance methods
public void SwitchBoolean(boolean x, boolean y)
{
System.out.println("The variable \"x\" is initially: " + x + ".\n" +
"The variable \"y\" is initially: " + y + ".");
x ^= y;
System.out.println("x ^= y is equal to: " + x + ".");
y ^= x;
System.out.println("y ^= x is equal to: " + y + ".");
x ^= y;
System.out.println("x ^= y is now equal to: " + x + ".");
System.out.println("The variable \"x\" is now: " + x + ".\n" +
"The variable \"y\" is now: " + y + ".\n");
} // end of SwitchBoolean
public void SwitchInts(int x, int y)
{
System.out.println("The variable \"x\" is initially: " + x + ".\n" +
"The variable \"y\" is initially: " + y + ".");
x ^= y;
System.out.println("x ^= y is equal to: " + x + ".");
y ^= x;
System.out.println("y ^= x is equal to: " + y + ".");
x ^= y;
System.out.println("x ^= y is now equal to: " + x + ".");
System.out.println("The variable \"x\" is now: " + x + ".\n" +
"The variable \"y\" is now: " + y + ".\n");
} // end of SwitchInts
// main method
public static void main(String[] args)
{
SwitchValues obj = new SwitchValues();
obj.SwitchBoolean(true, false);
obj.SwitchInts(3, 5);
} // end of main method
} // end of class SwitchValues
... and the results printed out for the int values are as follows:
The variable "x" is initially: 3.
The variable "y" is initially: 5.
x ^= y is equal to: 6.
y ^= x is equal to: 3.
x ^= y is now equal to: 5.
The variable "x" is now: 5.
The variable "y" is now: 3.