Code In Action

Elementary Algorithm : Swapping the values of two variables in Java

This is a very simple problem, and many sorting and data manipulation algorithms uses this internally. Lets see the different approaches to solve this problem.

let's consider two String variables, you can also take any other type of varaibles, such as integer, float , double variables.

String str1 = "abc";
String str2 = "cde";

The output for the problem is str1 should store "cde" i.e str1 = "cde", and str2 should store "abc" i.e str2 = "abc".

A typical non programmer thinks this is simple, and simply assigns

1. str2 to str1 i.e str1 = str2
2. str1 to str2 i.e str2 = str1

Lets evaluate this approach

1. first assign value of str2 to str1. now str1 has value "cde". i.e str1 = "cde". As per our problem, we got str1 = "cde" which is correct.
2. next assign value of str1 to str2. so now str2 has value "cde". i.e str2 = "cde", which is incorrect. As per our problem, it should store "abc". This is happend, because we have already overridden value of str1 variable, so we lost it's original value.

If we fine tune the above algorithm, a bit, we will have the below approach

new value of str1 = old value of str2
new value of str2 = old value of str1

To solve in this way, we need to find a way of not destyoing the old value of str1. This can be achieved by introducing a temporary variable tmp which is also of same type. Now copy the value of str to tmp and then assign this value to str2. The final algorithm is

String tmp;

tmp = str1;
str1 = str2;
str2 = tmp;

Now if we follow this approach.
1. we will have value of str1 in tmp i.e tmp = "abc".
2. Now assign value of str2 to str1 i.e str1 = "cde".
3. finally assign value of tmp to str2 i.e str2 = "abc".

With this algorithm, we got correct result.

Algorithm Description :

1. Save the original value of str1 in tmp.
2. Assign value of str2 to str1.
3. Assign value of tmp to str2.

Implementation in Java:
package com.speakingcs.elemalgos;

public class SwapVariables {

public static void main(String[] args) {

String str1 = "abc";

String str2 = "cde";

String tmp;

tmp = str1; // tmp = "abc"

str1 = str2; // str1 = "cde"

str2 = tmp; // str2 = "abc"

System.out.println("str1 = "+ str1);

System.out.println("str2 = " + str2);

}

}

Detailed Explanation :