In Java, parameter passing is inherently by value, which poses a challenge when attempting to swap primitive variables within a method. A naive implementation, such as:
<code class="java">void swap(int a, int b) { int temp = a; a = b; b = temp; }</code>
will not actually modify the original variables outside the method. To address this, here are two unconventional approaches:
This technique allows swapping by leveraging the ordering of operations in method calls:
<code class="java">int swap(int a, int b) { // usage: y = swap(x, x=y); return a; }</code>
When calling swap(x, x=y), the value of x will be passed into swap before the assignment to x. Thus, when a is returned and assigned to y, it effectively swaps the values of x and y.
For a more generalized solution, a generic method can be defined that can swap any number of objects of the same type:
<code class="java"><T> T swap(T... args) { // usage: z = swap(a, a=b, b=c, ... y=z); return args[0]; }</code>
Calling this method as z = swap(a, a=b, b=c) will swap the values of a, b, and c, assigning the final value to z.
The above is the detailed content of How Can You Swap Primitive Variables in Java When Parameter Passing is by Value?. For more information, please follow other related articles on the PHP Chinese website!