Java - Modifying Elements of an Array Parameter Inside a Method

Introduction

The values stored in the elements of an array parameter can always be changed inside a method.

The first element of the arrays changed after the method calls.

Demo

import java.util.Arrays;

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

    // Call methods passing the arrays
    tryElementChange(origNum);// w w  w.  j ava 2  s .  co  m
    tryElementChange(origNames);

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

  public static void tryElementChange(int[] num) {
    // If array has at least one element, store 1116 in
    // its first element
    if (num != null && num.length > 0) {
      num[0] = 2;
    }
  }

  public static void tryElementChange(String[] names) {
    // If array has at least one element, store "Twinkle" in
    // its first element
    if (names != null && names.length > 0) {
      names[0] = "book2s.com";
    }
  }
}

Result

You can change the elements of an array parameter inside a method, even if the array parameter is declared final.

Related Topic