Multiple Ways to Copy Array in Java Effectively
Tags: tutorial, beginners, programming, java
Published: 2022-09-17 10:44:09

If you were given the task of copying the values from array `a` to array `b`, how would you do it? 

![Thinking man](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ah62ifne57vjl2ojbda.png)

...if you asked me when I was a beginner in java programming, I would have answered it as in _**Source code 1**_.

_**Source code 1:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = a;

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 1:**_
```
Array a: [1, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

With **_Source code 1_**, this task is certainly successful because I can perfectly copy the values from array `a` to array `b` with the proof can be seen in **_Output 1_**.

---

But what if something causes one of the values of array `a` to change? as in **_Source code 2_**, the first value in array `a` changes to something else.

_**Source code 2:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = a;

a[0] = 2;

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 2:**_
```
Array a: [2, 2, 3, 4, 5]
Array b: [2, 2, 3, 4, 5]
```

You can see the result in _**Output 2**_, where the value of array `b` will also change if there is a change in the value of array `a`. This method is not recommended for copying the values of one array to another _(unless you intentionally want to link the values of the two arrays)_.

---

Well then, but how do I copy instead of linking the values of array `a` to array `b`?
...One way is to individually copy value from array `a` to value from array `b` using loops, as can be seen in _**Source code 3**_.

_**Source code 3:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = new int[a.length];

for (int i = 0; i < a.length; i++) {
    b[i] = a[i];
}

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 3:**_
```
Array a: [1, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

You can see that using the code in **_Source code 3_**, I can make array `b` and array `a` have the same values as in **_Output 3_**.

Then, what if I update one of the values in array `a` as shown in **_Source code 4_**?

_**Source code 4:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = new int[a.length];

for (int i = 0; i < a.length; i++) {
    b[i] = a[i];
}

a[0] = 2;

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 4:**_
```
Array a: [2, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

As **_Output 4_** shows, array `b` will not change if there is an update to any of the values in array `a`. Congratulations, you have successfully copied the value of array `a` to array `b`!

**But we will not stop here**, because it turns out that Java has made it easy to copy array values to other arrays without having to use the iterative method.

There are 4 built-in methods you can use to copy arrays effectively in Java.
* `copyOf()`
* `copyOfRange()`
* `arraycopy()`
* `clone()`

And I will try to explain the four methods one by one.

---

#1. Using `copyOf()` method

`copyOf()` is the first method that can be used to copy the values of one array to another. _**Syntax 1**_ is the syntax for this method:

_**Syntax 1:**_
`public static int[] copyOf(int[] original, int newLength)`
* `original` is the source array.
* `newLength` is the length of the destination array.

**_Source code 5_** shows the implementation of this method.

_**Source code 5:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = Arrays.copyOf(a, a.length);

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 5:**_
```
Array a: [1, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

You can see the complexity of the code can be reduced compared to the "manual iteration" method I described earlier. And at **_Output 5_**, it can be seen that the results that appear are also in accordance with what we expected.

_**Source code 6**_ shows the code in which one of the array values `a` is modified, and the result can be seen in _**Output 6**_.

_**Source code 6:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = Arrays.copyOf(a, a.length);

a[0]++;

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 6:**_
```
Array a: [2, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

If you are interested in this method, and want to learn more about it, you can start by studying the documentation for the class that this method belongs to, namely `Arrays`. Here is a link to the `Arrays` class documentation: https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

---

#2. Using `copyOfRange()` method

`copyOfRange()` is an expansion of the previous method, where this method allows us to specify the range of array values that we will copy. And this method also comes from the same class, namely the `Arrays` class. The syntax of this method can be seen in _**Syntax 2**_.

_**Syntax 2:**_
`public static int[] copyOfRange(int[] original, int from, int to)`
* `original` is the source array.
* `from` is the start index value to be copied.
* `to` is the final index value to be copied.

**_Source code 7_** shows the implementation of this method.

_**Source code 7:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = Arrays.copyOfRange(a, 0, a.length);

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 7:**_
```
Array a: [1, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

**_Output 7_** shows that the results are in line with our expectations.

**_Source code 8_** is code where one of the values of array `a` is changed and _**Output 8**_ shows that the value of array `b` is not affected by changes in the value of array `a`.

_**Source code 8:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = Arrays.copyOfRange(a, 0, a.length);

a[0]++;

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 8:**_
```
Array a: [2, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

---

#3. Using `arraycopy()` method

`arraycopy()` is the third method for copying the values of one array to another. This method is also the foundation of the implementation of the `copyOf` and `copyOfRange` methods which if you look at the implementation code of these methods in the `Arrays` class, both methods use the `arraycopy()` method. The syntax of this method can be seen in **_Syntax 3_**.

_**Syntax 3:**_
`public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);`
* `src` is the source array
* `srcPos` is starting position in the source array.
* `dest` is the destination array.
* `destPos` is starting position in the destination data.
* `length` is the number of array elements to be copied.

**_Source code 9_** shows the implementation of this method.

_**Source code 9:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = new int[a.length];

System.arraycopy(a, 0, b, 0, a.length);

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 9:**_
```
Array a: [1, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

As in the code above, we must initialize array `b` first. We cannot directly assign array `b` with the `arraycopy()` method, because this method is `void`, so this method does not return any value. After that we will call the `arraycopy()` method, to copy the value of array `a` to array `b`.

The results of this code can be seen in **_Output 9_**, where it can be seen that the results are in line with our expectations.

**_Source code 10_** is the code where if one of the values of array `a` is updated, and **_Output 10_** is the result of the code where array b is not affected by the update of array `a`.

_**Source code 10:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = new int[a.length];

System.arraycopy(a, 0, b, 0, a.length);

a[0]++;

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 10:**_
```
Array a: [2, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

If you are interested in learning more about this method, you can start from the implementation class of this method, the `System` class. Here is the `System` class documentation: https://docs.oracle.com/javase/7/docs/api/java/lang/System.html

---

#4. Using `clone()` method

`clone()` method is my favorite method because it is very easy to use, and very simple. To be able to use this method, you only need to call the clone method of the object array to be copied.

The implementation of this method can be seen in **_Source code 11_**.

_**Source code 11:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = a.clone();

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 11:**_
```
Array a: [1, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

It can be seen from **_Output 11_**, the results of the code above are in line with our expectations.

And finally in **_Source code 12_**, it can be seen that there is an update of one of the values of array `a`. And in **_Output 12_**, it can be seen that the value of array `b` is not affected by changes that occur in array `a`.

_**Source code 12:**_
```java
int[] a = {1, 2, 3, 4, 5};
int[] b = a.clone();

a[0]++;

System.out.println("Array a: " + Arrays.toString(a));
System.out.println("Array b: " + Arrays.toString(b));
```
_**Output 12:**_
```
Array a: [2, 2, 3, 4, 5]
Array b: [1, 2, 3, 4, 5]
```

---

Those are some of my explanations of some of the built-in Java methods to copy one array to another more effectively. Note that the operations of the above methods, apart from integers, can also be performed on arrays with other datatypes such as double, boolean, etc.

---

Cover image:
https://i.picsum.photos/id/116/1920/720.jpg?hmac=efKDwhyr2wd5_mn1XOD1sjLYVawieQjikrwTWmsP5-U

Other image:
https://toppng.com/uploads/preview/thinking-man-11530959704arfgepmc9x.png