How to swap two String variables without third variable.


To swap the contents of two strings (say s1 and s2) without the third, first of all concatenate them and store in s1. Now using the substring() method of the String class store the value of s1 in s2 and vice versa.

Example

 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);
   }
}

Output

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements