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
// taken from this answer: https://stackoverflow.com/a/16826296/427413
String returnFirst(String x, String y) {
return x;
}
String a = "one"
String b = "two"
a = returnFirst(b, b = a); // If this is confusing try reading as a=b; b=a;
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 of b
) is passed as the second argument to the functionb
and ignoring its new valuea
temp
. The parameter x
works as temp
, but it looks cleaner because you define the function once and you can use it everywhere.