An “Array” is a data structure that stores a fixed amount of data(homogeneous elements). A unique index number is allocated to each element residing in the array to make them accessible. The operations like retrieval of a specific element are done using the allocated index numbers. The index numbers of an Array start from “0” and it is a static data structure, which means you can’t grow or shrink its size at run time.
This guide explains the procedure to return an array in Java.
How to Return an Array in Java?
The returning of an array means the procedure to access the content of a specific array residing in some function or method. The returning of an Array is specifically performed by the utilization of a “return” keyword. Before diving into practical examples about returning an array, there are some key points that must be considered, which are mentioned below:
- The “return type” of the method that returns an array should be the same as the data type of the Array. If the user provides an array and method having a different data type, then the execution process will be stopped, and the “Type Mismatch” error will occur. For instance, the method and the targeted array that is going to be returned both have the same data type of “int”:
int[] javabeatMethod() {
int[] arr={17,18,19,20,21};
}
- The “access modifier” should be used according to the task requirements as they specify the scope of a field, method, or class. The common access modifiers in Java are “public”, “static”, “private” and “protected”. For instance, the method named “javabeatMethod()” is defined as having the “public” and “static” as an access modifier:
public static String[] javabeatMethod() {
//method body
}
Let’s dive into the implementation of returning an array in Java.
Example 1: Return a Basic Array in Java
The “return” keyword is basically used to return an array or variable from the function or method depending upon scenarios. Moreover, the “for” loop is mostly used to iterate over the array and select or perform specific tasks over the array elements. For instance, an array is returned from the custom function, and its elements or contents are then displayed over the console, as shown below:
public class returnArray {
public static void main(String args[])
{
int arrDisplay[] = returnArr();
for (int j = 0; j < arrDisplay.length; j++)
{
System.out.print("\nArray element residing on index '" + j + "' is: " + arrDisplay[j]
);
}
}
public static int[] returnArr()
{
int[] provArray={72,34,77,39};
return provArray;
}
}
In the above code block:
- First, the class named “returnArray” holding the “main()” method is created. Inside the main() method, a random “int” type array “arrDisplay” is declared that stores the result of a “returnArr()” function.
- Next, the “for” loop is utilized that iterates till the length of an “arrDisplay” array and displays each array element on the console.
- After that, exit from the “main()” method and define a custom “returnArr()” function that has the type of “int”. In the function, declare and initialize the “provArray” named array having the data type of “int”.
- Finally, return the created “provArray” array using the “return” keyword.
Output for the above code block shows that the array is returned and its data is also displayed on the console:
Example 2: Return an Array of Objects in Java
In this case, the same approach discussed in the above example is going to be used to return and display the returned array objects data, as shown below:
class Games {
String gameName;
String officers;
public Games(String n, String m)
{
this.gameName = n;
this.officers = m;
}
}
public class returnArray {
public static void main(String[] args){
Games[] dispArray = demoArr();
for (int i = 0; i < dispArray.length; i++)
{
System.out.print("The '" + dispArray[i].gameName + "' game is created by '" + dispArray[i].officers + "'\n");
}
}
public static Games[] demoArr()
{
Games[] provArr = new Games[4];
provArr[0] = new Games("J Allard", "X-box");
provArr[1] = new Games("David Braben", "Elite");
provArr[2] = new Games("Jordan Mechner", "Prince of Persia");
provArr[3] = new Games("Steve Polge", "Epic Games");
return provArr;
}
}
The above code works like this:
- First, the class named “Games” is created that contains two String type variables “gameName” and “officers”. These variables are assigned with the parametric values provided using the class constructor.
- Next, another class named “returnArray” containing “main()” driver methods is defined. In it, a new array “dispArray” is created and it stores the result of the “demoArr()” function.
- The “for” loop is then utilized to display the content assigned to the “dispArray” array on the console.
- After that, define a “demoArr()” function which contains a new Array type instance of the “Games” class named “provArr”.
- Finally, multiple elements are inserted in the “provArr” array using the “Games” class constructor. Once completed, the generated “provArr” array is returned using the “return” keyword.
The output shows that array objects are now retrieved and displayed on the console:
Example 3: Return a Two-Dimensional Array in Java
A “two-dimensional” array is a nested array in which data is stored as the Arrays of Arrays. The working of a two-dimensional array is the same as one-dimensional, only at the time of declaration instead of single square brackets, two square brackets are utilized. Moreover, a single row is placed in the array at the time of initialization instead of a single row element. Take a look at the code block below to implement and return a two-dimensional array in Java:
public class returnArray {
public static void main(String[] args){
int[][] demoArr = returner();
for (int i = 0; i < demoArr.length; i++) {
for (int j = 0; j < demoArr[0].length; j++)
{
System.out.print(demoArr[i][j] + " ");
}
System.out.println();
}
}
public static int[][] returner()
{
int[][] provArray = { { 91, 82, 73 }, { 64, 55, 46 }, { 37, 28, 19 } };
return provArray;
}
}
The explanation of the above code snippet is as follows:
- First, create a class “returnArray” that contains the “main()” method. Inside this method, create a two-dimensional array “demoArr” that stores the result returned from a “returner()” function.
- Next, utilize two “for” loops to iterate over the array on both dimensions and print the array elements over the console.
- Then, create a two-dimensional array by utilizing two square brackets “[ ]” next to the data type declaration place.
- After that, assign the values to the array and return that array using the “return” keyword.
The generated output confirms that the two-dimensional array has been returned and displayed on the console:
Example 4: Return a Three-dimensional Array in Java
In this example, the three-dimensional array is created and returned in Java. Its implementation is similar to a two-dimensional array but instead of two square brackets at declaration time, three square brackets are inserted. Moreover, at initializing two rows are inserted instead of a single row, as shown in the below code snippet:
public class returnArray {
public static void main(String[] args){
int[][][] demoArr = returner();
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
for (int z = 0; z < 2; z++) {
System.out.print(demoArr[x][y][z] + " ");
}
System.out.println();
}
System.out.println();
}
}
public static int[][][] returner()
{
int[][][] provArray = { { { 99, 88 }, { 77, 66 } },{ { 55, 44 }, { 33, 22 } } };
return provArray;
}
}
The above code works like this:
- First, declare a three-dimensional array named “provArr” and initialize it with the output or value returned by the “retuner()” function.
- Next, utilize three loops to traverse over the three-dimensional array, this loop selects and displays each element residing in the array.
- After that, define a “returner()” function and create a three-dimensional array named “provArray”.
- In the end, the “provArray” gets returned by the containing function using the “return” keyword.
Let’s execute the above code in a Visual Studio terminal or Command Prompt by running the below-mentioned command:
javac <fileName.java>
java <fileName.java>
As the file name in our case is “returnArray.java”, so the command modifies like this:
javac returnArray.java
java returnArray.java // Or java returnArray
The generated output for the above code shows that a three-dimensional array has been returned:
That’s all about returning an array in Java.
Conclusion
Use the “return” keyword before the array name to return a single or multi-dimensional array in Java. The return of an array enhances the reusability and allows users to divide the code into multiple functions. The result of these functions can be obtained by invoking the corresponding function. This article has explained the return of an array in Java.