Copy 2D Arrays in Java

Waleed Feb 09, 2022 Jan 19, 2022
  1. Using Loop Iteration to Copy 2D Array in Java
  2. Using the clone() Method to Copy 2D Array in Java
  3. Using arraycopy() Method to Copy 2D Array in Java
Copy 2D Arrays in Java

Whenever we attempt to copy elements of the 2D array to another array, we often assign an original array to the destination array. Why this approach is logically wrong, we’ll discuss it first.

Even though the below-mentioned solution is logically wrong, we want to let you know why this solution doesn’t work.

// Java Program to copy 2-dimensional array
// create 2D array
int [ ][ ] arr1 = { {2,4,6}, {8,10,12} };
// creating the same array with the same size
int [ ] [ ] arr2 = new int[arr1.length];
// this code does not copy elements of arr1[ ] to arr2[ ] because arr2[ ] sill refer to the same location
arr2 = arr1;

When we write arr2=arr1, we are assigning arr2[ ] a reference to the arr1[ ]. Therefore, changing one array will be reflected in both copied and the original array because both arrays are pointing to the same location.

To demonstrate this fact, have a look at the code depicted below.

// A Java program to demonstrate assigning an array reference doesn't make any sense

public class copy2DArray{
   public static void main(String []args){
       // Create an array arr1[]  
          int [][] arr1 = { {2,4,5}, {6,8,10} };
       // Create an array arr2[] with the same size
          int [][] arr2 = new int[arr1.length][];
       // Doesn't copy elements of arr1 to arr2, but only arr2 starts refering arr1
          arr2 = arr1;
       // Any changing in the arr2 also reflects in the arr1 because
       // both are referin to the same location
          arr2 [0][0] = 88;
          System.out.println("Elements of arr1[] are:");
          for (int i=0; i<arr1.length; i++){
            for (int j=0; j<arr1.length; j++){
               System.out.println(arr1[i][j] + " ");
            }
        }
          System.out.println("\n\nElements of arr2[] are:");
          for (int i=0; i<arr2.length; i++){
            for (int j=0; j<arr2.length; j++){
               System.out.println(arr2[i][j] + " ");
            }
	 }
   }
}

Output:

Elements of arr1[] are:
88
4
6
8
Elements of arr2[] are:
88
4
6
8

In the above example, we have discussed the common mistakes developers often make while copying elements of the 2D array. Now we’ll discuss the correct method to accomplish the same task.

In Java, we can copy array elements using the following methods:

  1. Iterate all elements of an array and copy each element.
  2. By using the clone() method.
  3. By using arraycopy() method.

Using Loop Iteration to Copy 2D Array in Java

Loop iteration technique for copying a 2D array. Using this method, you’ll experience that any destination or original array modification will not affect an original array. Thus, the original array remains intact.

// A Java program to demonstrate assigning an array reference doesn't make any sense
import java.util.Arrays;
public class copy2DArray{
   public static void main(String [ ]args){
      // Create an array arr1[ ]  
         int [ ][ ] arr1 = { {2,4,5}, {6,8,10} };
      // Create an array arr2[ ] with the same size
         int [ ][ ] arr2 = new int[arr1.length][ ];
      // Copying elements of arr1[ ] to arr2[ ]
         for(int i = 0; i < arr1.length; i++){
      // allocation space to each row of arr2[]
            arr2[i] = new int[arr1[i].length];    
            for(int j= 0; j<arr1[i].length; j++){
                arr2[i][j] = arr1[i][j];
           }
        }

    // Any change in the elements of arr2[ ] will not be reflected  in an original array
        arr2[0][0] = 90;
       System.out.println("Elements of arr1[] are:");
        for (int i=0; i < arr1.length; i++){
           for (int j=0; j < arr1[0].length; j++){
               System.out.println(arr1[i][j] + " ");
            }
        }
      System.out.println("\n\nElements of arr2[] are:");
      for (int i=0; i < arr2.length; i++){
         for (int j=0; j < arr2[0].length; j++){
               System.out.println(arr2[i][j] + " ");
            }
        }
     }
}

Output:

Elements of arr1[] are:
2 
4
5 
6 
8
10 
Elements of arr2[] are:
90 
4 
5 
6 
8 
10

Using the clone() Method to Copy 2D Array in Java

We used the loop iteration technique to copy 2D array elements in the previous method. We can do the same task with the clone() method.

// A Java program to demonstrate assigning an array reference doesn't make any sense

import java.util.Arrays;
public class copy2DArray{
  public static void main(String []args){
 // Create an array arr1[]  
    int [ ][ ] arr1 = { {2,4,5}, {6,8,10} };
 // Create an array arr2[] with the same size
    int [ ][ ] arr2 = new int[arr1.length][];
 // Copying elements of arr1[ ] to arr2[ ] using the clone() method
    for(int i = 0; i < arr1.length; i++)
          arr2[i] =  arr1[i].clone();
 // Any change in the elements of arr2[] will not be reflected in an original array
    arr2[0][0] = 90;
    System.out.println("Elements of arr1[] are:");
       for (int i=0; i < arr1.length; i++){
           for (int j=0; j < arr1[0].length; j++){
               System.out.println(arr1[i][j] + " ");
           }
        }
    System.out.println("\n\nElements of arr2[] are:");
    for (int i=0; i < arr2.length; i++){
      for (int j=0; j < arr2[0].length; j++){
           System.out.println(arr2[i][j] + " ");
           }
        }
    }

}

Output:

Elements of arr1[] are:
2 
4
5 
6 
8
10 
Elements of arr2[] are:
90 
4 
5 
6 
8 
10

Using arraycopy() Method to Copy 2D Array in Java

Likewise, we can copy 2D arrays using the arraycopy() method. We can copy elements of any 2D array without iterating all the array elements with this method. To use this method, we need to provide the following parameters:

  • src: source array that you need to copy
  • srcPos: starting location of an original array.
  • dest: destination array.
  • destPos: starting index of the destination array.
  • length: total number of elements of 2D array that we want to copy

Exception:

  • NullPointerException: if either source or destination array is not defined or doesn’t exist.
  • ArrayStoreException: If a developer attempts to copy an integer array type into a string array, this situation automatically triggers this exception.

Example:

package sampleProject;
import java.util.Arrays;
public class Codesample {
   public static void main(String []args){
// Create an array arr1[]  
   int [][] arr1 = { {2,4,5}, {6,8,10} };
// Create an array arr2[] with the same size
   int [][] arr2 = new int[arr1.length][];
// Copying elements of arr1[] to arr2[] using the clone() method
   for(int i = 0; i < arr1.length; i++) {
       arr2[i] =  new int[arr1[i].length];
    System.arraycopy(arr1[i], 0, arr2[i], 0, arr1[i].length);
    }
// Any change in the elements of arr2[] will not be reflected in an original array
   arr2[0][0] = 90;
   System.out.println("Elements of arr1[] are:");
   for (int i=0; i < arr1.length; i++){
       for (int j=0; j < arr1[0].length; j++){
           System.out.println(arr1[i][j] + " ");
          }

	}
   System.out.println("\n\nElements of arr2[] are:");
   for (int i=0; i < arr2.length; i++){
      for (int j=0; j < arr2[0].length; j++){
          System.out.println(arr2[i][j] + " ");
        }
      }
   }

}

Output:

Elements of arr1[] are:
2 
4
5 
6 
8
10 
Elements of arr2[] are:
90 
4 
5 
6 
8 
10

Related Article - Java Array