Topics Index

Exploring java.lang > System >
Siva Nookala - 20 Feb 2017
The java.lang.System.arraycopy() method copies elements from the specified source array, beginning at the specified position, to the specified position of the destination array:

public static void arraycopy(Object source, int sourcePosition,
Object destination, int destinationPosition, int numberOfElements)

source : Array from which elements are to be copied.
sourcePosition : Index that specifies the starting point in the range of elements to copy from the array. This value can be any valid array index.
destination : Specifies the destination array that will store the copy.
destinationPosition : Specifies the index in the destination array where the first copied element should be stored.
numberOfElements : Specifies the number of elements to copy from the array in the first argument.

The elements at positions sourcePosition to (sourcePosition + numberOfElements- 1)are copied into positions destinationPosition to (destinationPosition + numberOfElements – 1), respectively, of the destination array.

Exceptions thrown by arraycopy():
Exception Description
IndexOutOfBoundsException If copying causes access of data outside the range of array
ArrayStoreException If it is not possible to store an element of the source array in the destination array because of a type mismatch
NullPointerException If either source or destination is null

The following example shows the usage of arraycopy() method:
class ArrayCopyDemo1
    public static void main(String arg[])
        char array[] = {'J', 'a', 'v', 'a', 'i', 's', 'f', 'u', 'n'};
        char arrayCopy[] = new char[4];
        System.arraycopy(array, 0, arrayCopy, 0, 4);
        // Print characters as a string
        System.out.println(new String(arrayCopy));    



  • In the above program, change the last argument of arraycopy() from 4 to 3 or 2 and observe the change in the output.
We can pull different ranges out of the source array by changing the second argument.

For Example :

System.arraycopy(charArray, 4, charArrayCopy, 0, 4) copies characters at positions 4 through 7 from the array to the destination array, arrayCopy. Remember that the indices we pass to the arraycopy() must be valid. Otherwise, an Exception will be thrown.

class ArrayCopyDemo2
    public static void main(String arg[])
        int array[] = {5, 1, 4, 9, 6, 2};
        int arrayCopy[] = new int[4];
        System.arraycopy(array, 0, arrayCopy, 0, arrayCopy.length);  // LINE A
        for (int e : arrayCopy)
            System.out.print(e + " ");    

5 1 4 9


  • Make a change to the second argument of arraycopy() such that the destination array, arrayCopy here, will have elements {1, 4, 9, 6}.

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App