How can I swap two strings without using a third variable in Java?

Java 8Object Oriented ProgrammingProgramming

To swap the contents of two strings (say s1 and s2) without the third.

  • First of all concatenate the given two strings using the concatenation operator “+” and store in s1 (first string).

s1 = s1+s2;
  • The substring method of the String class is used to this method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1, if the second argument is given.

    Now using the substring() method of the String class store the value of s1 in s2 and vice versa.

s2 = s1.substring(0,i);
s1 = s1.substring(i);


 Live Demo

public class Sample {
   public static void main(String args[]){
      String s1 = "tutorials";
      String s2 = "point";
      System.out.println("Value of s1 before swapping :"+s1);
      System.out.println("Value of s2 before swapping :"+s2);
      int i = s1.length();
      s1 = s1+s2;
      s2 = s1.substring(0,i);
      s1 = s1.substring(i);
      System.out.println("Value of s1 after swapping :"+s1);
      System.out.println("Value of s2 after swapping :"+s2);


Value of s1 before swapping :tutorials
Value of s2 before swapping :point
Value of s1 after swapping :point
Value of s2 after swapping :tutorials
Updated on 30-Jul-2019 22:30:26