3.21 Array Elements as Actual Parameters

Array elements, like other variables, can store values of primitive data types or references to objects. In the latter case it means they can also be arrays, that is, array of arrays (see Section 4.1, p. 104). If an array element is of a primitive data type, then its data value is passed, and if it is a reference to an object, then the reference value is passed.

Example 3.6 Array Elements as Primitive Data Values
public class FindMinimum {

    public static void main(String[] args) {
        int[] dataSeq = {6,4,8,2,1};

        int minValue = dataSeq[0];
        for (int index = 1; index < dataSeq.length; ++index)
            minValue = minimum(minValue, dataSeq[index]);            // (1)

        System.out.println("Minimum value: " + minValue);
    }

    public static int minimum(int i, int j) {                        // (2)
        return (i <= j) ? i : j;
    }
}

Output from the program:

Minimum value: 1

In Example 3.6, note that the value of all but one element of the array dataSeq is retrieved and passed consecutively at (1) to the formal parameter j of the minimum() method defined at (2). The discussion in Section 3.18 on call-by-value also applies to array elements that have primitive values.

Example 3.7 Array Elements as Object Reference Values
public class FindMinimumMxN {

    public static void main(String[] args) {
        int[][] matrix = { {8,4},{6,3,2},{7} };                // (1)

        int min = findMinimum(matrix[0]);                      // (2)
        for (int i = 1; i < matrix.length; ++i) {
            int minInRow = findMinimum(matrix[i]);             // (3)
            if (min > minInRow) min = minInRow;
        }
        System.out.println("Minimum value in matrix: " + min);
    }

    public static int findMinimum(int[] seq) {                 // (4)
        int min = seq[0];
        for (int i = 1; i < seq.length; ++i)
            min = Math.min(min, seq[i]);
        return min;
    }
}

Output from the program:

Minimum value in matrix: 2

In Example 3.7, note that the formal parameter seq of the findMinimum() method defined at (4) is an array variable. The variable matrix denotes an array of arrays declared at (1), simulating a multidimensional array, which has three rows, where each row is an array. The first row, denoted by matrix[0], is passed to the findMinimum() method in the call at (2). Each remaining row is passed by reference value in the call to the findMinimum() method at (3).