In Java, arrays can be passed to methods as arguments. When an array is passed to a method, the reference to the array is passed, not the actual values. This means that any changes made to the array inside the method will reflect in the original array.
Passing arrays to methods is useful for performing operations such as sorting, modifying elements, or performing calculations on array data.
Below is a Java program that demonstrates passing an array to a method. The method modifies the array by multiplying each element by 2.
public class ArrayPassingExample {
// Method to modify the array by multiplying each element by 2
public static void modifyArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] *= 2; // Multiply each element by 2
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5}; // Initialize array
System.out.println("Original array:");
for (int num : numbers) {
System.out.print(num + " ");
}
// Passing array to method
modifyArray(numbers);
System.out.println("\nModified array:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
Original array:
1 2 3 4 5
Modified array:
2 4 6 8 10
numbers
is initialized with {1, 2, 3, 4, 5}
in main()
.for-each
loop prints the original values of the array.modifyArray(int[] arr)
method is called, and the reference of the array numbers
is passed.2
.✅ Arrays are passed by reference – changes inside the method affect the original array.
✅ Efficient memory usage – since only the reference is passed, not the entire array.
✅ Useful for modifying data – sorting, filtering, or transforming array elements.