Skip to content
Related Articles

Related Articles

Improve Article
Array Copy in Java
  • Difficulty Level : Easy
  • Last Updated : 05 Feb, 2021

Given an array, we need to copy its elements in a different array.

Method 1 (Simple but Wrong) 

We might be tempted to proceed like this: 

Java




int a[] = { 1, 8, 3 };
 
// Create an array b[] of same size as a[]
int b[] = new int[a.length];
 
// Doesn't copy elements of a[] to b[], only makes
// b refer to same location
b = a;

However, it’s incorrect! 



When we do “b = a”, we are actually assigning a reference to the array. Hence, if we make any change to one array, it would be reflected in other arrays as well because both a and b refer to the same location. 

Java




// A Java program to demonstrate that simply
// assigning one array reference is incorrect.
public class Test {
    public static void main(String[] args)
    {
        int a[] = { 1, 8, 3 };
 
        // Create an array b[] of same size as a[]
        int b[] = new int[a.length];
 
        // Doesn't copy elements of a[] to b[],
        // only makes b refer to same location
        b = a;
 
        // Change to b[] will also reflect in a[]
        // as 'a' and 'b' refer to same location.
        b[0]++;
 
        System.out.println("Contents of a[] ");
        for (int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
 
        System.out.println("\n\nContents of b[] ");
        for (int i = 0; i < b.length; i++)
            System.out.print(b[i] + " ");
    }
}
Output
Contents of a[] 
2 8 3 

Contents of b[] 
2 8 3 

Method 2: (Easy and correct)

We might iterate each element of the given original array and copy one element at a time. Using this method guarantees that any modifications to b, will not alter the original array a. 

Java




// A Java program to demonstrate copying by
// one by one assigning elements of a[] to b[].
public class Test {
    public static void main(String[] args)
    {
        int a[] = { 1, 8, 3 };
 
        // Create an array b[] of same size as a[]
        int b[] = new int[a.length];
 
        // Copy elements of a[] to b[]
        for (int i = 0; i < a.length; i++)
            b[i] = a[i];
 
        // Change b[] to verify that
        // b[] is different from a[]
        b[0]++;
 
        System.out.println("Contents of a[] ");
        for (int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
 
        System.out.println("\n\nContents of b[] ");
        for (int i = 0; i < b.length; i++)
            System.out.print(b[i] + " ");
    }
}
Output
Contents of a[] 
1 8 3 

Contents of b[] 
2 8 3 

Method 3: ( Using Clone() ) 

In the previous method we had to iterate over the entire array to make a copy, can we do better? The answer is YES!
We can use the clone method in Java

Java




// A Java program to demonstrate array copy using clone()
public class Test {
    public static void main(String[] args)
    {
        int a[] = { 1, 8, 3 };
 
        // Copy elements of a[] to b[]
        int b[] = a.clone();
 
        // Change b[] to verify that
        // b[] is different from a[]
        b[0]++;
 
        System.out.println("Contents of a[] ");
        for (int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
 
        System.out.println("\n\nContents of b[] ");
        for (int i = 0; i < b.length; i++)
            System.out.print(b[i] + " ");
    }
}
Output



Contents of a[] 
1 8 3 

Contents of b[] 
2 8 3 

Method 4: ( Using System.arraycopy() )

We can also use System.arraycopy() Method. The system is present in java.lang package. Its signature is as : 

public static void arraycopy(Object src, int srcPos, Object dest, 
                             int destPos, int length)

Where:

  1. src denotes the source array. 
  2. srcPos is the index from which copying starts.
  3. dest denotes the destination array
  4. destPos is the index from which the copied elements are placed in the destination array.
  5. length is the length of the subarray to be copied. 

The program illustrates the same:  

Java




// A Java program to demonstrate array
// copy using System.arraycopy()
public class Test {
    public static void main(String[] args)
    {
        int a[] = { 1, 8, 3 };
 
        // Create an array b[] of same size as a[]
        int b[] = new int[a.length];
 
        // Copy elements of a[] to b[]
        System.arraycopy(a, 0, b, 0, 3);
 
        // Change b[] to verify that
        // b[] is different from a[]
        b[0]++;
 
        System.out.println("Contents of a[] ");
        for (int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
 
        System.out.println("\n\nContents of b[] ");
        for (int i = 0; i < b.length; i++)
            System.out.print(b[i] + " ");
    }
}
Output
Contents of a[] 
1 8 3 

Contents of b[] 
2 8 3 

Method 5: ( Using Arrays.copyOf( ))

If you want to copy the first few elements of an array or full copy of the array, you can use this method. Its syntax is as:

public static int[] copyOf​(int[] original, int newLength) 

Java




// A Java program to demonstrate array
// copy using Arrays.copyOf()
import java.util.Arrays;
class GFG {
    public static void main(String[] args)
    {
        int a[] = { 1, 8, 3 };
 
        // Create an array b[] of same size as a[]
        // Copy elements of a[] to b[]
        int b[] = Arrays.copyOf(a, 3);
        // Change b[] to verify that
        // b[] is different from a[]
        b[0]++;
 
        System.out.println("Contents of a[] ");
        for (int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
 
        System.out.println("\n\nContents of b[] ");
        for (int i = 0; i < b.length; i++)
            System.out.print(b[i] + " ");
    }
}
Output
Contents of a[] 
1 8 3 

Contents of b[] 
2 8 3 

Method 6: ( Using Arrays.copyOfRange())

This method copies the specified range of the specified array into a new array.

public static int[] copyOfRange​(int[] original, int from, int to)

Where,

  1. original − This is the array from which a range is to be copied, 
  2. from       − This is the initial index of the range to be copied, 
  3. to            − This is the final index of the range to be copied, exclusive.

Java




// A Java program to demonstrate array
// copy using Arrays.copyOfRange()
import java.util.Arrays;
class GFG {
    public static void main(String[] args)
    {
        int a[] = { 1, 8, 3, 5, 9, 10 };
 
        // Create an array b[]
        // Copy elements of a[] to b[]
        int b[] = Arrays.copyOfRange(a, 2, 6);
        // Change b[] to verify that
        // b[] is different from a[]
        System.out.println("Contents of a[] ");
        for (int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
 
        System.out.println("\n\nContents of b[] ");
        for (int i = 0; i < b.length; i++)
            System.out.print(b[i] + " ");
    }
}
Output
Contents of a[] 
1 8 3 5 9 10 

Contents of b[] 
3 5 9 10 

Overview of the above methods: 

  • Simply assigning reference is wrong
  • The array can be copied by iterating over an array, and one by one assigning elements.
  • We can avoid iteration over elements using clone() or System.arraycopy()
  • clone() creates a new array of the same size, but System.arraycopy() can be used to copy from a source range to a destination range.
  • System.arraycopy() is faster than clone() as it uses Java Native Interface (Source : StackOverflow)
  • If you want to copy the first few elements of an array or a full copy of an array, you can use Arrays.copyOf() method.
  • Arrays.copyOfRange() is used to copy a specified range of an array. If the starting index is not 0, you can use this method to copy a partial array.

This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :