CodeBlanks Logo Icon CodeBlanks

Multi-dimensional arrays

Learn matrices with int[][].

Multi-dimensional arrays

A multi-dimensional array is an array of arrays. With int[][] you define a matrix:

int[][] m = new int[2][3];
// 2 rows, 3 columns
int[][] n = {{1, 2}, {3, 4}};
System.out.println(n[0][0]);  // 1

m[0][1] is the first row's second column. The first index is the row, the second is the column. In a literal each row is written in braces.

Matrix access

Each element of a matrix is accessed with two indexes: m[row][column].

int[][] m = {{1, 2}, {3, 4}};
System.out.println(m[0][0]);  // 1
System.out.println(m[0][1]);  // 2
System.out.println(m[1][0]);  // 3
System.out.println(m[1][1]);  // 4

The row count is m.length, a row's column count is m[0].length. To walk a matrix, use nested for loops.

Practice Print matrix elements

Write a Main class with a main method. Assign the literal {{1, 2}, {3, 4}} to int[][] m. Print the top-left element with System.out.println(m[0][0]) and the bottom-right with System.out.println(m[1][1]).

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        int[][] m = {{1, 2}, {3, 4}};
        System.out.println(m[0][0]);
        System.out.println(m[1][1]);
    }
}

Expected output

1
4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the matrix concepts

Term Meaning
int[][] Matrix
[0][0] Top left
[1][1] Bottom right
{{1,2},{3,4}} Literal

2 How many elements does new int[2][3] create?

  • 6 Correct answer
  • 3
  • 2
  • 5

Explanation: 2 rows × 3 columns = 6 elements.

3 Complete the matrix access

Question
int v = matrix[____][0];
Answer
int v = matrix[0][0];

Explanation: matrix[0][0] gives the top-left element.

All lessons in Beginner