Problem :
Write a java program to swap two string variables without using third or temp variable.
How To Swap Two String Variables Without Using Third Variable in Java?
To swap two string variables without using third or temp variable, we use substring() method of String class. This method has two overloaded forms.
1) substring(int beginIndex)
It returns substring of a calling string starting with the character at the specified index and ending with the last character of the calling string.
2) substring(int beginIndex, int endIndex)
It returns substring of a calling string starting with the character at beginIndex (inclusive) and ending with the character at endIndex (exclusive).
We use both of these forms to swap two string variables without using third variable. Let’s see the java program first and later we will see how it works with an example.
Java Program To Swap Two String Variables Without Using Third Variable :
import java.util.Scanner;
public class SwapTwoStrings
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter First String :");
String s1 = sc.next();
System.out.println("Enter Second String :");
String s2 = sc.next();
System.out.println("Before Swapping :");
System.out.println("s1 : "+s1);
System.out.println("s2 : "+s2);
//Swapping starts
s1 = s1 + s2;
s2 = s1.substring(0, s1.length()-s2.length());
s1 = s1.substring(s2.length());
//Swapping ends
System.out.println("After Swapping :");
System.out.println("s1 : "+s1);
System.out.println("s2 : "+s2);
}
}
Output :
Enter First String :
JAVA
Enter Second String :
J2EE
Before Swapping :
s1 : JAVA
s2 : J2EE
After Swapping :
s1 : J2EE
s2 : JAVA
How It Works?
Let s1 = “JAVA” and s2 = “J2EE”
//Swapping starts
s1 = s1 + s2
–> s1 = “JAVA” + “J2EE”
–> s1 = “JAVAJ2EE”
s2 = s1.substring(0, s1.length()-s2.length())
–> s2 = s1.substring(0, 8-4)
–> s2 = s1.substring(0, 4) //This copies first 4 chars of s1 to s2
–> s2 = “JAVA”
s1 = s1.substring(s2.length())
–> s1 = s1.substring(4) //This copies chars starting from index 4 to end of s1 to s1 itself
–> s1 = “J2EE”
//Swapping ends
After swapping, s1 = “J2EE” and s2 = “JAVA”
Also Read :
40+ Most Asked Java Interview Programs With Solution
30+ Java String Interview Questions And Answers
Frequently Asked Java Interview Programs On Strings
I want to find the Duplicate word and count from the text file
send me the array related program and the answer .
We can swap two string easily using replace function. Below is the code to do it
public class SwapTwoStrings{
public static void main(String []args){
String str1 = “Keep”;
String str2 = “peek”;
str1 = str1.concat(str2);
str2 = str1.replace(str2,””);
str1 = str1.replace(str2,””);
System.out.println(“str1: “+str1+” str2: “+str2);
}
}
Good one