Close

Java - System.arraycopy() Examples

Java Java API 


Class:

java.lang.System

java.lang.Objectjava.lang.Objectjava.lang.Systemjava.lang.SystemLogicBig

Method:

public static void arraycopy(Object src,
                             int srcPos,
                             Object dest,
                             int destPos,
                             int length)

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

Parameters:
src - the source array.
srcPos - starting position in the source array.
dest - the destination array.
destPos - starting position in the destination data.
length - the number of array elements to be copied.


Examples


package com.logicbig.example.system;

import java.util.Arrays;

public class ArraycopyExample {

public static void main(String... args) {
String[] strArray = {"one", "two", "three", "four", "five", "six"};

String[] otherStrArray = new String[4];
otherStrArray[0] = "otherOne";

System.arraycopy(strArray, 2, otherStrArray, 1, 2);

System.out.printf("src: %s%n", Arrays.toString(strArray));
System.out.printf("dest: %s%n", Arrays.toString(otherStrArray));
}
}

Output

src: [one, two, three, four, five, six]
dest: [otherOne, three, four, null]




Wrong value of srcPos or destPos or length may cause ArrayIndexOutOfBoundsException

package com.logicbig.example.system;

import java.util.Arrays;

public class ArraycopyExample2 {

public static void main(String... args) {
String[] strArray = {"one", "two", "three", "four", "five", "six"};

String[] otherStrArray = new String[4];
otherStrArray[0] = "otherOne";

System.arraycopy(strArray, 5, otherStrArray, 1, 2);

System.out.printf("src: %s%n", Arrays.toString(strArray));
System.out.printf("dest: %s%n", Arrays.toString(otherStrArray));
}
}

Output

Caused by: java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at com.logicbig.example.system.ArraycopyExample2.main(ArraycopyExample2.java:20)
... 6 more




The data types of src and dest should be compatible otherwise ArrayStoreException will be thrown.

package com.logicbig.example.system;

import java.util.Arrays;

public class ArraycopyExample3 {

public static void main(String... args) {
String[] strArray = {"one", "two", "three", "four", "five", "six"};

int[] otherIntArray = new int[4];
otherIntArray[0] = 100;

System.arraycopy(strArray, 2, otherIntArray, 1, 2);

System.out.printf("src: %s%n", Arrays.toString(strArray));
System.out.printf("dest: %s%n", Arrays.toString(otherIntArray));
}
}

Output

Caused by: java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at com.logicbig.example.system.ArraycopyExample3.main(ArraycopyExample3.java:20)
... 6 more




See Also