Swapping two variables

exercise No. 204

Q:

We consider:

Code
public static void main(String[] args) {

    int a = 1, b = 2;
    System.out.println("a = " + a + ", b = " + b);
    {
      // Swapping values of a and b
      final int bCopy = b;
      b = a;
      a = bCopy;
    }
    System.out.println("a = " + a + ", b = " + b);
}
Result
a = 1, b = 2
a = 2, b = 1

The values of a and b are being swapped within the block as expected. We now replace this block by a class method swap(int a, int b){...}:

Code
public static void main(String[] args) {

    int a = 1, b = 2;
    System.out.println("a = " + a + ", b = " + b);

    swap(a, b);

    System.out.println("a = " + a + ", b = " + b);
}

/**
 * Swapping values of two variables
 * @param a First variable
 * @param b Second variable
 */
static void swap(int a, int b) {
    final int bCopy = b;
    b = a;
    a = bCopy;
}
Result
a = 1, b = 2
a = 1, b = 2

This time the values of a and b in main(...) remain unchanged. Why is this not at all surprising?

A:

For the sake of easy variable identification by name we re-factor all variables in swap(...):

public static void main(String[] args) {

    int a = 1, b = 2;
    System.out.println("a = " + a + ", b = " + b);

    swap(a, b);

    System.out.println("a = " + a + ", b = " + b);
}

/**
 * Swapping values of two variables
 * @param x First variable
 * @param y Second variable
 */
static void swap(int x, int y) {
    int yCopy = y;
    y = x;
    x = yCopy;
}

This re-factoring has no effect on execution since both sets of variables {a, b, bcopy} or {x, y, yCopy} are local to our swap(...) method.

Calling swap(a, b) in main(...) copies the values of a and b into x and y respectively. This the usual call-by-value mechanism being the only way calling a method in Java. Swapping these copied values of x and y in swap(...)'s stack frame has no effect on main(...) thus leaving its values a and b unchanged.