Skip to main content

How To Pass / Return An Array In Java

 This Tutorial will Explain How to Pass an Array as an Argument to a Method and as a Return Value for the Method in Java with Examples:

Methods or functions are used in Java to break the program into smaller modules. These methods are called from other functions and while doing so data is passed to and from these methods to the calling functions.

The data passed from the calling function to the called function is in the form of arguments or parameters to the function. The data returned from the function is the return value.

=> Check Here To See A-Z Of Java Training Tutorials Here.


Pass Return Array in Java

Usually, all the primitive and derived types can be passed to and returned from the function. Likewise, arrays also can be passed to the method and returned from the method.

In this tutorial, we will discuss how to pass arrays as an argument to a method and return the array from the method.

What You Will Learn: [show]

Passing Array To The Method In Java

Arrays can be passed to other methods just like how you pass primitive data type’s arguments. To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type.

Given below is the method prototype:

void method_name (int [] array);

This means method_name will accept an array parameter of type int. So if you have an int array named myarray, then you can call the above method as follows:

method_name (myarray);

The above call passes the reference to the array myarray to the method ‘method_name’. Thus, the changes made to myarray inside the method will reflect in the calling method as well.

Unlike in C/C++, you need not pass the length parameter along with array to the method as all Java arrays have a property ‘length’. However, it might be advisable to pass several elements in case only a few positions in the array are filled.

The following Java program demonstrates the passing of an array as a parameter to the function.

public class Main
{
    //method to print an array, taking array as an argument  
    private static void printArray(Integer[] intArray){
        System.out.println("Array contents printed through method:");
        //print individual elements of array using enhanced for loop
       for(Integer val: intArray)
          System.out.print(val + " ");
    }
    public static void main(String[] args) {
        //integer array
            Integer[] intArray = {10,20,30,40,50,60,70,80};
     
         //call printArray method by passing intArray as an argument       
         printArray(intArray);
    }
}

Output:

Output - Passing of an array as a parameter to the function

In the above program, an array is initialized in the main function. Then the method printArray is called to which this array is passed as an argument. In the printArray method, the array is traversed and each element is printed using the enhanced for loop.

Let us take another example of passing arrays to methods. In this example, we have implemented two classes. One class contains the calling method main while the other class contains the method to find the maximum element in the array.

So, the main method calls the method in another class by passing the array to this method find_max. The find_max method calculates the maximum element of the input array and returns it to the calling function.

class maxClass{
   public int find_max(int [] myarray) {
       int max_val = 0;
      //traverse the array to compare each element with max_val
      for(int i=0; i<myarray.length; i++ ) {
         if(myarray[i]>max_val) {
            max_val = myarray[i];
         }
      }
      //return max_val
      return max_val;
   }
}
public class Main
{
    public static void main(String args[]) {
        //input array  
       int[] myArray = {43,54,23,65,78,85,88,92,10};
       System.out.println("Input Array:" + Arrays.toString(myArray));
 
      //create object of class which has method to find maximum
      maxClassobj = new maxClass();
        //pass input array to find_max method that returns maximum element
        System.out.println("Maximum value in the given array is::"+obj.find_max(myArray));
   }
}

Output:

Calculates the maximum element of the input array

In the above program, we have passed the array from one method in one class to another method present in a different class. Note that the approach of passing array is the same whether the method is in the same class or different class.

How To Return An Array In Java

Apart from all the primitive types that you can return from Java programs, you can also return references to arrays.

While returning a reference to an array from a method, you should keep in mind that:

  • The data type that returns value should be specified as the array of the appropriate data type.
  • The returned value from a method is the reference to the array.

The array is returned from a method in the cases where you need to return multiple values of the same type from a method. This approach becomes useful as Java doesn’t allow returning multiple values.

The following program returns a string array from a method.

import java.util.*;
public class Main
{
public static String[] return_Array() {
       //define string array
       String[] ret_Array = {"Java", "C++", "Python", "Ruby", "C"};
      //return string array
      return ret_Array;
   }
 
public static void main(String args[]) {
      //call method return_array that returns array  
     String[] str_Array = return_Array();
     System.out.println("Array returned from method:" + Arrays.toString(str_Array));
 
    }
}

Output:

Output for Return a string array

The above program is an example of returning an array reference from a method. The ‘return_array’ method is declared an array of strings ‘ret_Array’ and then simply returns it. In the main method, the return value from the return_array method is assigned to the string array and then displayed.

The following program provides another example of returning an array from a method. Here, we use an integer array that is used to store the computed random numbers and then this array is returned to the caller.

public class Main
{
   public static void main(String[] args)
   {
      final int N = 10;    // number of random elements
 
      // Create an array
      int[] random_numbers;
 
      // call create_random method that returns an array of random numbers
      random_numbers = create_random(N);
      System.out.println("The array of random numbers:");
      // display array of random numbers
      for (int i = 0; i <random_numbers.length; i++)
      {
          System.out.print(random_numbers[i] + " ");
      }
   }
 
   public static int[] create_random(int N)
   {
      //Create an array of size N => number of random numbers to be generated
      int[] random_array = new int[N];
 
        //generate random numbers and assign to array
      for (int i = 0; i <random_array.length; i++)
      {
          random_array[i] = (int) (Math.random() * 10);
      }
      //return array of random numbers
     return random_array;
   }
}

Output:

Output - Array of Random numbers

Sometimes the results of the computation are null or empty. In this case, most of the time, the functions return null. When arrays are involved it is better to return an empty array instead of null. This is because the method of returning the array will have consistency. Also, the caller need not have special code to handle null values.

Frequently Asked Questions

Q #1) Does Java Pass Arrays by Reference?

Answer: Yes. Arrays are by default passed by reference. While passing the array to function, we simply provide the name of the array that evaluates to the starting address of the array.

Q #2) Why Arrays are not passed by value?

Answer: Arrays cannot be passed by value because the array name that is passed to the method evaluates to a reference.

Q #3) Can an Array be returned in Java?

Answer: Yes, we can return an array in Java. We have already given examples of returning arrays in this tutorial.

Q #4) Can a method return multiple values?

Answer: According to specifications, Java methods cannot return multiple values. But we can have roundabout ways to simulate returning multiple values. For example, we can return arrays that have multiple values or collections for that matter.

Q #5) Can a method have two Return statements in Java?

Answer: No. Java doesn’t allow a method to have more than one return value.

Conclusion

Java allows arrays to be passed to a method as an argument as well as to be returned from a method. Arrays are passed to the method as a reference.

While calling a particular method, the array name that points to the starting address of the array is passed. Similarly, when an array is returned from a method, it is the reference that is returned.

In this tutorial, we discussed the above topics in detail with examples. In our subsequent tutorials, we will cover more topics on arrays in Java.

Comments