Java - Multi-Dimensional Array Elements Accessing

Introduction

A multi-dimensional array can be populated using nested for loops.

The number of for loops used to populate a multi-dimensional array is the number of array dimensions.

The following code illustrates how to populate and access elements of a two-dimensional array.

Demo

public class Main {
  public static void main(String[] args) {
    int[][] ra = new int[3][];
    ra[0] = new int[2];
    ra[1] = new int[1];
    ra[2] = new int[3];

    // Populate the ragged array using for loops
    for (int i = 0; i < ra.length; i++) {
      for (int j = 0; j < ra[i].length; j++) {
        ra[i][j] = i + j;/*from   w w w . j ava2 s  . c om*/
      }
    }

    // Print the array using for loops
    for (int i = 0; i < ra.length; i++) {
      for (int j = 0; j < ra[i].length; j++) {
        System.out.print(ra[i][j] + "\t");
      }
      // Add a new line after each row is printed
      System.out.println();
    }
  }
}

Result