Here is how we can initialize a 2-dimensional array in Java.
As we can see, each element of the multidimensional array is an array itself. And also, unlike C/C++, each row of the multidimensional array in Java can be of different lengths.
Output for the above code block will be as follows.
In the above example, we are creating a multidimensional array named a. Since each component of a multidimensional array is also an array (a[0], a[1] and a[2] are also arrays). Here, we are using the length attribute to calculate the length of each row.
Output is as follows
We can also use the for...each loop to access elements of the multidimensional array. For example,
Output is as follows
In the above example, we are have created a 2d array named a. We then used for loop and for...each loop to access each element of the array. Let's see how we can use a 3d array in Java. We can initialize a 3d array similar to the 2d array. For example,
Basically, a 3d array is an array of 2d arrays. The rows of a 3d array can also vary in length just like in a 2d array.
Output for the above program is as follows