Reputation: 41
I am aware of overflow, performance drops, etc but I need to swap two String values without any temporary variable. I know what cons are and found some effective methods but cannot understand one of them.
String a = "abc";
String b = "def";
b = a + (a = b).substring(0, 0);
System.out.printf("A: %s, B: %s", a, b);
Output shows it clear values are swapped. When I look at this seems something related with priority operations but I cannot figure it out in my mind. Please, could someone explain to me what happens?
Upvotes: 4
Views: 294
Reputation: 162
public class swapping { public static void main(String are[]) {
//Swapping two Integer without temp variable
int a=10;
int b=20;
a=a+b;
b=a-b;
a=a-b;
System.out.println(a+" "+b);
//Swapping two string character with temp variable.
String str1="Good";
int as=str1.length();
String str2="Morning";
str1=str1+str2;
str2=str1.substring(0, as);
str1=str1.substring(as);
System.out.println(str1+" "+str2);
}
}
Upvotes: 0
Reputation: 1387
Assuming both a and b are string variables:
a = (a+b).Substring((b=a).Length);
Upvotes: 0
Reputation: 2618
The fact you need to ask the question what's happening here, means you should seriously consider using constructions like this in your code.
Since in Java expressions are evaluated left to right (see here - 'Order of Evaluation' section).
This is what happens step-by-step in case of b = a + (a = b).substring(0, 0)
Populate a
variable with its value:
b = "abc" + (a = b).substring(0, 0);
Populate b variable with its value:
b = "abc" + (a = "def").substring(0, 0);
Since first attribute of string concatenation (+
) is already evaluated evaluate the second one, which starts with reassigning "def"
to a
.
b = "abc" + "def".substring(0, 0); //Now a = "def"
Run substring
on "def"
b = "abc" + ""
Concatenate
b = "abc"
Reassign to b
and now b = "abc" (while as we've shown before a has been reassigned to "def".
Upvotes: 0
Reputation: 2618
Basically you can think on the swap operation
b = a + (a = b).substring(0, 0);
as
b = "abc" + (a = "def").substring(0, 0);
In this first step I simply substituted the variables with their values (except from the a
in the parenthesis, since this is assigning a value, and not reading).
Now a
is equal to "def"
and therefore b
is:
b = "abc" + "def".substring(0, 0);
In this step I substituted the parenthesis with its value. And now that is clearly:
b = "abc";
since the method .substring(0, 0)
returns an empty string.
So the swap is done.
Upvotes: 7