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.

public class CopyingElements
{
  public static void main(String args[])
  {
    int x1[] = { 16, 26, 36, 46, 56, 66, 76 };
					// total elements at a time
    int x2[] = x1;
    System.out.println("1st element of x2: " + x2[0]);      // 16
                                                  // to copy a few elements

    int y1[] = { 15, 25, 35, 45, 55, 65, 75 };
    int y2[] = { 105, 205, 305, 405, 505, 605, 705, 805, 905 };
    System.arraycopy(y1, 1, y2, 2, 4);

    System.out.println("\n\ny2 elements after copying");
    for(int i = 0; i < y2.length; i++)
    {
      System.out.print(y2[i] + "\t");
    }
  }
}
Java Array Copying arraycopy method
Output screen of CopyingElements.java

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.

    Thanks

Leave a Comment

Your email address will not be published.