Java Program to Swap Two Strings

In this post, we will write a simple Java Program to swap two strings without using third String variable.
The login is very simple, first add two string then use substring method to get sub string from s1 and s2.
s1 = s1 + s2;
s2 = s1.substring(0, s1.length() - s2.length());
s1 = s1.substring(s2.length());

Java Program to Swap Two Strings without Third String Variable

/**
 * Java Program to Swap Two Strings without Third String Variable
 * @author javaguides.net
 *
 */
public class SwapTwoStrings {
 public static void main(String[] args) {
  String s1 = "javaguides";

  String s2 = "javadesignpatterns";

  display("Before Swapping :",s1,s2);
  
  // Swapping starts

  s1 = s1 + s2;

  s2 = s1.substring(0, s1.length() - s2.length());

  s1 = s1.substring(s2.length());

  // Swapping ends

  System.out.println("After Swapping :");
  display("After Swapping :",s1,s2);
 }
 
 private static final void display(String str, String s1 , String s2){
  System.out.println(str);
  System.out.println("s1 : " + s1);
  System.out.println("s2 : " + s2);
 }
}
Output:
Before Swapping :
s1 : javaguides
s2 : javadesignpatterns
--------------------------
After Swapping :
s1 : javadesignpatterns
s2 : javaguides
--------------------------

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Related String Programs

Note that these programs are asked in interviews.

Comments