09 May Multidimensional Arrays in Java
In the last lesson, we learned about One-Dimensional Arrays in Java and how to use them. Now, we will see about a concept of arrays in Java i.e. Multidimensional Arrays. Multi-dimensional arrays as the name suggests are arrays of arrays. You need to use two square brackets to declare a multidimensional array, unlike one-dimensional array.
Let us see an example to declare a 2 by 3 multidimensional array,
1 2 3 |
int result[][] = new int[2][3]; |
The following figure displays how a multidimensional array forms a 2×3 matrix,
Above, the left index determines row and the right index determines column.
We will now see how to display each element from our 2×3 matrix,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class StudyopediaDemo { public static void main(String args[]) { int i, j, k = 0; int result[][]= new int[2][3]; for(i=0; i<2; i++) for(j=0; j<3; j++) { result[i][j] = k; k++; } for(i=0; i<2; i++) { for(j=0; j<3; j++) System.out.print(result[i][j] + " "); System.out.println(); } } } |
The following is the output displaying each element,
In this lesson, we saw how to work with Multidimensional arrays in Java.
No Comments