Java Reference
In-Depth Information
You want x to eventually become equal to 78 , but if you attempt to solve the problem
this way, you lose the old value of x as soon as you assign the value of y to it. The
second assignment statement then copies the new value of x , 78 , back into y , which
leaves you with two variables equal to 78 .
The standard solution is to introduce a temporary variable that you can use to store
the old value of x while you're giving x its new value. You can then copy the old
value of x from the temporary variable into y to complete the swap:
int temp = x;
x = y;
y = temp;
You start by copying the old value of x into temp :
xx3 y78 temp 3
Then you put the value of y into x :
x3
x78 y78 temp 3
Next, you copy the old value of x from temp to y :
x3
x78 y3 temp 3
At this point you have successfully swapped the values of x and y , so you don't
need temp anymore.
In some programming languages, you can define this as a swap method that can be
used to exchange two int values:
// this method won't work
public static void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
As you've seen, this kind of method won't work in Java because the x and y that
are swapped will be copies of any integer values passed to them. But because arrays
are stored as objects, you can write a variation of this method that takes an array and
two indexes as parameters and swaps the values at those indexes:
public static void swap(int[] list, int i, int j) {
int temp = list[i];
 
Search WWH ::




Custom Search