In this post are described the methods used to copy one array values into another array. Do not forget that arrays are objects in Java ( Java Tutorial 6 – #4 Arrys ) which means that the array variable that manage the collection of values is a reference, a pointer, which contains the address of the first element of the array.
Based on this assumption, it is important to understand that the elements of an array are not copied like this:
//initial array
int[] oldArray = {1,2,3,4,5};
//new array
int[] newArray;
//shallow copy - copy reference values
newArray = oldArray;
//print a value using seconf reference
//prints value 3
System.out.println(newArray[2]);
There are few situations in which it is wanted a "copy" (shallow copy) like this, but most times it is a mistake. In the end, the initial array elements were not copied, but the first reference value oldArray was copied in the new reference, newArray. In terms of memory, the next figure is suggestive. In the end there will be a collection of values and only two references to manage that collection.

Array Shallow Copy in Java
Even if it seems a successful copy of values (displaying a value proves that) the problem is that any change in values through one of the two references will be visible through the second reference.
//modify a value using the first array reference
oldArray[0] = 100;
//prints the first value using the second referecene
System.out.println(newArray[0]); //it prints also 100
And if this situation is not what we wanted, it would be a situation difficult to manage, because it is a logical error that will not generate compiler or run-time errors.
What we saw is called a shallow copy because it occurs only at the reference level. What interests us most often is a copy of the content – deep copy.
In Java there are two possibilities to copy values from an array to another:
- an own implementation of an copying algorithm;
- use of API functions.
For the first approach, the copy means to:
- define a new vector;
- allocate space for the new array;
- copy values from the initial array:
//initial array
int[] oldArray = {1,2,3,4,5};
//define a new array + allocate space
int[] newArray = new int[oldArray.length];
//copy values
for(int i =0;i < oldArray.length;i++)
newArray[i] = oldArray[i];
The second solution is based on the use of arraycopy function from the System library:
System.arraycopy( source, sourceStart, destination, destStart, length );
- define a new array;
- allocate space for the new array;
- copy initial values of the array with arraycopy :
//initial array
int[] oldArray = {1,2,3,4,5};
//define a new array + allocate space
int[] newArray = new int[oldArray.length];
//copy values
System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
Other topics that are part of this Java 6 tutorial are accessible through Java 6 Tutorial – Contents.
Thank you, simple and straight forward explanation.