You are here:   HomeJava ProgrammingJava ArrayReturning an Array from a Method in Java
by Dinesh Thakur Category: array

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.

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

Returning an Array from a Method

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.

              Returning an Array Example



Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Popular Article