Swap Array Values

It’s pretty common that you’ll need to swap values in an array. But, before we look at a couple of ways to do it, let’s look at a way that makes perfect sense, but doesn’t work.

int[] ray = {1,2,3,4};
ray[0] = ray[1];
ray[1] = ray[0];

At first glance, this code looks like it should work. We’re setting the first element to the second element, and then the second element to the first element. But, it doesn’t work. Why? Because we’re setting the first element to the second element, and then the second element to the first element. So by the time we get to the second element, it’s already been changed.

We end up with the following array.

{1, 1, 3, 4}

So, how do we swap values in an array? There are a couple of ways to do it. Let’s look at the first one.

Using a temporary variable

The first way to swap values in an array is to use a temporary variable.

int[] ray = {1,2,3,4};
int temp = ray[0];
ray[0] = ray[1];
ray[1] = temp;

Here we’re storing the first element in a temporary variable. The fourth line then copies the contents of ray[1] into ray[0], at which point we have the same incorrect array as above. But this time ray[1] = temp takes care of putting the original value of ray[0] into ray[1].

Now we have the swapped array

{2, 1, 3, 4}

Using addition and subtraction

The second way to swap values in an array is to use addition and subtraction.

int[] ray = {1,2,3,4};
ray[0] = ray[0] + ray[1];
ray[1] = ray[0] - ray[1];
ray[0] = ray[0] - ray[1];

It’s a little more mathy, but it works. Honestly, I use the temp variable method every time. It’s easier to understand and remember.

The biggest downside to this method though is that it only works with numeric arrays. The temp variable method works no matter what is in the array.

This site contains affiliate links. If you click an affiliate link and make a purchase we may get a small commission. It doesn't affect the price you pay, but it is something we must disclose.