-2

While passing an array to a function in java and then assigning it to a new array, I am getting the same old array.

public static void main(String[] args) {
        int[] arr1 = { 1, 2, 3, };
        changes(arr1);
        for (int val : arr1) {
            System.out.println(val);
        }
    }

private static void changes(int[] arr1) {
    int[] arr2 = { 7, 8, 9 };
    arr1 = arr2;
}

Why is it so when passing array deals with passing the reference to that array?

Mehul Jain
  • 51
  • 1
  • 1
  • 8

1 Answers1

0

Because you are modifying the reference to arr1 locally (you can't modify the caller's reference). Change

arr1 = arr2;

to

System.arraycopy(arr2, 0, arr1, 0, arr2.length);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249