Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap String values without temporary variable

Tags:

java

string

swap

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?

like image 761
Chris Avatar asked Mar 19 '23 11:03

Chris


1 Answers

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.

like image 100
WoDoSc Avatar answered Apr 02 '23 11:04

WoDoSc