Swap String values ​​without a temporary variable

I am aware of overflow, performance degradation, etc., but I need to exchange two String values ​​without any temporary variable. I know what the cons are, and I found some effective methods, but I can not 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);

The conclusion shows that the net values ​​are reversed. When I look at this, it seems that something is related to priority operations, but I can not understand it in my mind. Please, can someone explain to me what is happening?

+4
source share
3 answers

Basically you can think of a swap operation

b = a + (a = b).substring(0, 0);

and

b = "abc" + (a = "def").substring(0, 0);

( a , ).

a "def", b:

b = "abc" + "def".substring(0, 0);

. :

b = "abc";

.substring(0, 0) .

, .

+7

, , , , .

Java (. - " " ).

, b = a + (a = b).substring(0, 0)

  • a :

    b = "abc" + (a = b).substring(0, 0);

  • b :

    b = "abc" + (a = "def").substring(0, 0);

  • (+) , , "def" a.

    b = "abc" + "def".substring(0, 0); //Now a = "def"

  • substring "def"

    b = "abc" + ""

  • b = "abc"

  • b b = "abc" (, , , a "def".

0

Assuming a and b are string variables:

a = (a+b).Substring((b=a).Length);
0
source

Source: https://habr.com/ru/post/1542626/


All Articles