To return an array in Java, you can use the return
statement in a method. The return
statement causes the method to exit and provides a value back to the calling code.
Here is an example of how you can return an array in Java:
class Main { public static void main(String[] args) { int[] numbers = getNumbers(); for (int number : numbers) { System.out.println(number); } } public static int[] getNumbers() { return new int[] {1, 2, 3, 4, 5}; } }
In this example, the getNumbers
method returns an array of integers with the values 1
, 2
, 3
, 4
, and 5
. The returned array is then assigned to the numbers
variable in the main
method, and its values are printed to the console using a for-each
loop.
Note that the type of the array being returned must be specified in the method signature. In this case, the getNumbers
method returns an array of integers, so the method is declared as public static int[] getNumbers()
.