initialize a 2d array in Java

Here is how we can initialize a 2-dimensional array in Java.


\begin{lstlisting}
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
\end{lstlisting}

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.


\begin{lstlisting}
class MultidimensionalArray {
public static void main(String...
...
System.out.println(''Length of row 3: '' + a[2].length);
}
}
\end{lstlisting}

Output for the above code block will be as follows.


\begin{lstlisting}
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
\end{lstlisting}

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.


\begin{lstlisting}
class MultidimensionalArray {
public static void main(String...
... < a[i].length; ++j) {
System.out.println(a[i][j]);
}
}
}
}
\end{lstlisting}

Output is as follows


\begin{lstlisting}
1
-2
3
-4
-5
6
9
7
\end{lstlisting}

We can also use the for...each loop to access elements of the multidimensional array. For example,


\begin{lstlisting}
class MultidimensionalArray {
public static void main(String...
...r(int data: innerArray) {
System.out.println(data);
}
}
}
}
\end{lstlisting}

Output is as follows


\begin{lstlisting}
1
-2
3
-4
-5
6
9
7
\end{lstlisting}

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,


\begin{lstlisting}
// test is a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
\end{lstlisting}

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.


\begin{lstlisting}
class ThreeArray {
public static void main(String[] args) {
...
...r(int item: array1D) {
System.out.println(item);
}
}
}
}
}
\end{lstlisting}

Output for the above program is as follows


\begin{lstlisting}
1
-2
3
2
3
4
-4
-5
6
9
1
2
3
\end{lstlisting}