How to return an array in java


As we know that arrays are very important for a programming language as they group the values of same data type in one variable so in Java array also play a positivo role. When we create functions or methods we usually pass variables as arguments. But what if we want to return a large amount of data having same data type at merienda from a function or method?

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 class arry {
    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.



Source link