0

I tried to deep copy an array using arrays.clone() method.

import java.util.*;

public class Main
{
    public static void main(String[] args) {
        
        int[] arr = {1,2,3,4,5};
        m1(arr);
        System.out.println("arr inside main: " + Arrays.toString(arr));
    }
    
    private static void m1(int[] arr) {
        int[] narr = {5,6,7,8,9};
        arr = narr.clone();
        System.out.println("arr inside m1: " + Arrays.toString(arr));
    }
}

Output:

arr inside m1: [5, 6, 7, 8, 9]
arr inside main: [1, 2, 3, 4, 5]

As it seen the original array inside the m1() function is changed, and since arrays are passed by reference, I thought the original array in the main() function should also have changed.

But it is not. I think I am lacking some java knowledge.
Please put some light.

Abhishek Kumar
  • 820
  • 12
  • 16
  • You didn't changed `arr` you assign it something else. That's different – azro Aug 16 '20 at 15:44
  • If you assign new value in arr inside m1, it will be no change outside. Try to copy it element by element (in loop). It should help – Andrew Blagij Aug 16 '20 at 15:46
  • *"since arrays are passed by reference"* - oh but they are not, see the answers to the linked question. – Joni Aug 16 '20 at 15:50

0 Answers0