Java System arraycopy() Method
Example
Copy three items from one array into another array:
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
String[] myCars = new String[3];
System.arraycopy(cars, 1, myCars, 0, 3);
for (String car : myCars) {
System.out.println(car);
}
}
}
Definition and Usage
The arraycopy() method copies items from one array (the source) into another array (the destination). You choose where to start in each array, and how many items to copy.
Both arrays must have the same type of items, and they must be big enough. Otherwise an exception is thrown.
Syntax
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Parameter Values
| Parameter | Description |
|---|---|
| src | Required. The array to copy from. |
| srcPos | Required. The index in the source array where the copying starts. |
| dest | Required. The array to copy to. |
| destPos | Required. The index in the destination array where the first copied item is placed. |
| length | Required. The number of items to copy. |
Technical Details
| Throws: | IndexOutOfBoundsException - if the copying goes outside one of the arrays.ArrayStoreException - if the types of the arrays do not match.NullPointerException - if src or dest is null. |
|---|
Related Pages
❮ System Methods