Swap two Strings without using third user defined variable in Java


In order to swap two strings i.e interchange the content of two strings we will use sub string method of string class in Java.First of all get the length of both strings before making any change in any of string.Now modify one string as concatenate both strings and assign to one string.

After this use sub string method of String class using begin index as length of new modified string 1 and last index as initial length of string 1.This will give us the swiped string 1 which contain content of string 2.

Now to get swiped string 2 again use sub string method here use begin index as 0 and last index as initial length of string 1

Example

Live Demo

public class SwapString {
   public static void main(String[] args) {
      String str1 = "Ram is a good boy.";
      String str2 = "Shyam is a good man.";
      String str3 = "";
      System.out.println("string 1 : " + str1);
      System.out.println("string 2 : " + str2);
      int str1Length = str1.length();
      int str2Length = str2.length();
      str1 = str1 + str2;
      str3 = str1.substring(str1Length, str1.length());
      str2 = str1.substring(0, str1Length);
      System.out.println("string 1 : " + str3);
      System.out.println("string 2 : " + str2);
   }
}

Output

string 1 : Ram is a good boy.
string 2 : Shyam is a good man.
string 1 : Shyam is a good man.
string 2 : Ram is a good boy.

Arushi
Arushi

e

Updated on: 30-Jul-2019

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements