Multi-Dimensional Arrays Made Simple (With Java Examples)

java dev.to


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 always perfectly rectangular
  • Jagged arrays give flexibility

Key Insights

  • Access → arr[row][col]
  • Traversal → nested loops
  • Jagged arrays → flexible rows
  • Used in grids, DP, matrices

For More: https://www.quipoin.com/tutorial/data-structure-with-java/multi-dimensional-arrays

Source: dev.to

arrow_back Back to Tutorials