Multidimensional Arrays
Multidimensional Arrays
So far every array you have worked with holds a flat list of values. Real problems often need more structure: a grid of pixels, a timetable, or a chessboard all demand rows and columns. Java handles this with multidimensional arrays — arrays whose elements are themselves arrays.
Declaring and Creating a 2D Array
The most common case is a two-dimensional (2D) array, often pictured as a table with rows and columns. The declaration adds one extra pair of brackets:
Java allocates three inner arrays, each of length four. Every cell starts at its default value (0 for int). You can also initialise it inline with an array literal:
Each inner array is a row. Think of scores[1][2] as "row 1, column 2" — the value 95.
Accessing Elements
You index a 2D array with two bracket expressions: the first for the row, the second for the column.
scores[1] is itself an int[] — you can pass it anywhere a 1D array is expected. This matters when you need to process one row at a time.
Iterating Over a 2D Array
Nested for loops are the standard way to visit every cell. The outer loop walks the rows; the inner loop walks the columns.
Output:
The enhanced for-each loop also works, treating each element of the outer array as a row:
A Practical Grid Example
Let us build a simple multiplication table — a classic 2D grid problem:
Output:
length — never hard-code dimensions. Write grid.length for rows and grid[0].length for columns. If the array is later resized, your loops still work without any changes.
Jagged Arrays
Java does not require every row to have the same length. When you allocate only the outer array and fill the rows manually, you get a jagged array (also called a ragged array).
Output:
NullPointerException. When you allocate only the outer dimension (new int[4][]), each row is null until you assign it. Accessing triangle[1][0] before assigning triangle[1] throws a NullPointerException.
Arrays with More Than Two Dimensions
Java allows three or more dimensions — just keep adding bracket pairs. A 3D array can represent a cube of values (for example, pixel data with width, height, and colour channels).
In practice, 2D arrays cover the vast majority of use cases. Go beyond two dimensions only when the data genuinely has that structure — the mental model and the code both get harder quickly.
Summary
- A 2D array is declared with
int[][] name = new int[rows][cols]and indexed withname[row][col]. - Use nested loops to iterate; the outer loop indexes rows and the inner loop indexes columns.
- Always use
array.lengthandarray[0].lengthinstead of hard-coded numbers. - Jagged arrays allow rows of different lengths — allocate the outer array first, then each row separately.
- Avoid accessing a row before it has been assigned or you will get a
NullPointerException.