How do you use “return” to return an array in Java?

In Java, you can use the return statement to return an array. Here is an example of using return to return an array:

public class ReturnArrayExample {

    public static void main(String[] args) {
        int[] numbers = getNumbers();
        
        for (int number : numbers) {
            System.out.println(number);
        }
    }

    public static int[] getNumbers() {
        int[] numbers = {1, 2, 3, 4, 5};
        return numbers;
    }
}

In the given example, the getNumbers() method returns an integer array containing numbers from 1 to 5. In the main method, the getNumbers() method is called and the returned array is assigned to the numbers variable. Then, a loop is used to iterate through the array and print out the value of each element.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds