Java method to swap primitives

javaswap

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.

Best Answer

I think this is the closest you can get to a simple swap, but it does not have a straightforward usage pattern:

int swap(int a, int b) {  // usage: y = swap(x, x=y);
   return a;
}

y = swap(x, x=y);

It relies on the fact that x will pass into swap before y is assigned to x, then x is returned and assigned to y.

You can make it generic and swap any number of objects of the same type:

<T> T swap(T... args) {   // usage: z = swap(a, a=b, b=c, ... y=z);
    return args[0];
}

c = swap(a, a=b, b=c)