Java Program to copy all elements of an array to another array


In this program, You will learn how to copy all elements of an array to another array in java.


List is: 1, 2, 12, 23, 24

Copy list is: 1, 2, 12, 23, 24

Example: How to copy all elements of an array to another array in java.

import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int i;
        int arr1[] = new int[5];
        int arr2[] = new int[5];
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter 5 numbers:");

        for (i = 0; i < 5; i++) {
            arr1[i] = sc.nextInt();
        }

        /* Copy start here */
        for (i = 0; i < 5; i++) {
            arr2[i] = arr1[i];
        }

        System.out.print("Array2 List:");
        for (i = 0; i < 5; i++) {
            System.out.print(" " + arr2[i]);
        }

    }
}

Output:

Enter 5 numbers:10 20 30 40 50
Array2 List: 10 20 30 40 50