Java Program to Swap two Strings Without Using any Third Variable
Last Updated :
11 Sep, 2023
Given two string variables, a and b, your task is to write a Java Program to swap these variables without using any temporary or third variable. Use of library methods is allowed.
Examples:
Input: a = "Hello"
b = "World"
Output:
Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello
Method 1 : In order to swap two string variables without using any temporary or third variable, the idea is to use string concatenation and substring() methods to perform this operation. The substring() method comes in two forms, as listed below:
- substring(int beginindex): This function will return the substring of the calling string starting from the index passed as an argument to this function till the last character in the calling string.
- substring(int beginindex, int endindex): This function will return the Substring of the calling string starting from the beginindex(inclusive) and ending at the endindex(exclusive) passed as an argument to this function.
Algorithm:
1) Append second string to first string and
store in first string:
a = a + b
2) call the method substring(int beginindex, int endindex)
by passing beginindex as 0 and endindex as,
a.length() - b.length():
b = substring(0,a.length()-b.length());
3) call the method substring(int beginindex) by passing
b.length() as argument to store the value of initial
b string in a
a = substring(b.length());
Below is the implementation of the above approach:
Java
// Java program to swap two strings without using a temporary
// variable.
import java.util.*;
class Swap
{
public static void main(String args[])
{
// Declare two strings
String a = "Hello";
String b = "World";
// Print String before swapping
System.out.println("Strings before swap: a = " +
a + " and b = "+b);
// append 2nd string to 1st
a = a + b;
// store initial string a in string b
b = a.substring(0,a.length()-b.length());
// store initial string b in string a
a = a.substring(b.length());
// print String after swapping
System.out.println("Strings after swap: a = " +
a + " and b = " + b);
}
}
OutputStrings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello
Time Complexity: O(n+m) where n and m are lengths of given strings.
Auxiliary Space: O(n+m)
Method 2 : Using Xor operator
Algorithm :
- Convert the input strings to char arrays.
- The XOR swap algorithm uses the XOR operator to swap the values of two variables without using a temporary variable.
- The program applies this algorithm to each pair of characters in the input string using loop.
- After performing the xor operations convert back the char arrays into strings.
Below is the implementation of the above approach.
Java
/*package whatever //do not write package name here */
import java.io.*;
public class Main
{
public static void main(String[] args) {
String a = "Hello";
String b = "World";
System.out.println("Before swap:");
System.out.println("a = " + a);
System.out.println("b = " + b);
// Convert strings to char arrays
char[] charArrayA = a.toCharArray();
char[] charArrayB = b.toCharArray();
// XOR swap algorithm to swap characters without temporary variable
for(int i = 0; i < charArrayA.length && i < charArrayB.length; i++) {
charArrayA[i] ^= charArrayB[i];
charArrayB[i] ^= charArrayA[i];
charArrayA[i] ^= charArrayB[i];
}
// Convert char arrays back to strings
a = new String(charArrayA);
b = new String(charArrayB);
System.out.println("After swap:");
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
OutputBefore swap:
a = Hello
b = World
After swap:
a = World
b = Hello
Time Complexity : O( n+m )
Auxiliary Space : O( n+m )
where n and m are lengths of the string of a and b respectively.
Similar Reads
Java Program to Swap two Variables Given two numbers x and y, we need to swap their values. In this article, we will learn the Swapping of two numbers in Java.Examples of SwappingInput : x = 10, y = 20;Output : x = 20, y = 10Input : x = 213, y = 109Output : x = 109, y = 213Steps to Swap Two Numbers in JavaBelow are the simple steps w
4 min read
Java Program to Swap two Variables Given two numbers x and y, we need to swap their values. In this article, we will learn the Swapping of two numbers in Java.Examples of SwappingInput : x = 10, y = 20;Output : x = 20, y = 10Input : x = 213, y = 109Output : x = 109, y = 213Steps to Swap Two Numbers in JavaBelow are the simple steps w
4 min read
Java Program to Swap the Elements of Vector The swap() method of java.util.Collections class is used to swap the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged. Syntax: public static void swap(List list, int i, int j) Parameters: This method takes
2 min read
Swap Two Variables in One Line We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write "x, y = y, x".2) C/C++: Belo
4 min read
Java Program to print all permutations of a given string A permutation also called an "arrangement number" or "order," is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Source: Mathword(http://mathworld.wolfram.com/Permutation.html) Below are the permutations o
3 min read
StringBuilder replace() in Java with Examples The replace(int start, int end, String str) method of StringBuilder class is used to replace the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified index start and extends to the character at index end - 1 or to the end of the se
3 min read