19. Java Multidimensional Arrays
19. Java Multidimensional Arrays
2-
dimensional Array
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts
with 0 and not 1.
Let's take another example of the multidimensional array. This time we will be
creating a 3-dimensional array. For example,
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
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.
// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
1
-2
3
-4
-5
6
9
7
We can also use the for...each loop to access elements of the multidimensional
array. For example,
class MultidimensionalArray {
public static void main(String[] args) {
// create a 2d array
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
Output:
-2
-4
-5
6
// test is a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
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:
1
-2
3
2
3
4
-4
-5
6
9
1
2
3