Copying arrays
- Java course
- Beginner
- Lesson 57/116
- 4 min
Learn to copy with System.arraycopy.
Copying arrays
System.arraycopy copies a portion of one array into another. It takes five parameters:
int[] src = {1, 2, 3};
int[] dest = new int[3];
System.arraycopy(src, 0, dest, 0, 3);
// dest = {1, 2, 3}The parameters are: source array, source start index, destination array, destination start index, number of elements to copy. The destination must be large enough; otherwise an exception is thrown.
arraycopy parameters
System.arraycopy(src, srcPos, dest, destPos, length) — five parameters in order:
src: source arraysrcPos: source start indexdest: destination arraydestPos: destination start indexlength: number of elements to copy
For example, System.arraycopy(src, 1, dest, 0, 2) copies 2 elements starting from src's index 1 into dest's index 0. For partial copies, adjust srcPos and length.
Practice Copy an array and print
Write a Main class with a main method. Assign {1, 2, 3} to int[] src. Assign new int[3] to int[] dest. Copy with System.arraycopy(src, 0, dest, 0, 3). Print the destination's first element with System.out.println(dest[0]).
Sample solution
public class Main {
public static void main(String[] args) {
int[] src = {1, 2, 3};
int[] dest = new int[3];
System.arraycopy(src, 0, dest, 0, 3);
System.out.println(dest[0]);
}
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the arraycopy call
System.array____(src, 0, dest, 0, 3);
System.arraycopy(src, 0, dest, 0, 3);
Explanation: System.arraycopy copies with five parameters.
2 Match the arraycopy parameters
| Term | Meaning |
|---|---|
src |
Source |
dest |
Destination |
srcPos |
Source start |
length |
Element count |
3 System.arraycopy(src, 0, dest, 0, n) — what is n?
- The source array
- Number of elements to copy Correct answer
- The destination array
- The start index
Explanation: n is the number of elements to copy.