Arrays as Arguments or Return Values in a Method
Explore how to use arrays in Java methods by passing them as arguments and returning them from methods. Understand the syntax for array parameters, how changes within methods affect arrays, and how to return arrays efficiently. This lesson helps you master essential array operations crucial for Java programming.
We'll cover the following...
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
📝 Syntax: An array as a parameter
Within a method’s header, a parameter can represent an entire array by having the form:
entry-type[]array-namewhere entry-type is the data type of the entries in the array, and array-name is the array’s name. The array’s length is not written explicitly.
Example:
public int countWords(String[] paragraph)
To use the method clearArray ...