Copy Elements of Array

This program copies elements from one array to another.

Problem Statement

Write a Java program to copy elements of one array into another array.

Source Code

1 public class ArrayCopy {
2 public static void main(String[] args) {
3 int[] arr1 = {1, 2, 3, 4, 5};
4 int[] arr2 = new int[arr1.length];
5 for(int i=0; i<arr1.length; i++) {
6 arr2[i] = arr1[i];
7 }
8 System.out.print("Copied array: ");
9 for(int num : arr2) System.out.print(num + " ");
10 }
11 }

Program Output

Copied array: 1 2 3 4 5 

Explanation

A new array arr2 is created with the same length as arr1, and a for loop copies each element from arr1 into arr2, demonstrating an element-by-element array copy operation.

Quick Links to Explore