Java Array Copying arraycopy

Java Array Copying arraycopy

Java Array Copying arraycopy method

Summary: Java is simple to practice and one example is arraycopy() method. Illustrated in this tutorial "Java Array Copying arraycopy".

Java makes it easier to copy array elements into another either totally or a few. To copy, the System class includes arraycopy() method whose signature is given below.

public static void arraycopy(Object sourceArray, int sourcePosition, Object destinationArray, int destinationPosition, int elementsToCopy)

The first parameter is the name of the source array, the second parameter indicates the element position in the source array from which elements are to be copied, the third parameter is the name of the destination array, the fourth parameter the element position in the destination array and the last parameter, the fifth parameter is the number elements to copy.

The following program uses Java Array Copying arraycopy method.

Java Array Copying arraycopy method

Output screen of

int x2[] = x1;

All the elements of x1 array are assigned to x2 array. The x2 array contains the same elements. Now, x2[0] prints 16.

Note: Assignment of array object to array object is the simplest way to assign complete array elements; but encapsulation between x1 and x2 does not exist. If an element of x1 is changed, x2 is also gets changed or vice versa also.

System.arraycopy(y1, 1, y2, 2, 4);

In the above statement, y1 and y2 are source and destination array objects. 1 is the starting position in the y1 array from where elements are taken to copy, 2 is the position in the destination array to where elements are to be copied and 4 indicates the number of elements to copy. Here 4 elements of y2 are replaced with y1 elements. Following is the schematic representation of the above statement.

Array copying

Some questions for you from java.lang package.

2 thoughts on “Java Array Copying arraycopy

  1. Uday Kumar Goahika

    Hi Sir,
    Actually array size doesn’t change, but here when we copy some elements from array y1 to array y2, array y2 size is increasing. Could you please explain how it internally works.


Leave a Reply

Your email address will not be published. Required fields are marked *