Frequently Asked Java Programs: 32 – Swap Two String Variables Without Using Third Variable

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program to swap two String variables without using third variable.

Problem Statement:-

Before Swapping:

String s1= “Java”;

String s2= “Selenium”;

After Swapping:

String s1= “Selenium”;

String s2= “Java”;

We have already seen Swapping two number variables without using third variable.


Step 1:-

First concatenate S1 and S2 and store in any existing variable say s1. After step 1 , we will variables with values as:-

s1= SeleniumJava

s2= Java

Step 2:-

Since we have concatenated string in s1, so let’s swap value for s2 first.

s2 should have “Selenium” which starts from zeroth index of s1. If we minus length of s2 from length of concatenated string s1 i.e. (12-4=8) will be swapped value for s2. So use subString method of String class and put starting index as zero and end index as 8.

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

After Step 2, we will have below values:-

s1= SeleniumJava

s2= Selenium

We have done half of work.

Step 3:-

To swap value of s1 , We can use subString method again and put starting index as length of swapped value of s2 i.e. 8. As from 8th index of s1 is desired value. No need to give last index as it will go by default to end if not provided. After Step 3. you will have below values:-

s1= “Java”;

s2= “Selenium”;

Java Program:-

package StringPrograms;

public class SwapTwoStringVariablesWitoutThirdVariable {
	public static void main(String[] args) {
		String s1 = "Java";
		String s2= "Selenium";
		System.out.println("-----Before swapping--------");
		System.out.println("S1= "+s1);
		System.out.println("S2= "+s2);
		// Concatenate value of S2 with S1. Note here that value of S2 will be changed. 
		s1= s1+s2;
		// The swap value of S2 will start from zeroth index in concatenated string. End index will be 
		// total length of concatenated string minus length of S2. 
		s2= s1.substring(0,(s1.length()-s2.length()));
		// The swap value of S1 will be starting at the end of length of swap value of S2 in concatenated 
		// string S1.
		s1= s1.substring(s2.length());
		System.out.println("-----Afetr swapping--------");
		System.out.println("S1= "+s1);
		System.out.println("S2= "+s2);



—–Before swapping——–
S1= Java
S2= Selenium
—–After swapping——–
S1= Selenium
S2= Java


Leave a Reply

Your email address will not be published. Required fields are marked *