Quick Reach
The Java copy array method
There is a method in the Java System class that allows copying one array to the other array. The method is called: arraycopy.
The example below shows you how to define and declare an array and then copying its elements to the other array by using the arraycopy method of the System class.
How to use the arraycopy method?
The syntax of Java arraycopy method is:
public static void arraycopy(
Object source_Array, int sourcePos,Object copty_to_array, int copty_to_array_pos, int length
)
Where
- source_Array tells which array to copy from.
- sourcePos tells the source array position to start from (index starts from 0).
- copty_to_array specifies which array to copy to.
- copt_to_array_pos specifies where to copy in the destination array.
- The length specifies the length of the destination array.
Example of using Java arraycoppy method
The following example copies array items of one array to the other by using the arraycopy method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class array_ex {
public static void main(String []args) {
int arrsrc[] = {10,20,30,40,50,60,70,80,90}; //Source array
int arrdest[] = new int[6]; //Destination array
System.arraycopy(arrsrc, 1, arrdest, 0, 6); //Copying array
//Displaying array
for (int i=0;i<arrdest.length;i++){
System.out.println(arrdest[i]);
}
}
}
|
Experience this online
The output will be:
20
30
40
50
60
70
You can see, the array elements of the destination array are displayed after copying from the source array (arrsrc).
Also see – Java array | Java String array
Leave A Comment?