Menu

1 / 2

Multi-Dimensional Arrays Made Simple (With Java Examples)

DEV Community·Quipoin·6 months ago
#W7UUA0rJ
#java#ai#machinelearning#webdev#arrays
Reading 0:00
15s threshold

At some point, 1D arrays are not enough.

What if you need to represent:

A chess board

A game grid

A matrix

That’s where multi-dimensional arrays come in.

What is a 2D Array?

A 2D array is simply an array of arrays.

Think of it like a table:

Rows

Columns

Declaration & Initialization

// Declaration

int[][] matrix = new int[3][4];

// Initialization

int[][] grid = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

Accessing Elements

int element = grid[1][2]; // 6

First index = row

Second index = column

Traversing a 2D Array

for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[i].length; j++) {

System.out.print(matrix[i][j] + " ");

}

System.out.println();

}

Time Complexity: O(n × m)

Visit each row and column

Jagged Arrays

Unlike normal 2D arrays, rows can have different lengths.

int[][] jagged = new int[3][];

jagged[0] = new int[2];

jagged[1] = new int[3];

jagged[2] = new int[1];

Useful when data is not uniform

The Real Insight

2D arrays = array of arrays

Memory is not…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.