Just like a method can return a primitive type, similarly a method can also return an array. If a method returns an array then its return type is an array. This is really useful when a method computes a sequence of values.
In order to understand how an array is returned from a method, consider a program that returns an array which is the reverse of another array.
public class ReturningArray
{
public static void main(String[] args)
{
int[] num= {5,15,25,30,50};
System.out.println("Elements in Original Array :");
for(int i=0;i<num.length;i++)
System.out.print(num[i]+" ");
int[] result=reverse(num);
System.out.println("\nElements in New Array :");
for(int i=0;i<result.length;i++)
System.out.print(result[i]+" ");
}
static int[] reverse(int[] orgArray)
{
int[] temp=new int[orgArray.length];
int j=0;
for(int i=orgArray.length-1;i>=0;i--,j++)
temp[j]=orgArray[i];
return temp;
}
}
In this program, we first input the elements of the array. In order to reverse the array elements, we make a method reverse () that takes array as argument and returns an array that contains the elements in the reverse order. The statement
int[] result = reverse(num)i
invokes the function reverse () and pass the original array as an argument through its reference variable num which is copied into the orgArray parameter. In the method body, the statement
int[] temp = new int[orgArray.length]i
creates a new array of length same as that of original array and stores its reference in the variable temp. Then using the for loop, the elements are copied from orgArray one by one into new array temp in the reversed order. Once all the elements are copied, the loop terminates. The statement,
return temp;
returns the reference of the new array through its variable temp which is then assigned to the reference variable result. Finally, its contents are displayed.