To swap the values of two variables in Java, you can use a temporary variable to store one of the values while you update the other variable.
Here's an example of how to swap the values of two variables x
and y
in Java:
int x = 1; int y = 2; int temp = x; x = y; y = temp;
In this example, the value of x
is stored in the temporary variable temp
, and then the value of y
is assigned to x
. Finally, the value of temp
is assigned to y
, effectively swapping the values of x
and y
.
You can also use destructuring assignment introduced in Java 14 to swap the values of two variables in a single line of code:
int x = 1; int y = 2; (x, y) = (y, x);
In this example, the values of x
and y
are destructured and assigned to a tuple, and then the tuple is destructured and assigned to x
and y
, effectively swapping their values.
You can find more information about destructuring assignment and other features of Java in the Java documentation.