3.20 Passing Array References

Arrays are objects in Java (see Section 4.1, p. 100). A review of arrays is recommended before continuing with this section.

The discussion on passing object reference values in the previous section is equally valid for arrays. Method invocation conversions for array types are discussed along with those for other reference types in Section 6.6.

Example 3.5 Passing Arrays
public class Percolate {

    public static void main (String[] args) {
        int[] dataSeq = {6,4,8,2,1};   // Create and initialize an array.

        // Write array before percolation.
        for (int i = 0; i < dataSeq.length; ++i)
            System.out.print(" " + dataSeq[i]);
        System.out.println();

        // Percolate.
        for (int index = 1; index < dataSeq.length; ++index)
            if (dataSeq[index-1] > dataSeq[index])
                swap(dataSeq, index-1, index);                   // (1)

        // Write array after percolation.
        for (int i = 0; i < dataSeq.length; ++i)
            System.out.print(" " + dataSeq[i]);
        System.out.println();
    }

    public static void swap(int[] table, int i, int j) {          // (2)
        int tmp = table[i]; table[i] = table[j]; table[j] = tmp;
    }

    public static void swap(int v1, int v2) {                     // (3)
        int tmp = v1; v1 = v2; v2 = tmp;
    }
}

Output from the program:

6 4 8 2 1
4 6 2 1 8

In Example 3.5, the idea is to repeatedly swap neighboring elements in an integer array until the largest element in the array percolates to the last position of the array.

Note that in the definition of the method swap() at (2), the formal parameter table is of array type. The swap() method is called in the main() method at (1), where one of the actual parameters is the array variable dataSeq. The reference value of the array variable dataSeq is assigned to the array variable table at method invocation. After return from the call to the swap() method, the array variable dataSeq will reflect the changes made to the array via the corresponding formal parameter. This situation is depicted in Figure 3.6 at the first call and return from the swap() method, indicating how values of elements at index 0 and 1 in the array have been swapped.

Figure 3.6. Parameter Passing: Arrays

graphics/03fig06.gif

However, the definition of the swap() method at (3) will not swap two values. The method call

swap(dataSeq[index-1], dataSeq[index]);

will have no effect on the array elements, as the swapping is done on the values of the formal parameters.