Java Reference
In-Depth Information
Arrays and Methods
You will find that when you pass an array as a parameter to a method, the method has
the ability to change the contents of the array. We'll examine in detail later
in the chapter why this occurs, but for now, the important point is simply to understand
that methods can alter the contents of arrays that are passed to them as parameters.
Let's explore a specific example to better understand how to use arrays as parameters
and return values for a method. Earlier in the chapter, we saw the following code for
constructing an array of odd numbers and incrementing each array element:
int[] list = new int[5];
for (int i = 0; i < list.length; i++) {
list[i] = 2 * i + 1;
}
for (int i = 0; i < list.length; i++) {
list[i]++;
}
Let's see what happens when we move the incrementing loop into a method. It
will need to take the array as a parameter. We'll rename it data instead of list to
make it easier to distinguish it from the original array variable. Remember that the
array is of type int[] , so we would write the method as follows:
public static void incrementAll(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i]++;
}
}
You might think this method will have no effect whatsoever, or that we have to
return the array to cause the change to be remembered. But when we use an array as
a parameter, this approach actually works. We can replace the incrementing loop in
the original code with a call on our method:
int[] list = new int[5];
for (int i = 0; i < list.length; i++) {
list[i] = 2 * i + 1;
}
incrementAll(list);
This code produces the same result as the original.
The key lesson to draw from this is that when we pass an array as a parameter to a
method, that method has the ability to change the contents of the array. We don't
need to return the array to allow this to happen.
 
Search WWH ::




Custom Search