In this java program tutorial, we will write a program to copy the array in java. Before that, you may go through the following topic in java.
We will look at two programs:
- Using loop
- Using System.arraycopy()
Explanation: In this program, we will copy the elements of one array to another and display the copied array. We will iterate the array using one of the lops in java and copy each element at every iteration.
Array 1
1 2 3 4
Copied Array
1 2 3 4
Deep Copy Array Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class Main { public static void main(String[] args) { int[] arr1 = new int[] { 10, 20, 30, 40, 50 }; int arr2[] = new int[arr1.length]; for (int i = 0; i < arr1.length; i++) arr2[i] = arr1[i]; System.out.print("Original Array: "); for (int i = 0; i < arr1.length; i++) { System.out.print(arr1[i] + " "); } System.out.print("\nCopied Array: "); for (int i = 0; i < arr2.length; i++) { System.out.print(arr2[i] + " "); } } } |
Output:
Original Array: 10 20 30 40 50
Copied Array: 10 20 30 40 50
Copy Array to another array in java using System.arraycopy()
Syntax of the arraycopy() method:
System.arraycopy(Object src, int srcPos, Object dest, int destPos,int length);
- src: Source of copying array.
- srcPos: Starting position of the source array.
- dest: Destination, where the array is to copied.
- destPos: Position of the destination array.
- length: Number of elements to be copied.
Program source:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr1 = new int[] { 10, 20, 30, 40, 50 }; int arr2[] = new int[arr1.length]; System.arraycopy(arr1, 0, arr2, 0, arr1.length); System.out.println("Original Array = " + Arrays.toString(arr1)); System.out.println("Copied Array = " + Arrays.toString(arr2)); } } |
Output: It will produce the same output as the above program.