What is Java System.arraycopy() Method?

The java.lang.System.arraycopy() method copies a source array, at a specific beginning position, to a destination at a given index.
This method belongs to java.lang.System class. It copies the content of a subarray of a specified length from a given source array to another array called the destination array. The source array is referred to as src and the destination array as dest. The number of elements is given by the len argument.

Java System.arraycopy() method Declaration

The method declaration for java.lang.System.arraycopy() method in the java.lang class is as follows:

public static void arraycopy(Object src, int srcIndex, Object dest, int destIndex, int len)

Parameters

Following are the parameters of the arraycopy method:
  1. src: It is the source array from which elements will be copied.

  2. srcIndex: It is the starting index of the source array from which copying begins (0-based index).

  3. dest: It is the destination array where elements will be copied.

  4. destIndex: It is the starting index of the destination array where elements will be copied (0-based index).

  5. len: It is the number of elements that need to be copied from the source array to the destination array.

Functionality

The arraycopy method copies data from src, starting from srcIndex till srcIndex +(len - 1) elements, to the dest array at destIndex till destIndex + (len - 1).

Return Value

The arraycopy method is has a void return type which means it does not return anything.

Example


public class Example {

    public static void main(String[] args) {

        String[] src = { "Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        String[] dest = { "January", "February", "March", "April", "May", "June", "July", "August"};
  
        int srcIndex = 2;
        int destIndex = 3;
        int len = 2;
        
        //print number of elements that need to be copied 
        //from the source to the destination array  
        System.out.println("len : " + len);
        
        //print source index
        System.out.println("srcIndex : " + srcIndex);
  
        //print elements of the source array
        System.out.print("src : ");
        for (int i = 0; i < src.length; i++)
            System.out.print(src[i] + " ");
        System.out.println("");
  
        //print destination index
        System.out.println("destIndex : " + destIndex); 
        
        //print elements of the destination array
        System.out.print("dest : ");
        for (int i = 0; i < dest.length; i++)
            System.out.print(dest[i] + " ");
        System.out.println("");
                
        // Use of arraycopy() method
        System.arraycopy(src, srcIndex, dest, destIndex, len); 
        // this method copies the 'len' no of elements 
        // from the src array to the dest array using the srcIndex
        // and destIndex as reference points in both the arrays
        
                        
        // Print elements of destination after  
        System.out.print("final destination array : ");
        for (int i = 0; i < dest.length; i++)
            System.out.print(dest[i] + " ");
    }
}

Output

len : 2 srcIndex : 2 src : Monday Tuesday Wednesday Thursday Friday Saturday Sunday destIndex : 3 dest : January February March April May June July August final destination array : January February March Wednesday Thursday June July August

Example of changing parameters


// Example of changing parameters
         srcIndex = 4;
         destIndex = 5;
         len = 1;

Output

len : 1 srcIndex : 4 src : Monday Tuesday Wednesday Thursday Friday Saturday Sunday destIndex : 5 dest : January February March April May June July August final destination array : January February March April May Friday July August

Explanation

In the above code, we have defined two arrays src[] and dest[]. After that, we have defined the srcIndex and destIndex to define the reference positions for both arrays. In the first example, the System.arraycopy method copies the elements from the source array src[], starting at index 2 and ending at index 3 (because len = 2), to the destination array, starting from index 3. It then outputs the final destination array after copying the elements. In the second example, the System.arraycopy method copies 1 element (because len = 1) from the source array src[], starting at index 4, to the destination array, starting from index 5, and also outputs the final destination array after copying the elements.

Copying Arrays of Primitive Types

One of the most common use cases for System.arraycopy() is copying elements between arrays of primitive types like int, double, or char. Here's how it works:

Example: Copying an Array of Integers

public class PrimitiveArrayCopy {
    public static void main(String[] args) {
        int[] sourceArray = {1, 2, 3, 4, 5};
        int[] destinationArray = new int[5];

        // Copy elements from sourceArray to destinationArray
        System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);

        // Print the destination array
        for (int element : destinationArray) {
            System.out.print(element + " ");
        }
    }
}

Output: 1 2 3 4 5

Example: Copying an Array of Characters

public class CharArrayCopy {
    public static void main(String[] args) {
        char[] sourceArray = {'J', 'A', 'V', 'A'};
        char[] destinationArray = new char[4];

        // Copy elements from sourceArray to destinationArray
        System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);

        // Print the destination array
        System.out.println(new String(destinationArray));
    }
}

Output: JAVA

Exceptions Thrown by System.arraycopy()

The System.arraycopy() method can throw several exceptions. Understanding these exceptions is crucial for debugging and writing robust code:

  • ArrayIndexOutOfBoundsException: Thrown if the specified positions (source position or destination position) or the length of elements to copy exceed the bounds of the arrays.
  • NullPointerException: Thrown if either the source or destination array is null.
  • ArrayStoreException: Thrown if the source and destination arrays are not compatible types (e.g., copying between arrays of different reference types without a valid relationship).

Example of an Exception

public class ArrayCopyExceptionDemo {
    public static void main(String[] args) {
        int[] sourceArray = {1, 2, 3};
        int[] destinationArray = new int[2]; // Smaller size

        try {
            // Attempt to copy more elements than the destination array can hold
            System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Conclusion

By the end of this post, we hope you have got yourself familiarized with the java.lang.System.arraycopy method in Java. Keep practicing for a deeper command of the concept. Till then, keep growing and keep shining!