Java - Multi-Dimensional Arrays

Introduction

You can represent a tabular data in a two dimensional array.

A multi-dimensional array is declared using a pair of brackets [] for each dimension in the array declaration.

For example, you can declare a two dimensional array of int as shown:

int[][] table;

table is a reference variable that can hold a reference to a two-dimensional array of int.

A two-dimensional array of int with three rows and two columns can be created as shown:

table = new int[3][2];

The indexes of each dimension in a multi-dimensional array are zero-based.

Each element of the table array can be accessed as table[rownumber][columnNumber].

To assign a value to the first row and the second column in the table array:

table[0][1] = 32;

You must set the first level array's dimension when creating a multi-dimensional array.

table = new int[3][];

This statement creates only first level of array.

Only table[0], table[1] and table[2] exist at this time.

Since table[0], table[1] and table[2] are arrays of int, you can assign them values as

table[0] = new int[2]; // Create two columns for row 1
table[1] = new int[2]; // Create two columns for row 2
table[2] = new int[2]; // Create two columns for row 3

You can create a two-dimensional array with different number of columns for each row.

Such an array is called a ragged array.

Demo

public class Main {
  public static void main(String[] args) {
    // Create a two-dimensional array of 3 rows
    int[][] raggedArr = new int[3][];

    // Add 2 columns to the first row
    raggedArr[0] = new int[2];

    // Add 1 column to the second row
    raggedArr[1] = new int[1];

    // Add 3 columns to the third row
    raggedArr[2] = new int[3];

    // Assign values to all elements of raggedArr
    raggedArr[0][0] = 1;//  ww  w. j a v a  2 s  .  co m
    raggedArr[0][1] = 2;
    raggedArr[1][0] = 3;
    raggedArr[2][0] = 4;
    raggedArr[2][1] = 5;
    raggedArr[2][2] = 6;

    // Print all elements. One row at one line
    System.out.println(raggedArr[0][0] + "\t" + raggedArr[0][1]);
    System.out.println(raggedArr[1][0]);
    System.out.println(raggedArr[2][0] + "\t" + raggedArr[2][1] + "\t" + raggedArr[2][2]);
  }
}

Result

Related Topics