Java Glossary : swap

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : S words : swap.

swap
Exchanging two values is tricky in Java. You can't write a swap method, you must code logic like this inline.

// swap int variables a and b
int a = 1;
int b = 2;
// save a copy of "a" you are about to clobber
int swap = a;
a = b;
b = swap;

To swap two references use logic like this:

// swap references a and b
Thing a = new Thing( 1 );
Thing b = new Thing( 2 );
// save a copy of "a" you are about to clobber
Thing swap = a;
a = b;
b = swap;
// avoid packratting Thing( 1 )
swap = null;

It is possible to swap two values without using a temporary using XOR. Don't use this technique without a serious need. It will confuse the heck out of most programmers.

// Swap references a and b without a temporary
// It works on the principle that if you xor
// with something twice you
// get back to where you started.
// Note, this is slower than using a swap temp variable.
int a = 17;
int b = 42;
a = a ^ b;
b = a ^ b; // a ^ b ^ b = a
a = a ^ b; // a ^ b ^ a ^ b ^ b = b

If you try to encapsulate this logic in a method, it will have no effect on the caller's variables. You have to expand it inline.

// XOR swap fail for swapping array elements if two indexes refer to the same element.
{
   int[] x = { 100, 200 };
   int i = 0, j = 1;
   x[i] ^= x[j];
   x[j] ^= x[i];
   x[i] ^= x[j];
   // prints 200 100
   System.out.println( x[0] + " " + x[1] );
}
{
   int[] x = { 100, 200 };
   int i = 0, j = 0;
   x[i] ^= x[j];
   x[j] ^= x[i];
   x[i] ^= x[j];
   // prints 0 200
   System.out.println( x[0] + " " + x[1] );
}

Further, the XOR technique cannot be used on two Objects in Java, the only time there would be a pressing advantage to it. I present it more as a curiosity from a bygone age.


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 1473.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/swap.html J:\mindprod\jgloss\swap.html