Is it possible to swap two variables in Java? [duplicate]

Not with primitive types (int, long, char, etc). Java passes stuff by value, which means the variable your function gets passed is a copy of the original, and any changes you make to the copy won’t affect the original.

void swap(int a, int b)
{
    int temp = a;
    a = b;
    b = temp;
    // a and b are copies of the original values.
    // The changes we made here won't be visible to the caller.
}

Now, objects are a bit different, in that the “value” of an object variable is actually a reference to an object — and copying the reference makes it point at the exact same object.

class IntHolder { public int value = 0; }

void swap(IntHolder a, IntHolder b)
{
    // Although a and b are copies, they are copies *of a reference*.
    // That means they point at the same object as in the caller,
    // and changes made to the object will be visible in both places.
    int temp = a.value;
    a.value = b.value;
    b.value = temp;
}

Limitation being, you still can’t modify the values of a or b themselves (that is, you can’t point them at different objects) in any way that the caller can see. But you can swap the contents of the objects they refer to.

BTW, the above is rather hideous from an OOP perspective. It’s just an example. Don’t do it.

Leave a Comment