Skip to main content
Engineering LibreTexts

16.4: Copying Arrays

  • Page ID
    15259
  • As explained in Section 8.2, array variables contain references to arrays. When you make an assignment to an array variable, it simply copies the reference. But it doesn’t copy the array itself! For example:

    double[] a = new double[3];
    double[] b = a;
    

    These statements create an array of three doubles and make two different variables refer to it, as shown in Figure 8.4.3.

    State diagram showing two variables that refer to the same array.
    Figure \(\PageIndex{1}\): State diagram showing two variables that refer to the same array.

    Any changes made through either variable will be seen by the other. For example, if we set a[0] = 17.0, and then display b[0], the result is 17.0. Because a and b are different names for the same thing, they are sometimes called aliases.

    If you actually want to copy the array, not just a reference, you have to create a new array and copy the elements from the old to the new, like this:

    double[] b = new double[3];
    for (int i = 0; i < 3; i++) {
        b[i] = a[i];
    }
    

    Another option is to use java.util.Arrays, which provides a method named copyOf that copies an array. You can invoke it like this:

    double[] b = Arrays.copyOf(a, 3);
    

    The second parameter is the number of elements you want to copy, so you can also use copyOf to copy just part of an array.

    • Was this article helpful?