In Java, arrays are objects, and they can be passed to methods just like any other object. Understanding how to pass and return arrays is essential for managing data in your programs.
Passing an Array to a Method
When you pass an array to a method, you’re actually passing a reference to the array, not the array itself. This means changes made to the array inside the method affect the original array outside the method.
Example: Passing an Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class ArrayExample { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; // Pass array to the method modifyArray(numbers); // Print the modified array for (int num : numbers) { System.out.print(num + " "); } } public static void modifyArray(int[] arr) { // Modify the array inside the method arr[0] = 10; } } |
Output
1 |
10 2 3 4 5 |
As shown, the first element of the array was modified inside the modifyArray()
method.
Returning an Array from a Method
You can return an array from a method just like returning any other object. The method will return a reference to the array, not a copy, allowing you to work with the array in the calling code.
Example: Returning an Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class ArrayExample { public static void main(String[] args) { // Call method to get the array int[] newArray = getArray(); // Print the returned array for (int num : newArray) { System.out.print(num + " "); } } public static int[] getArray() { // Return an array from the method return new int[]{1, 2, 3, 4, 5}; } } |
Output
1 |
1 2 3 4 5 |
The method getArray()
returns a new array, and we can use it in the main()
method.