Question

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?

Was it helpful?

Solution

As you understand, the only way to swap to primitives by a method works only if they are in global scope or class scope.

As for arrays and objects, they are passed by reference in Java. So any changes that you make changes the actual argument to the method. On the other hand if you are looking for a neat way to swap two objects, just implement a swap method as a method in the class and call it like:

anObject.swap(anotherObject);

This way you can implement the swap however you want.

OTHER TIPS

Swapping primitives like that can't be done in Java. The closest you can get is swapping information contained in objects, whether arrays or regular objects that hold values.

You can swap 2 primitives by storing them in an Object like for example an array list. Objects live on the heap space, so basically passing an array list to the swap method is like passing a reference to that array list.

Hope that helps.

EDIT: It is important to note that all parameter passing in JAVA is By Value, but when passing an object you are basically passing the object reference value which points to the object allocated on the Heap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top