Array Copy in Java

Object Oriented ProgrammingJava 8Programming

Array in java can be copied to another array using the following ways.

  • Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. To prevent this side effect following are the better ways to copy the array elements.

  • Create a new array of the same length and copy each element.

  • Use the clone method of the array. Clone methods create a new array of the same size.

  • Use System.arraycopy() method. arraycopy can be used to copy a subset of an array.

Example

Create a java class named Tester.

Tester.java

Live Demo

public class Tester {
   public static void main(String args[]) {      
      //Scenario 1: Copy array using assignment
      int[] a = {1, 2, 3};      
      int[] b = a;

      //test side effect
      b[0]++;

      System.out.println("Scenario 1: ");
      System.out.print("Array a: ");
      printArray(a);
      System.out.print("Array b: ");
      printArray(b);

      //Scenario 2: Copy array by iterating
      int[] c = {1, 2, 3};       int[] d = new int[c.length];
      for (int i = 0; i < d.length; i++) {
         d[i] = c[i];
      }

      //test side effect
      d[0]++;

      System.out.println("Scenario 2: ");
      System.out.print("Array c: ");
      printArray(c);
      System.out.print("Array d: ");
      printArray(d);

      //Scenario 3: Copy array using clone
      int[] e = {1, 2, 3};      
      int[] f = e.clone();

      //test side effect
      f[0]++;

      System.out.println("Scenario 3: ");
      System.out.print("Array e: ");
      printArray(e);
      System.out.print("Array f: ");
      printArray(f);

      //Scenario 4: Copy array using arraycopy
      int[] g = {1, 2, 3};      
      int[] h = new int[g.length];
      System.arraycopy(g, 0, h, 0, h.length);

      //test side effect
      h[0]++;

      System.out.println("Scenario 4: ");
      System.out.print("Array g: ");
      printArray(g);
      System.out.print("Array h: ");
      printArray(h);    
   }

   public static void printArray(int[] a) {
      System.out.print("[ ");
      for (int i = 0; i < a.length; i++) {
         System.out.print(a[i] + " ");
      }
      System.out.println("]");
   }
}

Output

Compile and Run the file to verify the result.

Scenario 1:  
Array a: [ 2 2 3 ]
Array b: [ 2 2 3 ]
Scenario 2:  
Array c: [ 1 2 3 ]
Array d: [ 2 2 3 ]
Scenario 3:  
Array e: [ 1 2 3 ]
Array f: [ 2 2 3 ]
Scenario 4:  
Array g: [ 1 2 3 ]
Array h: [ 2 2 3 ]
raja
Published on 20-Jul-2018 11:07:51
Advertisements