Search code examples
javastringswap

Swap String values without temporary variable


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?


Solution

  • 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.