๐ŸŽ“ A1Learner
๐Ÿ”
0 of 48 lessons completed

Java Multidimensional Arrays

A multidimensional array is an array whose elements are arrays. A two-dimensional array forms a grid with rows and columns.

Read one cell

The grid holds two rows of three numbers. The first print reads row 0, column 1, and the second reads row 1, column 2.

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

Change one cell

The assignment targets row 1, column 0. The print line reads that same cell back.

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

Print every row

The import line brings in the Arrays helper. The loop passes one row at a time to Arrays.toString.

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[][] grid = {{1, 2, 3}, {4, 5, 6}};
    for (int i = 0; i < grid.length; i++) {
      System.out.println(Arrays.toString(grid[i]));
    }
  }
}

Example

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[][] scores = {{80, 90}, {70, 100}};
    scores[0][1] = 95;
    for (int i = 0; i < scores.length; i++) {
      System.out.println(Arrays.toString(scores[i]));
    }
  }
}

Key points

  • The type int[][] names a two-dimensional array of int values.
  • The first index picks the row and the second index picks the column.
  • An assignment to one cell changes only that cell.
  • An import line brings a helper class into the file.
  • Arrays.toString turns one row into readable text.

In this example, the grid holds two rows of scores. The assignment changes the cell at row 0, column 1 to 95. The loop prints each row through Arrays.toString. The first printed row shows the new value.

Note

Import lines sit above the class, outside it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does grid[1][2] select?