In this tutorial, we will write a java program to copy all the elements of an array to another array. This can be easily done by using any loop such as for, while or do-while loop. We just need to run a loop from 0 to the array length (size of an array) and at every iteration, read the element of the given array and write the same value in another array.
For example:
array1 is {3, 5, 7, 9}
array2[] is {}
Then after copying all the elements of array1[] to array2[]
the elements in array2[] will be = {3, 5, 7, 9}
Steps to copy all elements from one array to another array
- Initialize the first array.
- Create another array with the same size as of the first array
- Run a loop from 0 till the length of first array
- Read the element of first array
- Copy the element to the second array
- Repeat the step 3 until the complete array is traversed
- Run a loop from 0 to the length of any array
- Read and print the elements of second array
- Repeat the step 5 until the second array is completely traversed.
- End of Program.
Java Program to copy all elements of one array into another array
public class JavaExample {
public static void main(String[] args) {
//Initializing an array
int [] firstArray = new int [] {3, 5, 7, 9, 11};
/* Creating another array secondArray with same size
* of first array using firstArray.length as it returns
* the size of array firstArray.
*/
int secondArray[] = new int[firstArray.length];
//Displaying elements of first array
System.out.println("Elements of First array: ");
for (int i = 0; i < firstArray.length; i++) {
System.out.print(firstArray[i] + " ");
}
//Copying all elements of firstArray to secondArray
for (int i = 0; i < firstArray.length; i++) {
secondArray[i] = firstArray[i];
}
//Displaying elements of secondArray
System.out.println();
System.out.println("Elements of Copied array: ");
for (int i = 0; i < secondArray.length; i++) {
System.out.print(secondArray[i] + " ");
}
}
}
Output:
Elements of First array: 3 5 7 9 11 Elements of Copied array: 3 5 7 9 11
Leave a Reply