Java Copy Array | Java Array Clone Examples

Here is the situation, you have an Array and you want another copy of it to do manipulate the data of it. So to do it you need a Copy of Array. This tutorial you will learn “How Java Copy Array” example program.

Before start must read the – Array Initialization | Types with Examples Tutorial 

Java Copy Array and How to Java Clone Array Examples

Let’s start Array copy in Java

  • Iteration- Easy and correct
  • Using Clone()
  • Using System.arraycopy()
  • Reference of an Array (Simple but Wrong)

Java Copy Array Examples

Let’s see one bye one example how to copy a array with different methods.

Iteration- Easy 

A doing Iteration is an easy way to copy an Array in Java. Each element copy at a time.

Here is the example used a Java for loop for an iteration. We are checking is both Array reference is same or not. It will not the same because the copyArray is different memory allocation and changing the value of it not reflect on Original Arrays.

Output: Original Array
9 0 3
Copy of Array
9 0 3
Is same: false

Using Clone()

So many Loop iteration on an upper example? Here is java can do much better with clone() method. See the example How to  How to Java Clone Array Example.

Output: Original Array
1 0 4
Copy of Array
2 0 4

Using System.arraycopy()

If you want a subArray or few elements of an array to be copied in the new array can use this one way

System.arraycopy() Method is present in java.lang package.

  • src – The Source Array,
  • srcPos – is the index from which copying starts.
  • dest – The Destination Array
  • destPos – The index copied elements are placed in the destination array.
  • length is the length of subarray to be copied in another Array.

Check the below Java Array Clone example for better understanding.

Output: array[]
1 0 2copyArray[]
1 0 2

Reference of an Array (Simple but Wrong)

Using an Assignment operator will copy the only reference, means they both array variables will refer same memory and data. Here is an example of it and also check the both have the same reference or not.

this way is not Correct because the changing the value of array on anyone will reflect another one. Which is missing the object of the goal to get another copy to do some change without touching original data.

Output: Is same refer: true

Do comment if you have any doubts and suggestions on this tutorial

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java Copy Array | How to Java Clone Array Examples are in Java 11, so it may change its different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.