97.5k views
1 vote
can you write a swap routine in java, or in any other language with only call-by-sharing parameters? what exactly should swap do in such a language? (hint: think about the distinction between the object to which a variable refers and the value [contents] of that object.)

User Aldi
by
8.3k points

1 Answer

6 votes

Yes, I can write a swap routine in Java or any other language that uses call-by-sharing parameters. In such a language, the swap routine can swap the values of two variables without directly modifying the original variables themselves, but by modifying the values held by those variables.

Here is an example implementation of a swap routine in Java:

public static void swap(Double a, Double b) {

Double temp = a;

a = b;

b = temp;

}

In this implementation, the swap routine takes in two Double objects, a and b, which are call-by-sharing parameters. The routine then creates a temporary Double variable called temp, and assigns the value of a to temp. It then sets the value of a to the value of b, and the value of b to the value of temp. Finally, the routine returns, with the values of a and b now swapped.

It's important to note that, while the values of a and b are swapped within the swap routine, the original variables that were passed in as parameters are not modified. This is because Java uses call-by-sharing parameter passing, which means that the variables themselves are not passed into the routine, but rather the values held by those variables are passed in. As a result, any changes made to the values of those variables within the routine do not affect the original variables themselves.

User Kagaratsch
by
8.2k points