Skip to main content

2D Arrays (Matrices)

A 2D Array in Java is effectively an array of arrays. It represents a grid or a matrix of elements.

Representation

Instead of a single line of elements, imagine a grid with rows and columns.

  • Row 0: [1, 2, 3]
  • Row 1: [4, 5, 6]
  • Row 2: [7, 8, 9]

Element 5 is at index [1][1] (Row 1, Column 1). Element 3 is at [0][2].

Implementation in Java

public class MatrixExample {
public static void main(String[] args) {
// Declaring a 3x3 2D array
int[][] matrix = new int[3][3];

// Assigning values
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
// ...

// Literal 2D Array Initialization
int[][] grid = {
{1, 2, 3}, // Row 0
{4, 5, 6}, // Row 1
{7, 8, 9} // Row 2
};

// Traversal
for (int i = 0; i < grid.length; i++) { // iterate over rows
for (int j = 0; j < grid[i].length; j++) { // iterate over columns
System.out.print(grid[i][j] + " ");
}
System.out.println(); // new line after each row
}
}
}

Jagged Arrays

Since a 2D array in Java is an array of arrays, the inner arrays don't have to be of the same length! These are called Jagged Arrays.

int[][] jagged = new int[3][];
jagged[0] = new int[2]; // Row 0 has 2 columns
jagged[1] = new int[4]; // Row 1 has 4 columns
jagged[2] = new int[1]; // Row 2 has 1 column