Java program to Copy an Array

In this article, you will learn the Java program to copy an array. To copy an array we just use a for loop and copy the array element into another array.

Example#1. Copy the array to another array

package com.javacodepoint.array;

public class CopyArrayExample {

	public static void main(String[] args) {

		// Declare and Initialize an integer array
		int arr1[] = { 2, 4, 3, 8, 10, 0, 7, 15 };

		// Declare another array to copy with same size
		int arr2[] = new int[arr1.length];

		// Iterate first array and copy to second array
		for (int i = 0; i < arr1.length; i++) {
			arr2[i] = arr1[i];
		}

		// Print the copied array
		System.out.println("Copied array elements: ");
		for (int i = 0; i < arr2.length; i++) {
			System.out.print(arr2[i] + " ");
		}

	}

}

OUTPUT:

Copied array elements:
2 4 3 8 10 0 7 15

Example#2. Copy the array to another array using Scanner

In this example, we will take array element input from the users by using the java.lang.Scanner class. Let’s see the java code below:

package com.javacodepoint.array;

import java.util.Scanner;

public class CopyArrayExample2 {

	public static void main(String[] args) {

		// Creating scanner object for reading user inputs
		Scanner sc = new Scanner(System.in);

		// Read the size of the Array
		System.out.println("Enter the size of the Array: ");
		int n = sc.nextInt();

		// Declare the integer Array of given size
		int arr1[] = new int[n];

		// Reading the Array values
		System.out.println("Enter " + n + " element(s) of the Array: ");
		for (int i = 0; i < n; i++) {
			arr1[i] = sc.nextInt();
		}

		// Declare another array to copy with same size
		int arr2[] = new int[arr1.length];

		// Iterate first array and copy to second array
		for (int i = 0; i < arr1.length; i++) {
			arr2[i] = arr1[i];
		}

		// Print the copied array
		System.out.println("Copied array elements: ");
		for (int i = 0; i < arr2.length; i++) {
			System.out.print(arr2[i] + " ");
		}

	}

}

OUTPUT:

Enter the size of the Array:
5
Enter 5 element(s) of the Array:
2
6
3
9
7
Copied array elements:
2 6 3 9 7

See also: Java Program To Find the Sum of an Array.

Java logical programs list


Java Basic Programs

Java String Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *