Create Array of an Array in Java

Mohd Ebad Naqvi Jul 02, 2021
  1. Create an Array of Arrays by Assigning a List of Arrays in Java
  2. Create an Array of Arrays Using the new Keyword in Java
Create Array of an Array in Java

In Programming, an array is a linear data structure that can store a fixed-size sequential collection of elements of the same type. We can also use arrays to store other arrays. This way, we create a multi-dimensional array. The sub-arrays can also contain other arrays.

We will create an array of arrays in Java in this article.

Create an Array of Arrays by Assigning a List of Arrays in Java

In this method, different arrays are created, and embedded in a single array by using the syntax int[][] arrays = {arr1, arr2, arr3 ..};

Now the array will contain all the arrays defined within its block. All the arrays defined inside it can be accessed using the parent array.

For example,

public class ArrayDemo1 {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4};
        int[] arr2 = {5, 6, 7, 8};
        int[] arr3 = {9, 10, 11, 12};
    
    int[][] arrays = {arr1, arr2, arr3};
     
    for(int[] array: arrays) {
        for(int n: array) {
            System.out.print(n+" ");
        }
        System.out.println();
    }
  }   
}

Output:

1 2 3 4 
5 6 7 8 
9 10 11 12 

Create an Array of Arrays Using the new Keyword in Java

The new keyword can create new instances of a class in Java. We can use it to declare an array at each index of the parent array. We can define the sub-arrays while assigning them in the parent array.

See the following code.

public class ArrayDemo2 {
    public static void main(String[] args) {
        int[][] NumArrays = new int[5][];

        NumArrays[0] = new int[] {1, 2, 3, 4};
        NumArrays[1] = new int[] {5, 6, 7, 8};
        NumArrays[2] = new int[] {9, 10, 11, 12};
        NumArrays[3] = new int[] {13, 14, 15, 16};
        NumArrays[4] = new int[] {17, 18, 19, 20};

        for(int[] array: NumArrays) {
            for(int i: array) {
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }
}

Output:

1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14 15 16 
17 18 19 20 

Related Article - Java Array