Web Analytics

Multi-Dimensional Arrays

Beginner ~25 min read

A multi-dimensional array is essentially an "array of arrays." The most common type is the 2D array, which represents a table or matrix with rows and columns. You can think of it like an Excel spreadsheet or a chessboard.

2D Arrays (Matrices)

To declare a 2D array, we use two sets of brackets [][]. The first bracket represents rows, and the second represents columns.

Java 2D Array Matrix Diagram
// Syntax: int[][] matrix = new int[rows][cols];
int[][] matrix = new int[3][3]; // A 3x3 table

Accessing Elements

You access elements by specifying the row index first, then the column index.

matrix[0][0] = 1;  // Top-left
matrix[1][2] = 5;  // Middle-right
Output
Click Run to execute your code

Jagged Arrays

Since a 2D array is just an array of arrays, each "row" can actually be a different length! These are called ragged or jagged arrays.

int[][] jagged = new int[3][]; // Define 3 rows, but cols unknown
jagged[0] = new int[2]; // Row 0 has 2 cols
jagged[1] = new int[4]; // Row 1 has 4 cols
jagged[2] = new int[1]; // Row 2 has 1 col
Use Case: Jagged arrays are memory efficient if you have data rows of varying sizes (e.g., storing varying number of comments for different posts).

Summary

  • Use [][] to declare a 2D array.
  • Think of it as array[rowIndex][colIndex].
  • Use nested loops to iterate over all elements.
  • Rows in a 2D array can have different lengths (Jagged Arrays).

Module Complete!

Congratulations! You have completed Module 2: Variables & Data Types. You now have a solid understanding of primitives, strings, arrays, and how to store data in Java.

In the next module, we will bring your programs to life with Operators & Control Flow (If statements, loops, logic).