How to swap two string variables in Java without using a third variable

user1281029 picture user1281029 · Aug 30, 2013 · Viewed 57.2k times · Source

How do I swap two string variables in Java without using a third variable, i.e. the temp variable?

String a = "one"
String b = "two"
String temp = null;
temp = a;
a = b;
b = temp;

But here there is a third variable. We need to eliminate the use of the third variable.

Answer

Ankur Lathi picture Ankur Lathi · Aug 30, 2013

Do it like this without using a third variable:

String a = "one";
String b = "two";

a = a + b;
b = a.substring(0, (a.length() - b.length()));
a = a.substring(b.length());

System.out.println("a = " + a);
System.out.println("b = " + b);