Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Multidimensional array

A multidimensional array in Java is an array of arrays. T[][] denotes two levels: the outer array stores references to rows, which may have different lengths or be null.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

T[][] name;
int[][] rectangle = new int[2][3];
int[][] rows = new int[2][];

T[][] denotes an array of arrays of elements of type T; here, T stands for a type name such as int or String. Each [] adds a nesting level. Declaring a variable alone does not create an array.

new int[2][3] creates an outer array and two rows of three zeros each. new int[2][] creates only the outer array: both row references initially contain null. Rows can be assigned later; their lengths need not match. Each created array has a fixed length, but a row reference can be replaced.

rows.length gives the number of rows, while rows[i].length gives the selected row's length. Access through rows[i][j] uses zero-based indices. An out-of-bounds index causes ArrayIndexOutOfBoundsException; reading the length or an element of a null row causes NullPointerException.

The example creates rows of lengths 2 and 1, then sums their elements. The nested loops traverse the actual rows without assuming a rectangular shape.

Examples

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

        int sum = 0;
        for (int[] row : rows) {
            for (int value : row) {
                sum += value;
            }
        }

        System.out.println(rows.length);
        System.out.println(rows[0].length + " " + rows[1].length);
        System.out.println(sum);
    }
}

Result

2
2 1
6

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources