Explanation
This Java program demonstrates how to copy elements from one array to another. In Java, arrays are objects. If you simply assign one array variable to another (e.g., arr2 = arr1), you are only copying the reference (memory address), meaning both variables would point to the same data. This program shows the correct way to perform a "manual copy" so that two distinct arrays exist in memory.
The logic follows these steps:
- Initialization: An integer array named
arr1is created and populated with five values: 1, 2, 3, 4, and 5. - Displaying Original: The program iterates through
arr1using aforloop to print its contents to the console. - Memory Allocation: A second array,
arr2, is declared. It is initialized using thenewkeyword with a size equal toarr1.length. This ensuresarr2has enough space to hold all elements from the first array. - The Copying Process: A
forloop runs from index 0 to the end of the array. In each iteration, the value atarr1[i]is assigned toarr2[i]. - Verification: Finally, the program iterates through
arr2and prints its contents to verify that the values were successfully transferred.