Arrays and Methods

Arrays can be passed to and returned from methods, providing a powerful way to work with collections of data within a function scope.

Passing Arrays to Methods

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.

Example: Passing an Array as an Argument
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.

Example: Modifying an Array Inside a Method
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.

Returning Arrays from Methods

A method can also return an array. Typically, you create a new array within the method and return its reference.

Example: Returning an Array from a Method
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.

Key Points When Working with Arrays and Methods

  1. Pass by Reference: Arrays are passed by reference, so changes in methods affect the original array.
  2. Return Array References: When returning arrays, you return a reference to the array, not a copy. Ensure the array is not modified unexpectedly outside of its intended scope.
  3. Array Creation in Methods: It’s common to create arrays within methods, especially when the size or values need to be dynamically determined at runtime.

Combining Passing and Returning Arrays

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
    }
}

Summary

  • Passing Arrays: Arrays are passed by reference to methods, allowing modifications within the method to affect the original array.
  • Returning Arrays: A method can return an array, providing a flexible way to return multiple values.
  • Creating Arrays in Methods: Useful for dynamically generating arrays that are returned or passed between methods.