Google News
logo
Java Program to Copy all Elements of one Array into Another Array
In the following example of Java program that copies all the elements of one array into another array :
Program :
import java.util.Arrays;

public class CopyArray {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int[] arr2 = new int[arr1.length];
        for(int i = 0; i < arr1.length; i++) {
            arr2[i] = arr1[i];
        }
        System.out.println("Array 1: " + Arrays.toString(arr1));
        System.out.println("Array 2: " + Arrays.toString(arr2));
    }
}
Output :
Array 1: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Array 2: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In this program, we have two integer arrays arr1 and arr2. We first initialize arr1 with some elements. We then initialize arr2 with the same size as arr1 using new int[arr1.length].

We then loop through arr1 using a for loop and copy each element to arr2 using arr2[i] = arr1[i]. Finally, we print both arrays using Arrays.toString() method.