Arrays.copyOf method

In this post under Java Collections, I will explain with example the purpose and how to use “Arrays” class public static method “copyOf”.

Arrays.copyOf method takes a source array, creates a destination array, and copies the elements present in source array to destination array.

Lets see an eample. Below is the main class

Main class

1  package core.collection;
2  
3  import java.math.BigDecimal;
4  import java.util.Arrays;
5  
6  public class ArraysCopyOfExample {
7      public static void main(String[] args) {
8          int[] intInputArray = new int[] {1, 2, 3};
9          int[] intOutputArray = Arrays.copyOf(intInputArray, 4);
10         System.out.println("intOutputArray: " + Arrays.toString(intOutputArray));
11 
12         intOutputArray = Arrays.copyOf(intInputArray, 3);
13         System.out.println("intOutputArray: " + Arrays.toString(intOutputArray));
14 
15         BigDecimal[] bigDecimalInputArray = new BigDecimal[] {BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TWO, BigDecimal.TEN};
16         BigDecimal[] bigDecimalOutputArray = Arrays.copyOf(bigDecimalInputArray, 5);
17         System.out.println("bigDecimalOutputArray: " + Arrays.toString(bigDecimalOutputArray));
18     }
19 }

In the above code, at line 8, I create an input array named “intInputArray”, containing elements of primitive int. I also populated it with values.

At line 9, I call “Arrays” class “copyOf” static method and pass the “intInputArray” as an argument. I also pass a number (in this case 4) as argument, which will tell the length of the destination array.

The result of this method call, is a new array of user specified length with values copied from “intInputArray”.

If the destination array length is more than the source array. The remaining positions in the array will be set to null for objects or primitive default for primitive arrays.

If the destination array length is smaller than source array. The number of elements copied from the source array is equal to destination array length. The remaining elements from the source array are
not coppied

In this way, we can copy elements of one array to another.

Below is the output

Output

intOutputArray: [1, 2, 3, 0]
bigDecimalOutputArray: [0, 1, 2, 10, null]

Leave a comment