02.Java Multidimensional Arrays
02.Java Multidimensional Arrays
In this tutorial, we will learn about the Java multidimensional array using 2-
dimensional arrays and 3-dimensional arrays with the help of examples.
Before we learn about the multidimensional array, make sure you know
about Java array.
A multidimensional array is an array of arrays. Each element of a
multidimensional array is an array itself. For example,
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},
};
Initialization of 2-
dimensional Array
Example: 2-dimensional Array
class MultidimensionalArray {
public static void main(String[] args) {
// 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},
};
Output:
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
3
-4
-5
// test is a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
// create a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
Output:
1
-2
3
2
3
4
-4
-5
6
9
1
2