In this tutorial you will learn about the Java Program to copy all elements of one array into another array and its application with practical example.
Java Program to copy all elements of one array into another array
In this tutorial, we will learn to create a Java program that will copy all elements of one array into another array using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java programming.
- Arithmetic operations in Java Programming.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
STEP 1: START STEP 2: INITIALIZE arr1[] ={1, 2, 3, 4, 5} STEP 3: CREATE arr2[] of size arr1[]. STEP 4: COPY elements of arr1[] to arr2[] STEP 5: REPEAT STEP 6 UNTIL (i<arr1.length) STEP 6: arr2[i] =arr1[i] STEP 7: DISPLAY elements of arr1[]. STEP 8: REPEAT STEP 9 UNTIL (i<arr1.length) STEP 9: PRINT arr1[i] STEP 10: DISPLAY elements of arr2[]. STEP 11: REPEAT STEP 12 UNTIL (i<arr2.length) STEP 12: PRINT arr2[i]. STEP 13: END |
Copy all array elements to another array.
In this program, First, we will first declare the size of the array and its elements for the prorgam. Then we will find the length of array 1 using the length function for the second array. After that we will copy the elements of the array one to array two. At last, we will print the first and the second array to the user.
With the help of this program, we can copy all elements of one array into another array.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class CpyArry { public static void main(String[] args) { //Declaring the required array for the program. int [] arr1 = new int [] {1, 2, 3, 4, 5}; //Finding the size of array 1 //Create another array arr2 with size of arr1 int arr2[] = new int[arr1.length]; //Copying all elements of one array 1 into another array for (int i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; } //Printing elements of array arr1 System.out.println("Elements of original array: "); for (int i = 0; i < arr1.length; i++) { System.out.print(arr1[i] + " "); } System.out.println(); //Printing elements of array arr2 System.out.println("Elements of new array: "); for (int i = 0; i < arr2.length; i++) { System.out.print(arr2[i] + " "); } } } |
Output:-
In the above program, we have first initialized the required variable.
- arr1[] = it will hold the integer value.
- arr2[] = it will hold the integer value.
- i = it will hold the integer value.
Finding the size of the array one using the length function.
Copying the elements of the array one to the second array.
Printing array 1 to the user.
Printing array 2 to the user.