I know all of you here are very knowledgeable and generally quite skilled at explaining, so I'd like to ask for your input.
I've seen a few posts and articles on the distinction between pass-by-value and pass-by-reference languages and they've made me very curious as to how I might implement a swap method. This is of particular interest because both a school project and a personal project are/will be using a swap method in order to work. I did find a rather novel solution by Marcus in this question that I'll use if I cannot find another one.
My understanding is that it is not possible to implement the following and have x = 5, y = 10
as a result:
int x = 10; int y = 5;
swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
public static void main(String[] args) {
swap(x, y);
//x = 10, y = 5
System.out.println("x was 10 and y was 5");
System.out.println("Now x is " + x + ", and y is " + y);
}
However, as far as I have gathered, the following will work because x and y are not passed:
int x = 10; int y = 5;
swap() {
int temp = x;
x = y;
y = temp;
}
public static void main(String[] args) {
swap();
//x = 5, y = 10
}
How do I swap two primitives? What about two instances of the same object (I only need the fields/variables swapped)? Are there any special considerations I must make for swapping in arrays?