Java exchanges the values of two variables in the following three methods:
1. intermedian exchange
Int x = 10;
Int y = 20;
Int temp = x;
X = y;
Y = temp;
This method can regard the intermediate amount as an empty cup, that is, to regard temp as an empty cup,
Regard x as a cup containing white wine, and regard y as a cup containing red wine.
Int temp = x; pour the liquor into an empty cup. At this time, temp is filled with liquor, and x is changed to an empty cup.
X = y; Pour red wine in y into x empty cup. At this time, x is filled with red wine, and y is changed to empty cup.
Y = temp; pour white wine into the empty y cup. At this time, x is filled with red wine, and y is filled with white wine to swap x and y.
2. addition, subtraction, and exchange of Values
Int x = 10;
Int y = 20;
X = x + y;
Y = x-y;
X = x-y;
This method calculates the sum of two numbers first and then performs the subtraction operation.
X = x + y; the value of x is 10 + 20 = 30;
Y = x-y; at this time, x is changed to 30 by the above calculation, so y = 30-20 = 10;
X = x-y; at this time, y is changed to 10 by the above calculation, so x = 30-10 = 20; swap two numbers
3. Displacement operation Switching
Int x = 10;
Int y = 20;
X = x ^ y;
Y = x ^ y;
X = x ^ y;