How to copy Arrays in Java with Examples

In this post we will learn how to copy arrays in java. Copying arrays simply means copying one array elements into another array. There are two main ways to do this first by using loops and second by using methods.

How to copy arrays in java, java program to copy one array to another array


So first we will learn how to copy array using loop's. In this example I am going to use  a simple for loop. But here, you can also make a use of another loops it's totally depend on you.



  Java Program to copy elements of one array into another array using for loop :



public class CopyingArray {

	public static void main(String[] args) {
		
		int arr1[] = {10,20,30,40,50};
		//creating arr2[] of size arr1[]
		int arr2[] = new int[arr1.length];
		
		
		for(int i=0;i<arr1.length;i++) {
		//assigning values of arr1 to arr2
			arr2[i]=arr1[i];
		}
		//printing elements of arr1
		System.out.print("Elements in arr1[] are: ");
		for(int i=0;i<arr1.length;i++) {
			System.out.print(arr1[i]+" ");
		}
		
		//for next line
		System.out.println();
		
		//printing elements of arr2
		System.out.print("Elements in arr2[] are: ");
		for(int i=0;i<arr2.length;i++) {
			System.out.print(arr2[i]+" ");
		}
	}	

}


 
 Output of the above program is : 
Elements in arr1[] are : 10 20 30 40 50
Elements in arr2[] are : 10 20 30 40 50



Another way to copy array elements is by using methods. In Java there are multiple methods to copy elements of one array into another array like copyOf(), clone() etc. In below example I have used only copyOf() method.


  Java Program to copy elements of one array into another array using copyOf() method : 


import java.util.Arrays;

public class CopyingArray {

	public static void main(String[] args) {
		
		int arr1[] = {10,20,30,40,50};
		//copy arr1 elements into arr2
		int arr2[] = Arrays.copyOf(arr1, 5);
		
		
		//printing elements of arr1
		System.out.print("Elements in arr1[] are: ");
		for(int i=0;i<arr1.length;i++) {
			System.out.print(arr1[i]+" ");
		}
		
		//for next line
		System.out.println();
		
		//printing elements of arr2
		System.out.print("Elements in arr2[] are: ");
		for(int i=0;i<arr2.length;i++) {
			System.out.print(arr2[i]+" ");
		}
	}	

}



  Output of the above program is : 
Elements in arr1[] are : 10 20 30 40 50
Elements in arr2[] are : 10 20 30 40 50


Share your thoughts in the comment section given below.... :)

2 comments:

If you have any doubts, please discuss here...👇