How to Copy One Array to Another in Java ?

Answer : Java provides inbuilt methods to copy array…

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

[pastacode lang=”java” manual=”public%20class%20Wiki%0A%7B%20%0A%09public%20static%20void%20main(String%5B%5D%20args)%20%0A%09%7B%20%0A%09%09int%20a%5B%5D%20%3D%20%7B2%2C%208%2C%203%7D%3B%20%0A%0A%09%09%2F%2F%20Copy%20elements%20of%20a%5B%5D%20to%20b%5B%5D%20%0A%09%09int%20b%5B%5D%20%3D%20a.clone()%3B%20%0A%0A%09%09%2F%2F%20Change%20b%5B%5D%20to%20verify%20that%20b%5B%5D%20is%20different%20%0A%09%09%2F%2F%20from%20a%5B%5D%20%0A%09%20%0A%0A%09%09System.out.println(%22Values%20of%20a%5B%5D%20%22)%3B%20%0A%09%09for%20(int%20i%3D0%3B%20i%3Ca.length%3B%20i%2B%2B)%20%0A%09%09%09System.out.print(a%5Bi%5D%20%2B%20%22%20%22)%3B%20%0A%0A%09%09System.out.println(%22%5Cn%5CnValues%20of%20b%5B%5D%20%22)%3B%20%0A%09%09for%20(int%20i%3D0%3B%20i%3Cb.length%3B%20i%2B%2B)%20%0A%09%09%09System.out.print(b%5Bi%5D%20%2B%20%22%20%22)%3B%20%0A%09%7D%20%0A%7D” message=”” highlight=”” provider=”manual”/]

Output

Values of a[] 
2 8 3 

Values of b[] 
2 8 3
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like