How to Copy One Array to Another in Java

Here you will learn how to copy one array to another in Java.

There are mainly four different ways to copy all elements of one array into another array in Java.

1. Manually
2. Arrays.copyOf()
3. System.arraycopy()
4. Object.clone()

Lets discuss each of them in brief.

How to Copy One Array to Another in Java

How to Copy One Array to Another in Java

1. Manually

In this method we manually copy elements one by one. It is not an efficient way. Below example shows how to do this.

Example:

 

2. Arrays.copyOf()

We can directly copy one array to another by using Arrays.copyOf() method. It has following syntax.

 

Example:

 

3. System.arraycopy()

It is another method that directly copies one array to another. It has following syntax.

 

Example:

 

4. Object.clone()

We can also use clone() method of Object class to make a copy of an array.

Example:

 

Comment below if you have any doubt related to above tutorial or you know about any other way to copy one array to another in Java.

3 thoughts on “How to Copy One Array to Another in Java

  1. Barakehud

    Nice post. Can you please benchmark them and post the results. I think most people will click this article to see these results.

    Reply
  2. Marty

    For the copyOf function of the Array class, I see it returns an array of integers. If that’s the case why do you still instantiate the destination array (which in our case is array b)?

    Reply
  3. Arya C Achari

    Thank you very much sir … it is so knowledgeable. i hope you will send me programs like this again

    Reply

Leave a Reply

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