Arrays can be passed to and returned from methods, providing a powerful way to work with collections of data within a function scope.
When you pass an array to a method, you’re passing a reference to the original array, not a copy. This means any modifications made to the array elements within the method affect the original array outside of the method.
public class ArrayExample {
public static void printArray(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
printArray(numbers); // Passes the array to the method
}
}
In this example, numbers
is passed to printArray()
, which iterates and prints each element. Because the array is passed by reference, changes to arr
inside printArray()
would affect numbers
.
public class ArrayExample {
public static void doubleElements(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] *= 2; // Doubles each element in the array
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
doubleElements(numbers);
printArray(numbers); // Output: 2, 4, 6, 8, 10
}
}
In this case, doubleElements()
modifies each element in numbers
, doubling its value.
A method can also return an array. Typically, you create a new array within the method and return its reference.
public class ArrayExample {
public static int[] createArray(int size) {
int[] newArray = new int[size];
for (int i = 0; i < size; i++) {
newArray[i] = i * 2; // Populate the array with multiples of 2
}
return newArray;
}
public static void main(String[] args) {
int[] result = createArray(5);
printArray(result); // Output: 0, 2, 4, 6, 8
}
}
In this example, createArray()
generates a new array with values based on the given size and returns it. This returned array can then be assigned to a variable and used in other parts of the program.
Sometimes, a method may take an array as input, process or modify it, and return either the same array or a new one.
public class ArrayExample {
public static int[] modifyAndReturnArray(int[] arr) {
int[] newArr = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
newArr[i] = arr[i] * 3; // Creates a new array with each element tripled
}
return newArr;
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
int[] modifiedNumbers = modifyAndReturnArray(numbers);
printArray(modifiedNumbers); // Output: 3, 6, 9
printArray(numbers); // Original array remains unchanged: 1, 2, 3
}
}