1

After I replace the index 0 of an array in the function, the value of arrayCharacter is also changed. The result is

[A, B, C] [ko, B, C] [ko, B, C]

I don't understand why the result is not:

[A, B, C] [A, B, C] [A, B, C]

This is my code:

public static void main(String[] args) {
        String[] arrayCharacter = new String[]{"A", "B", "C"};
        for (int i = 0; i < 3; i++) {
            proses(arrayCharacter);
        }
    }

    public static void proses(String[] arrayCharacter) {
        String[] characterTemp = arrayCharacter;
        System.out.println(Arrays.toString(arrayCharacter));
        characterTemp[0] = "ko";
    }
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Jhohannes Purba
  • 576
  • 1
  • 5
  • 16
  • 2
    See: [Are arrays passed by value or passed by reference in Java?](http://stackoverflow.com/questions/12757841/are-arrays-passed-by-value-or-passed-by-reference-in-java). – agold Oct 07 '15 at 09:13

1 Answers1

2

The issue is that in this line: String[] characterTemp = arrayCharacter; you are not copying the array, but rather you have characterTemp and arrayCharacter pointing at the same memory location. Thus, any changes done to one will be reflected to the other.

The solution is to copy the content of the source array. System.arrayCopy does that for you:

public static void proses(String[] arrayCharacter) {
        String[] characterTemp = new String[arrayCharacter.length];
        System.arrayCopy(arrayCharacter, 0, characterTemp, 0, characterTemp.length); //This will create a separate copy of the array.
        System.out.println(Arrays.toString(arrayCharacter));
        characterTemp[0] = "ko";
    }
npinti
  • 51,780
  • 5
  • 72
  • 96