Java - What is the output: Array Parameter Reference?


What is the output of the following code?

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] origNum = { 1, 2, 3 };
    System.out.println("Before method call:" + Arrays.toString(origNum));

    // Pass the array to the method

    System.out.println("After method call:" + Arrays.toString(origNum));

  public static void tryArrayChange(int[] num) {
    System.out.println("Inside method-1:" + Arrays.toString(num));
    // Create and store a new int array in num
    num = new int[] { 10, 20 };

    System.out.println("Inside method-2:" + Arrays.toString(num));

Click to view the answer

Before method call:[1, 2, 3]
Inside method-1:[1, 2, 3]
Inside method-2:[10, 20]
After method call:[1, 2, 3]


Because an array is an object, a copy of its reference is passed to a method.

If the method changes the array parameter, the actual parameter is not affected.

The main() method passes array to the tryArrayChange() method, which in turn assigns a different array reference to the parameter.

The output shows that the array in the main() method remains unaffected.

If you do not want your method to change the array reference inside the method body, you must declare the method parameter as final.

public static void tryArrayChange(final int[] num) {
   // An error. num is final and cannot be changed
   num = new int[]{10, 20};

Related Topic