← Back to Chapters

Java Multi-Dimensional Arrays

? Java Multi-Dimensional Arrays

? Quick Overview

A multi-dimensional array in Java is an array of arrays. The most common form is a two-dimensional array, which is useful for representing tables, matrices, grids, or structured data.

? Key Concepts

  • Stored in rows and columns
  • Each row itself is a separate array
  • Can be rectangular or jagged
  • Indexing starts from 0

? Syntax / Theory

Java supports multi-dimensional arrays by nesting array brackets. Memory is allocated row-wise.

? View Code Example
// Declaration of a 2D integer array
int[][] matrix;

? Code Example(s)

? View Code Example
// Creating and initializing a 2D array
int[][] numbers = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Printing elements using nested loops
for(int i = 0; i < numbers.length; i++){
for(int j = 0; j < numbers[i].length; j++){
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}

? Live Output / Explanation

Output

1 2 3
4 5 6
7 8 9

The outer loop controls rows, while the inner loop accesses columns of each row.

? Interactive Visualizer

Click a cell to see how to access it in Java:

 
// Click a number above...

✅ Tips & Best Practices

  • Always use array.length for rows and array[row].length for columns
  • Jagged arrays can save memory when rows have different sizes
  • Initialize arrays before accessing elements

? Try It Yourself

  • Create a 3×3 matrix and calculate the sum of all elements
  • Print only the diagonal elements
  • Create a jagged array representing student marks