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.

Logic:-

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:-

Output:-

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

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.
%d bloggers like this: