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
public class ex{
public static void main(String[] args){
String s1="abc";
String s2="def";
System.out.println(s1);
System.out.println(s2);
s3=s2.replaceAll(s1,s2=s1);
System.out.println(s1);
System.out.println(s2);
}
}
// 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.Actually, the code in your question did not swap String a,b.
You should see this issue: Swap two strings in Java, by passing them to a utility function, but without returning objects or using wrapper classes
And Java is passing by value: Is Java "pass-by-reference" or "pass-by-value"?
package com.core;
public class SwappingNoTemp {
public static void main(String[] args) {
String a = "java";
String b = "c";
a = a + b;
b = a.substring(0, a.length() - b.length());
a = a.substring(b.length());
System.out.println("swapping is a.." + a);
System.out.println("swapping is b.." + b);
}
}
I'd just like to point out, just in case anyone looks through this thread. There is no way of swapping two strings without using a third variable. In the java examples, since strings are immutable, a=a+b creates a third string, and doesn't reassign a. Doing the reverseString, creates a new variable, but this time on the stack frame as the program goes into a new scope. The use of Xor swapping might work, but Strings are immutable in java, and so xor swaps will also create a temporary variable. So in fact, unless the language enables you to reassign to the same memory space, it isn't possible to swap strings without creating new variables.
For strings:
String a = "one"
String b = "two"
a = a + b;
b = a.replace(b, "");
a = a.replace(b, "");