Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Multidimensional Arrays

Multidimensional Arrays

A multidimensional array consists of arrays within arrays.

Multidimensional arrays prove useful when organizing data in a tabular format, resembling a table comprising rows and columns.

You can form a two-dimensional array by enclosing each array within its own set of curly braces:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

Now, myNumbers consists of an array containing two arrays as its elements.

Access Elements

To retrieve elements from the myNumbers array, you need to provide two indexes: one for the array and another for the element within that array. In this instance, the example accesses the third element (2) in the second array (1) of myNumbers.

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]); // Outputs 7

 

Keep in mind that array indexes commence from 0: [0] represents the first element, [1] denotes the second element, and so forth.

Change Element Values

You also have the capability to modify the value of an element:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7
 

Loop Through a Multi-Dimensional Array

You can utilize a nested for loop to iterate through the elements of a two-dimensional array, requiring you to reference the two indexes as before.

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
  for (int j = 0; j < myNumbers[i].length; ++j) {
    System.out.println(myNumbers[i][j]);
  }
}

Alternatively, you can employ a for-each loop, which is frequently simpler to comprehend and implement:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int[] row : myNumbers) {
for (int i : row) {
System.out.println(i);
}
}