DEV Community

Cover image for Returning an Array from a Method
Paul Ngugi
Paul Ngugi

Posted on

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.

public static int[] reverse(int[] list) {
  int[] result = new int[list.length];

  for (int i = 0, j = result.length - 1;
  i < list.length; i++, j--) {
  result[j] = list[i];
 }

  return result;
}
Enter fullscreen mode Exit fullscreen mode

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);

Top comments (0)