How does Java exchange the values of these two variables

  • 2020-04-01 01:10:41
  • OfStack

1. Exchange with intermediate quantities
Int x = 10;
Int y = 20;
Int temp = x;
X = y;
Y = temp;

In this way, we can think of the intermediate as an empty cup, that is, we can think of temp as an empty cup,
Think of x as a glass of white wine, and y as a glass of red wine

Int temp = x; Pour the white wine into an empty glass. At this point, temp contains the white wine and x becomes an empty glass
X = y; Pour the red wine from y into an empty glass of x, where x contains red wine and y becomes empty
Y = temp; Pour the white wine into an empty glass of y, where x holds the red wine and y holds the white wine, and switch between x and y

2. Numerical phase addition and subtraction exchange
Int x = 10;
Int y = 20;
X is equal to x plus y;
Y is equal to x minus y;
X is equal to x minus y;

In this method, the sum of two Numbers is calculated first and then subtracted

X is equal to x plus y; So x is equal to 10 plus 20 is equal to 30;
Y is equal to x minus y; Now x becomes 30 through this top operation, so y is equal to 30 minus 20 is equal to 10;
X is equal to x minus y; So now y becomes 10, so x is equal to 30 minus 10 is equal to 20; Realize the interchange of two Numbers

3. Exchange of displacement calculation

Int x = 10;
Int y = 20;
X is equal to x to the y;
Y is equal to x to the y;
X is equal to x to the y;

Related articles: