Java Code Example: Passing Array to Method

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.


Java Code Example

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 + " ");
        }
    }
}

Output

Original array:
1 2 3 4 5 
Modified array:
2 4 6 8 10 

Explanation

  1. Array Declaration & Initialization:
    • The array numbers is initialized with {1, 2, 3, 4, 5} in main().
  2. Printing Original Array:
    • A for-each loop prints the original values of the array.
  3. Passing Array to Method:
    • The modifyArray(int[] arr) method is called, and the reference of the array numbers is passed.
  4. Modifying the Array in Method:
    • The method loops through the array and multiplies each element by 2.
    • Since arrays are passed by reference, the original array gets modified.
  5. Printing Modified Array:
    • The modified array is printed, showing the updated values.

Key Takeaways

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.