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.
You can do in this way.
// taken from this answer: https://stackoverflow.com/a/16826296/427413
This works because the Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined), so the execution order is:
b
is evaluated in order to be passed as the first argument to the functionb = a
is evaluated, and the result (the new value ofb
) is passed as the second argument to the functionb
and ignoring its new valuea
temp
. The parameterx
works astemp
, but it looks cleaner because you define the function once and you can use it everywhere.Jj Tuibeo's solution works if you add replaceFirst() and use a regular expression:
The simplest way is given below:
You can also do this by using a temp variable but in a different way: