Java Program to copy all elements of one Array into another Array
In this program, we need to copy all the elements from one array to another. This can be achieved by traversing the first array and storing the elements of the first array in the second array at the corresponding position.
Java Program to copy all elements of one Array into another Array
Create a Java file with the name of Main.java and paste the given code in your Java file.
public class Main {
public static void main(String[] args) {
//Initialize array
int [] array1 = new int [] {1, 2, 3, 4, 5};
//Create another array array2 with size of array1
int array2[] = new int[array1.length];
//Copying all elements of one array into another
for (int i = 0; i < array1.length; i++) {
array2[i] = array1[i];
}
//Displaying elements of array array1
System.out.println("Elements of original array: ");
for (int i = 0; i < array1.length; i++) {
System.out.print(array1[i] + " ");
}
System.out.println();
//Displaying elements of array array2
System.out.println("Elements of new array: ");
for (int i = 0; i < array2.length; i++) {
System.out.print(array2[i] + " ");
}
}
}
Output:
That’s all in this post, If your code does not work or you’ve faced any problem then comment down your problem.