Java - Array Element Copy

Introduction

You can copy array elements from one array to another in two ways:

  • Using a loop
  • Using the static arraycopy()method of the java.lang.System class

The signature of the arraycopy() method is as follows:

public static void arraycopy(Object sourceArray, 
                             int sourceStartPosition,
                             Object destinationArray,
                             int destinationStartPosition,
                             int lengthToBeCopied)
Parameter Meaning
sourceArray reference to the source array.
sourceStartPositionstarting index in the source array from where the copying of elements will start.
destinationArray reference to the destination array.
destinationStartPosition start index in the destination array from where new elements from source array will be copied.
lengthToBeCopied number of elements to be copied from the source array to the destination array.

The following code demonstrates how to copy an array using a for loop and the System.arraycopy() method.

Demo

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    // Have an array with 5 elements
    int[] data = { 1, 2, 3, 4, 5 };

    // Expand the data array to 7 elements
    int[] eData = expandArray(data, 7);

    // Truncate the data array to 3 elements
    int[] tData = expandArray(data, 3);

    System.out.println("Using for-loop...");
    System.out.println("Original Array: " + Arrays.toString(data));
    System.out.println("Expanded Array: " + Arrays.toString(eData));
    System.out.println("Truncated Array: " + Arrays.toString(tData));

    // Copy data array to new arrays
    eData = new int[9];
    tData = new int[2];
    System.arraycopy(data, 0, eData, 0, 5);
    System.arraycopy(data, 0, tData, 0, 2);

    System.out.println("Using System.arraycopy() method...");
    System.out.println("Original Array: " + Arrays.toString(data));
    System.out.println("Expanded Array: " + Arrays.toString(eData));
    System.out.println("Truncated Array: " + Arrays.toString(tData));
  }// w w w .j  a v a  2s  .c om

  // Uses a for-loop to copy an array
  public static int[] expandArray(int[] oldArray, int newLength) {
    int originalLength = oldArray.length;
    int[] newArray = new int[newLength];
    int elementsToCopy = 0;

    if (originalLength > newLength) {
      elementsToCopy = newLength;
    } else {
      elementsToCopy = originalLength;
    }

    for (int i = 0; i < elementsToCopy; i++) {
      newArray[i] = oldArray[i];
    }
    return newArray;
  }
}

Result