Make Selenium Easy

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

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

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.

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

by Amod Mahajan time to read: 2 min
0
%d bloggers like this: