We can do that by returning an array where we want to use numerous values of the same data type without occupying the large memory space.
How do we return an array in Java?
In Java, we can return an array from a function. The following practical example, will showcase how to return an array practically in Java.
Code:
public static int[] rtnarray() {
int[] ary = {0,2,4,6,8,10,12,14,16,18,20};
return ary;
}
public static void main(String[] args) {
int[] get = rtnarray();
int q = 0;
while(q<get.length)
{
System.out.println("The value at index-number " + q + " is: " +get[q]);
q++;
}
}
}
In this code, we create a static function which will return an integer type array. Then in the main function, we create an integer type array variable and initialize it with the function that returns an integer array. Lastly, we use a while loop to display the elements of the array.
Output:
The output clearly shows that we can return an array with the help of a method and display the required result.
Here you go! You have learned to return an array in Java.
Conclusion
In java, an array can be returned with the help of a method or a function. For this purpose, the method return type must be the type of the array, and the variable that stores the array also has the same data type as the array. In this article, we talked about we have gone through the prose in detail through which we can return an array in Java.