Java Program to copy all elements from one array to another array

In this program, the objective is to copy all the elements from one array to another array. To achieve this, we utilize a loop to iterate through each element of the first array. During each iteration, we store the corresponding element from the first array into the second array at the same position.

ARRAY 1  
1   2  3  4  5  
  
ARRAY 2  
1   2  3  4  5

Algorithm of a Java Program to copy all elements from one array to another array

STEP 1: Start the program.

STEP 2: Initialize the source array arr1[] with values: 1, 2, 3, 4, 5.

STEP 3: Create a destination array arr2[] of the same size as arr1[].

STEP 4: Copy the elements from arr1[] to arr2[].

STEP 5: Repeat steps 6 to 12 until the condition (i < arr1.length) is true.

STEP 6: Set arr2[i] equal to arr1[i].

STEP 7: Display the elements of arr1[].

STEP 8: Repeat steps 9 to 10 until the condition (i < arr1.length) is true.

STEP 9: Print the value of arr1[i].

STEP 10: Display the elements of arr2[].

STEP 11: Repeat steps 12 to 13 until the condition (i < arr2.length) is true.

STEP 12: Print the value of arr2[i].

STEP 13: End the program.

Java Program to copy all elements from one array to another array :

public class CopyArray {    
    public static void main(String[] args) {        
             //Initialize array     
        int [] arr1 = new int [] {1, 2, 3, 4, 5};     
         //Create another array arr2 with size of arr1    
        int arr2[] = new int[arr1.length];    
        //Copying all elements of one array into another    
        for (int i = 0; i < arr1.length; i++) {     
            arr2[i] = arr1[i];     
        }      
         //Displaying 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();    
            
        //Displaying 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:

Elements of original array
1 2 3 4 5
Elements of new array:
1 2 3 4 5

In conclusion, we have successfully designed and implemented a Java program to copy all elements from one array to another array. This program allows us to efficiently transfer data between arrays, ensuring that the elements are accurately replicated in the destination array. Follow tutorials.freshersnow.com to learn more.