7.7 Returning an Array from a Method
When a method returns an array, the reference of the array is returned.
You can pass arrays when invoking a method. A method may also return an array. For example,
the following method returns an array that is the reversal of another array.
1 public static int[] reverse(int[] list) {
2 int[] result = new int[list.length];
3 for (int i = 0, j = result.length - 1;
4 i < list.length; i++, j--) {
5 result[j] = list[i];
6 }
7
8 return result;
9 }
10
Line 2 creates a new array result. Lines 4-7 copy elements from array list to array
result. Line 9 returns the array. For example, the following statement returns a new array
list2 with elements 6, 5, 4, 3, 2, 1:
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
7.8 Case Study: Counting the Occurrences of Each Letter 265
7.7.1 Suppose the following code is written to reverse the contents in an array, explain
why it is wrong. How do you fix it?
int[] list = {1, 2, 3, 5, 4};
for (int i = 0, j = list.length - 1; i < list.length; i++, j--) {
// Swap list[i] with list[j]
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}