How to Return Array in Java from Method

Return Array in Java | In the previous tutorial, we have learned how to pass an array as an argument to a method while calling a method.

Although we can pass an array when calling a method, we can also return an array from a method, just like other simple data types and objects.

When a method returns an array, actually, the reference of the array is returned. For example, we create a class called ReturnArray from a method named display().

When we will call display() method, it will return an array num of integers (i.e. integer array). Look at the following source code.

Program source code 1:

package arraysProgram;
public class ReturnArray {
 public int[ ] display()
 {
    int[] num = {1, 2, 3, 4, 5};
    return num; // Returning the reference of array that refers to the  array elements.
 }
}
public class Test {
public static void main(String[] args) 
{
  ReturnArray obj = new ReturnArray();
   int[ ] num = obj.display(); 
  for(int i = 0; i < num.length; i++)
  {
	System.out.println("num[" +i+ "] = " + num[i]); 
  }
 }
}
Output:
          num[0] = 1
          num[1] = 2
          num[2] = 3
          num[3] = 4
          num[4] = 5

In this program, the class ReturnArray is defined with a method named display(). The display() method is defined with one dimensional array as its argument and it is made to return one-dimensional array.

The purpose of this method is to return a reference of array that refers to array elements, to a calling method.

In the main() method, we have called display() method using object reference variable obj and is to display them using for loop one by one on the console.


Now let’s understand the general syntax of how to return one dimensional and two-dimensional arrays from a method in java.

Returning One dimensional Array from Method in Java


The general syntax of a method that can return a one dimensional array is as follows:

data-type[ ][ ] method-name(argument)
{
    // statements;
   // return arrayname;
}

Here, data-type represents the type of array being returned. The use of one pair of brackets ([ ]) indicates that the method is returning one-dimensional array of type data-type.

Arguments can be optional that can be a scalar type or array type. The return statement returns the array name without any brackets.

The syntax of calling a method is as follows:

data-type[ ] arrayname = obj-ref.method-name(arguments);

Here, obj-ref is a reference to an object of the class of which the method is a member. The arguments (if any) are inputs to a method given from the calling method.


Let’s create a simple program to compute the sum of elements in an array of integers.

Program source code 2:

package arraysProgram;
public class ArraySum 
{
 static int[ ] sum()
 {
    int[ ] data = {10, 20, 30 ,40 , 50};
    return data;
 }
	
public static void main(String[] args) 
{
  int sum = 0;	
  int[ ] s = sum();
 for(int i = 0; i < s.length; i++ )
 {
     sum = sum + s[i]; 
   }
 System.out.println("Sum of array elements: " +sum);
 }
}
Output:
           Sum of array elements: 150

Returning Two dimensional Array from a Method in Java


We can also return two dimensional array from a method in java. The general syntax to declare a method that can return a two-dimensional array is as follows:

data-type[ ][ ] method-name()
{
   // statement
  // return arrayname;
}

In the above syntax, the use of two pairs of square brackets indicates that the method returns two-dimensional array of type data-type.

The general syntax of calling a method is as follows:

data-type[ ][ ] arrayname = obj-ref.method-name(arguments);

Let’s take an example program where we will return two dimensional array from a method. In this program, we will take two-dimensional arrays of int type that will represent two matrices.

Then, we will add them and get them into another two-dimensional array of int type that represents sum matrix. This sum matrix will be displayed on the console.

Program source code 3:

package arraysProgram;
public class TDArray 
{
 void show(int x[ ][ ])
 {
   for(int i = 0; i < x.length; i++)
   {
	 for(int j = 0; j < x[i].length; j++)
		System.out.print(x[i][j]+ " ");
	 System.out.println();
   }
 }
 int[ ][ ] sum(int[ ][ ] x, int[ ][ ] y)
 {
	int[ ][ ] z = new int[x.length][x[0].length];
	for(int i = 0; i < x.length; i++)
	     for(int j = 0; j < x[i].length; j++)
		     z[i][j] = x[i][j] + y[i][j];
     return z; // Returning 2D array.
 }
}
public class TDArrayfromMethod {
public static void main(String[ ] args) 
{
  int[ ][ ] x = {{1, 2}, {3, 4}};
  int[ ][ ] y = {{5, 6}, {7, 8}};
  int[ ][ ] z = new int[x.length][x[0].length];

// Create an object of class TDArray. 
   TDArray obj = new TDArray();
   System.out.println("Matrix x: ");
   obj.show(x);
   System.out.println("Matrix y: ");
   obj.show(y);
 
    z = obj.sum(x, y);
   System.out.println("Matrix z: ");
   obj.show(z);
 }
}
Output:
          Matrix x: 
          1 2 
          3 4 
         Matrix y: 
         5 6 
         7 8 
         Matrix z: 
         6 8 
         10 12 

In this program, we have created a class TDArray with two methods show() and sum(). The show() method is declared with a two dimensional array as its argument.

The purpose of this method is to print elements of array passed to it. The sum() method is declared with two 2D arrays as its arguments and made to return a two dimensional array.

The function of this method is to display the sum of two 2D arrays passed to it and return the sum array (two dimensional array) to calling method.

In the main() method of class TDArrayfromMethod, two dimensional arrays x and y are created with their values initialized and they are printed on the console.

After that the sum of arrays is calculated and assigned to another two-dimensional array z with statement z = obj.sum(x, y);. The sum array is then displayed on the console.

In this way, we can also think of passing and returning arrays of even arrays of higher dimensional also from a method.


4. Let’s create a program where we will find out the list of prime numbers between the given two numbers. In this example program, we will use Scanner class to get input from the keyboard. Concentrate on the following source code to understand better.

Program source code 4:

package arraysProgram;
public class Primes 
{
// Test and return true if a number n is prime.	
 static boolean prime(int n)
 {
// Initially, isPrime is set to true. It become false if n is not prime.	 
    boolean isPrime = true;
    for(int i = 2; i <= n-1; i++)
	 if(n % i == 0)
	  isPrime = false;
	 return isPrime;
 }  
 static void findPrime(int num1, int num2)
 {
   System.out.println("List of prime numbers between " +num1+ " and " +num2+ " :");	 
   for (int i = num1; i <= num2; i++) 
   {  
     if (prime(i)) // Calling prime() method directly.
     {  
         System.out.print(i+ " ");  
    }  
   }  
 }
}
import java.util.Scanner;
public class PrimeTest {
public static void main(String[] args) 
{
// Create an object of Scanner class to connect with keyboard.	
   Scanner sc = new Scanner(System.in);
   System.out.println("Enter your first number:");
   int num1 = sc.nextInt();
 
   System.out.println("Enter your second number:");
   int num2 = sc.nextInt();
   Primes.findPrime(num1, num2);
 }
}
Output:
          Enter your first number:
          10
          Enter your second number:
          30
          List of prime numbers between 10 and 30 :
          11 13 17 19 23 29 

In this program, we have generated prime number series between two given numbers. A prime number is a number that is divisible by 1 and itself but not divisible by any other number. For example, the prime numbers between 2 and 10 are 2, 3, 5, and 7.


Hope that this tutorial has elaborated on all the important points concerning how to return array in java from a method. I hope that you will have understood the concepts of returning an array from a method in java.
Thanks for reading!!!
Next ⇒ Arrays Class in Java⇐ Prev Next ⇒