Academic Java    Java Tutorial  >  Methods  >  arrays as parameters (a)

arrays as parameters Example

Java arrays as parameters EXAMPLE output When a formal parameter of a method is an array, the length of the array is unimportant to the method.

In this program three arrays of differing lengths are used as actual parameters in calls to the same method show().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Arrays As Parameters Example
class ArraysAsParametersExample {

   static void show(int[] array) {
      System.out.println("length of array is "+array.length);
   }

   public static void main(String[] args) {

      int[] ia = {8,2,19};
      show(ia);
      show(new int[]{});
      show(new int[]{-7,1});

   }
}

11-13 The method show() is called three times with an array as parameter. The length of the array (different for each call) is not part of the method matching process.
On the first call an array of length 3 is passed as a parameter. On the second call an anonymous array of length 0 is passed as a parameter. On the third call an anonymous array of length 2 is passed as a parameter.

4 The formal parameter is an int[], that is an array of int of any length. Each of the three calls therefore matches this method.