copying arrays Example
This program shows how arrays, or parts of them, can be copied to other arrays.The method System.arraycopy() has 5 parameters:
- source array
- source start index
- destination array
- destination start index
- number of elements to copy.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Copying Arrays Example
class CopyingArraysExample {
public static void main(String[] args) {
int[] ia = {5,-3,7};
int[] ib = new int[ia.length];
System.arraycopy(ia, 0, ib, 0, ia.length);
System.arraycopy(ib, 1, ia, 0, 2);
}
}
6-7 Two arrays are created of the same length.
The first is initialized with values. The second one is not initialized but will be given a default 0 value in each element.
9 All elements of ia are copied to ib.
The copying, in this case, starts from index 0 and copies to index 0. Then similar copies are done for index 1, and so on.
The number of copied elements is ia.length, in this case 3.
11 Two elements are copied from ib to ia.
Copying starts from index 1 of ib and is copied to the start destination index 0 of ia.
So ia now contains {-3, 7, 7}.
