Skip to content

Passing array as argument

In Java, arrays are objects, and when they are passed as arguments to methods, their references are passed. This means that the method works directly on the original array and any modifications made inside the method will reflect in the array outside the method.


Key Points

  1. Reference Passing: Java always passes object references (including arrays) by value. This means the reference to the array is copied and passed to the method.
  2. Mutability: Changes made to the array inside the method affect the original array.
  3. Flexibility: Passing arrays allows methods to handle multiple values at once, making them efficient for batch processing.

Syntax

To pass an array as an argument:

  1. Define the array parameter in the method signature.
  2. Call the method by passing the array.

void methodName(dataType[] array) {

    // Method logic here

}


Example 1: Passing and Modifying an Array

public class Main {

    // Method to double the values of the array elements

    public static void doubleValues(int[] arr) {

        for (int i = 0; i < arr.length; i++) {

            arr[i] *= 2;

        }

    }

    public static void main(String[] args) {

        int[] numbers = {1, 2, 3, 4, 5};

        System.out.println(“Original Array:”);

        for (int num : numbers) {

            System.out.print(num + ” “);

        }

        // Pass the array to the method

        doubleValues(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


Example 2: Passing Array to Compute and Return a Result

public class Main {

    // Method to calculate the sum of array elements

    public static int calculateSum(int[] arr) {

        int sum = 0;

        for (int num : arr) {

            sum += num;

        }

        return sum;

    }

    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40};

        // Pass the array to the method

        int result = calculateSum(numbers);

        System.out.println(“Sum of Array Elements: ” + result);

    }

}

Output:

Sum of Array Elements: 100


Example 3: Passing a Multidimensional Array

public class Main {

    // Method to print a 2D array

    public static void print2DArray(int[][] matrix) {

        for (int i = 0; i < matrix.length; i++) {

            for (int j = 0; j < matrix[i].length; j++) {

                System.out.print(matrix[i][j] + ” “);

            }

            System.out.println();

        }

    }

    public static void main(String[] args) {

        int[][] matrix = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9}

        };

        // Pass the 2D array to the method

        System.out.println(“Matrix:”);

        print2DArray(matrix);

    }

}

Output:

Matrix:

1 2 3

4 5 6

7 8 9


Passing Array to main Method

The main method in Java accepts a String array as an argument. This allows passing command-line arguments to the program.

public class Main {

    public static void main(String[] args) {

        // args contains command-line arguments

        for (String arg : args) {

            System.out.println(arg);

        }

    }

}

Run the program with command-line arguments:

java Main Hello World

Output:

Hello

World


Example 4: Using Arrays in Helper Methods

Splitting array-related logic into helper methods improves code organization.

public class Main {

    // Method to find the maximum element in the array

    public static int findMax(int[] arr) {

        int max = arr[0];

        for (int num : arr) {

            if (num > max) {

                max = num;

            }

        }

        return max;

    }

    public static void main(String[] args) {

        int[] numbers = {10, 20, 5, 15};

        // Pass the array to find the maximum element

        int max = findMax(numbers);

        System.out.println(“Maximum Element: ” + max);

    }

}

Output:

Maximum Element: 20


Best Practices

  1. Immutability: If you don’t want the original array modified, create a copy of the array before passing it.

int[] copy = Arrays.copyOf(originalArray, originalArray.length);

  • Error Handling: Validate array size and null references before processing.

if (array == null || array.length == 0) {

    throw new IllegalArgumentException(“Invalid array”);

}


Conclusion

Passing arrays as arguments in Java is straightforward and enables efficient manipulation of multiple values. By understanding reference behavior and utilizing helper methods, you can process arrays effectively and write clean, maintainable code.