How to swap two strings without using a third variable in java / Various methods to swap two strings without additional variable

Swapping strings

Swapping two strings means interchanging their values with one another. Example, there are two string variables s1 and s2 with values
s1 = “codippa.com” and
s2 = “the website”,
Swapping the two strings will make their value as
s1 = “the website” and
s2 = “codippa.com”

Common Approach

The most common approach of swapping two strings is to store the value of one of the strings into a temporary variable and then assigning the value of second string to first one. Finally, assigning the value of temporary variable back to the first string as shown below

String s1 = "codippa.com";
String s2 = "the website";
// create a temporary variable
String temp = null;
// assign the value of first string to temporary variable
temp = s1;
// assign the value of second string to first one
s1 = s2;
// assign the value of temporary variable to second string
s2 = temp;
System.out.println(s1); //prints "the website"
System.out.println(s2); //prints "codippa.com"

This is a simple solution and is of no harm. But suppose due to some requirement you are not supposed to use a temporary(or third) variable or this scenario is put before in an interview, then this post will help you out. It lists different methods to swap two string values without a temp variable.

Method 1: Using concatenation and substring

Java string api provides a couple of substring method which enable to extract portions of a string. This method will utilize its following substring methods.

  • substring(int beginIndex): Returns a substring of string starting from the given index till the end of string. Thus, “codippa.com”.substring(6) will return “.com”.
  • substring(int beginIndex, int endIndex): Returns a substring of string starting from the beginIndex till endIndex - 1. Thus, “codippa.com”.substring(0, 7) will return “codippa”.

Algorithm

This method can be carried out using the below steps.

  1. Calculate the length of first string.
  2. Concatenate both the strings and assign it to first string.
  3. Now use the two argument substring method on the concatenated result with index starting from 0 till the length of first string. Result will be the value of first string. Assign this to the second string.
  4. Now use the one argument substring method on the concatenated value with argument value as the length of the first string. This will return the value of second string. Assign the result to first string.
  5. String values are successfully swapped.

Code for the algorithm is given below

String s1 = "codippa.com";
String s2 = "the website";
// calculate the length of first string
int length = s1.length(); // will be 11
s1 = s1 + s2; // result will be codippa.comthewebsite
s2 = s1.substring(0, length); // result will be codippa.com
s1 = s1.substring(length); // result will be thewebsite
// print both strings
System.out.println("First string : "+s1);
System.out.println("Second string : "+s2); 

Above code will print

First string : the website
Second string : codippa.com

 

This method relies on the concept that String in java is immutable. Every operation on a string returns a separate string leaving actual string unmodified. The above method calls substring twice on s1 each time returning different result which shows that s1 was unmodified even after first substring was called.

 

Method 2: Using concatenation and split

This approach uses split method of java.lang.String class which divides a string on the argument supplied to it and gives the result in an array.

Algorithm

  1. Concatenate two strings with a separator character($, say) and assign the result to any of the two strings.
  2. Now split the result on separator. The result will be an array whose first index is the first string and second index will be second string.
  3. Assign the value at first index of the array to second string and value at the second index of the array to first string.
  4. Strings are swapped successfully.

Code for the above algorithm is given below

String s1 = "codippa.com";
String s2 = "the website";
// concatenate the strings with a separator in between
s2 = s1 + "$" + s2;
// split and assign the value at second index to first string
s1 = s2.split("\\$")[1];
// split and assign the value at first index to second string
s2 = s2.split("\\$")[0];
// print both strings
System.out.println("First string : " + s1);
System.out.println("Second string : " + s2);

Since $ is a special character, it needs to be escaped with \\. If you do not want this, then use any other character such as #, %, & etc., or may be a number.

The above method again shows that String is immutable. Notice both the calls to split return the same array which means that the first call to split did not change the contents of s2.

 

Method 3: Using concatenate and replace

This approach uses replace method of java.lang.String class. This method when called on a string, replaces the sequence of characters in the string with other supplied characters and returns the string after replacement. It takes 2 arguments: string to replace and replacement. Example, "codippa.com".replace(".com", "web"); returns codippaweb.

Algorithm

  1. Concatenate the two strings and assign the result to any one of the two strings.
  2. Call replace on the concatenated result with string to replace as first string and replacement as an empty string. This will return the second string. Assign the result to first string.
  3. Again call replace on the concatenated result with string to replace as second string and replacement as an empty string. This will return the first string. Assign the result to second string.
  4. String values are swapped.

Code implemented using the above algorithm follows

String s1 = "codippa.com";
String s2 = "the website";
// concatenate the strings
s2 = s1 + s2;
// replace first string with blank value
s1 = s2.replace(s1, "");
// replace second string with blank value
s2 = s2.replace(s1, "");
// print both strings
System.out.println("First string : " + s1);
System.out.println("Second string : " + s2);

Output will be

First string : the website
Second string : codippa.com

 

Method 4: Using a helper method

This is a tricky approach which makes use of a method which accepts two string arguments and returns one of those strings. Out of the two arguments, the first argument is one of the strings while second argument is not only a string but an assignment also.

public static void main(String[] args) {
  String s1 = "codippa.com";
  String s2 = "the website";
  // call the helper method with 2 arguments
  s1 = returnFirstString(s2, s2 = s1);
  // print both strings
  System.out.println("First string : " + s1);
  System.out.println("Second string : " + s2);
}

static String returnFirstString(String first, String second) {
    return first;
}

Output will be

First string : the website
Second string : codippa.com

Method returnFirstString accepts two arguments and just returns the first argument. One would say, when the second argument is not required, then why to pass it. Well, there is a reason to it. Notice the line s1 = returnFirstString(s2, s2 = s1); where this method is called. This method call passes the string s2 as first argument. In the second argument, string s1 is assigned to s2 so that s2 now contains the value of s1. Now, without the second argument, it would not be possible to assign s1 to s2.
Also note that in this method call the order of arguments should not be changed since if s2 = s1 is placed as first argument, it will change the value of s2 and the same will be reflected in the second argument.

The above method shows that when calling a method, its arguments are parsed from left to right since the value of s2 was changed in the second argument but the first argument contains the actual value of s2.

 

Note

All the above methods make use of certain java concepts which are highlighted after the method.

Hope this post helped you in better understanding the methods to swap two strings and the logic behind them. Keep visiting for more such stuff.

Leave a Reply