Multidimensional Array in Java

We learnt about single dimensional array which arranged data in a single row. Now lets learn about multidimensional array which arranges data in row and column.


Multidimensional Array is used to store data in tabular or matrix form. We can create multidimensional array by just adding one more square bracket after data type. Syntax:

DataType[][] variable;
Storing data is easy as well. We can place values in a comma separated list inside curly braces and again separated each group with a comma and wrap everything in a comma. Here is how:
variable = {{v1,v2,v3},{v4,v5,v6},{v7,v8,v9}}
or, creating array with new keyword is easy as well. Syntax:
variable = new DataType[rows][cols];


How Multidimensional Array Works

These arrays stores data in matrix form. And can be accessible using two indexes, that is row and column. Lets see if we create array a, how data saves here:


We can see above that each element have two indexes Since array index starts at 0, we have one less index than total size.


How to Access Data?

To traverse all elements in multidimensional array, we have to use two loops. One nested inside another. So that each loops iteration value with work as row and colum index.


Example:

Code:
public class LearnMDArray { public static void main(String[] args) { //creating array int[][] nums = {{2, 4, 6}, {3, 6, 9}, {4, 8, 12}}; //printing multidimensional array System.out.println("Values in Array: "); for(int i = 0; i < nums.length; i ++) { for(int j = 0; j < nums.length; j++) { System.out.print(nums[i][j] + " \t"); } System.out.println(); } } }
Code:
Values in Array:
2 4 6
3 6 9
4 8 12

For and For Each Loop in Java Array Previous Next OOP Concepts in Java