How to store a 2d Array in another 2d Array in java?


Create an array to which you want to store the existing array with the same length. A 2d array is an array of one dimensional arrays therefore, to copy (or, to perform any operation on) the elements of the 2d array you need two loops one nested within the other. Where, the outer loop is to traverse through the array of one dimensional arrays and, the inner loop is to traverse through the elements of a particular one dimensional array.

Example

public class Copying2DArray {
   public static void main(String args[]) {
      int[][] myArray = {{41, 52, 63}, {74, 85, 96}, {93, 82, 71} };
      int[][] copyArray =new int[myArray.length][];
      for (int i = 0; i < copyArray.length; ++i) {
         copyArray[i] = new int[myArray[i].length];
         for (int j = 0; j < copyArray[i].length; ++j) {
            copyArray[i][j] = myArray[i][j];
         }
      }
      System.out.println(Arrays.deepToString(copyArray));
   }
}

Output

[[41, 52, 63], [74, 85, 96], [93, 82, 71]]

Updated on: 19-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements