How to Copy One Array to Another in Java ?



How to Copy One Array to Another in Java

  • Java provides inbuilt methods to copy array. Whether we want a full copy or partial copy of array, we can do it easily using java inbuilt classes.

Object.clone():

  • Object class provides clone() method and since array in java is also an Object, we can use this method to achieve full array copy.
  • If you want partial copy of the array we cant't use this method.

Sample Code in Java

public class Wiki
{ 
	public static void main(String[] args) 
	{ 
		int a[] = {2, 8, 3}; 

		// Copy elements of a[] to b[] 
		int b[] = a.clone(); 

		// Change b[] to verify that b[] is different 
		// from a[] 
	 

		System.out.println("Values of a[] "); 
		for (int i=0; i<a.length; i++) 
			System.out.print(a[i] + " "); 

		System.out.println("\n\nValues of b[] "); 
		for (int i=0; i<b.length; i++) 
			System.out.print(b[i] + " "); 
	} 
}

Output

Values of a[] 
2 8 3 

Values of b[] 
2 8 3


Related Searches to How to Copy One Array to Another in Java ?