Answer
Swap Two Strings Without Third Variable
Java
public class StringSwapping {
public static void main(String[] args) {
String a = "Hello";
String b = "World";
System.out.println("before swapping: ");
System.out.println("the value of a is: " + a);
System.out.println("the value of b is: " + b);
// Step 1: append a and b
a = a + b; // a = "HelloWorld"
// Step 2: store initial string a in String b
b = a.substring(0, a.length() - b.length());
// b = "HelloWorld".substring(0, 10-5) = "HelloWorld".substring(0,5) = "Hello"
// Step 3: store initial string b in String a
a = a.substring(b.length());
// a = "HelloWorld".substring(5) = "World"
System.out.println("the value of a and b after swapping: ");
System.out.println("the value of a is: " + a);
System.out.println("the value of b is: " + b);
}
}
Output
CODE
before swapping:
the value of a is: Hello
the value of b is: World
the value of a and b after swapping:
the value of a is: World
the value of b is: Hello
Step-by-Step Trace
CODE
a = "Hello" (length=5)
b = "World" (length=5)
Step 1: a = a + b = "HelloWorld" (length=10)
Step 2: b = a.substring(0, a.length()-b.length())
= "HelloWorld".substring(0, 10-5)
= "HelloWorld".substring(0, 5)
= "Hello"
Step 3: a = a.substring(b.length())
= "HelloWorld".substring(5)
= "World"
Result: a="World", b="Hello" ✓
Simpler: Using Temp Variable (Standard Practice)
Java
String a = "Hello";
String b = "World";
String temp = a;
a = b;
b = temp;
System.out.println("a=" + a + ", b=" + b); // a=World, b=Hello
With StringBuilder
Java
StringBuilder a = new StringBuilder("Hello");
StringBuilder b = new StringBuilder("World");
a.append(b); // a = "HelloWorld"
b = new StringBuilder(a.substring(0, a.length() - b.length())); // b = "Hello"
a = new StringBuilder(a.substring(b.length())); // a = "World"
Important Note
The without-temp approach only works correctly when both strings have no overlapping characters that could confuse the substring extraction. For production code, always use a temp variable — it's clearer and safer.
