Passing arrays to methods

A method can have parameters of any types including arrays, strings, primitive types, and so on.

In the following example, the method processArray has a single parameter of the type int[]:

public static void processArray(int[] array) { /* do something */ }

In the body of the method, we can process the input array in any way.

A parameter of an array type looks like a primitive type parameter. But there is one important difference related to the fact that an array is a reference type.

When you pass a value of a primitive type to a method, a copy of the value is created. When you pass an array to a method, a copy of the reference is created, but the value is the same. It means that if you change the actual value (elements of an array) in the body of a method, you will see these changes outside the method.

The following method swaps the first and the last elements of its parameter (array).

public static void swapFirstAndLastElements(int[] nums) { // nums is an array
    if (nums.length < 1) {
        return; // it returns nothing, i.e. just exits the method

    int temp = nums[nums.length - 1]; // save the last element in a temporary local variable
    nums[nums.length - 1] = nums[0];  // now, the last element becomes the first
    nums[0] = temp;                   // now, the former first element becomes the last

Calling the method from the main method:

public static void main(String[] args) {

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

    System.out.println(Arrays.toString(numbers)); // before swapping

    swapFirstAndLastElements(numbers); // swapping

    System.out.println(Arrays.toString(numbers)); // after swapping

The output is:

[1, 2, 3, 4, 5]
[5, 2, 3, 4, 1] 

So, in the body of the main method, an array is visible as modified.

Leave a Reply

Your email address will not be published.