Java Multi-Dimensional Arrays

What Are Multidimensional Arrays?

A multidimensional array is essentially an array of arrays. This can be particularly useful when you need to store data in a tabular format, like a table with rows and columns.

Tutorials dojo strip

Creating a Two-Dimensional Array

To create a two-dimensional array, you simply nest each array within its own set of curly braces:

JAVA

Here, garage is now an array containing two arrays as its elements.

Accessing Elements

To access the elements of the garage array, you specify two indexes: one for the array and one for the element inside that array. For example, to access the third element in the second array:

JAVA

Note: Array indexes start at 0, so [0] is the first element, [1] is the second element, and so on.

Modifying Element Values

You can also change the value of an element in a multidimensional array:

JAVA

Looping Through a Multidimensional Array

Using Nested For Loops

To iterate through a two-dimensional array, you can use a for loop inside another for loop:

JAVA

Using For-Each Loops

Alternatively, you can use a for-each loop, which is often easier to read and write:

JAVA

Tutorials dojo strip