Arrays as Arguments or Return Values in a Method

In this lesson, we explore how an entire array can either be passed to a method as an argument or returned from a method.

Passing an array to a method

To write a parameter in the header of a method’s definition to represent an array, we follow the same rules as for any other parameter. It consists of the data type of the array followed by its name. Since an array’s data type is the type of its entries followed by a pair of square brackets, an array parameter has the following form:

entry-type[ ] array-name

For example, suppose that a driver program uses an array of numbers to test a particular class. At some point in the program, we might need to set these numbers to zero. The driver could define the following static method to accomplish this step:

/** Sets all values in an array to zero. */
public static void clearArray(double[] anArray)
{
   for (int index = 0; index < anArray.length; index++)
      anArray[index] = 0.0;
} // End clearArray

Get hands-on with 1200+ tech skills courses.