Search code examples
javaswap

Java method to swap primitives


how do I make my swap function in java if there is no method by which we can pass by reference? Could somebody give me a code?

swap(int a, int b)
{
     int temp = a;
     a = b;
     b = temp;
}

But the changes wont be reflected back since java passes parameters by value.


Solution

  • You can't create a method swap, so that after calling swap(x,y) the values of x and y will be swapped. You could create such a method for mutable classes by swapping their contents¹, but this would not change their object identity and you could not define a general method for this.

    You can however write a method that swaps two items in an array or list if that's what you want.

    ¹ For example you could create a swap method that takes two lists and after executing the method, list x will have the previous contents of list y and list y will have the previous contents of list x.