Back to course

Deep Dive into Arrays (Multi-dimensional Arrays)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 29: Deep Dive into Arrays

Arrays were introduced in Lesson 7. Here we explore multi-dimensional arrays and helper classes.

1. Single-Dimensional Arrays Recap

  • Fixed size upon creation.
  • Hold elements of a single type.
  • Indexed from 0 to length - 1.

java int[] numbers = {10, 20, 30}; System.out.println(numbers.length); // Output: 3

2. Multi-Dimensional Arrays (Arrays of Arrays)

Multi-dimensional arrays are often used to represent matrices or grids (e.g., 2D arrays).

Declaration and Initialization

java // Declaration of a 2x3 integer matrix int[][] matrix = new int[2][3];

// Assigning values matrix[0][0] = 1; matrix[1][2] = 6;

// Initializer list: int[][] grid = { {1, 2, 3}, // Row 0 {4, 5, 6} // Row 1 };

System.out.println(grid[1][0]); // Output: 4

Iterating 2D Arrays

Requires nested loops:

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

3. Jagged Arrays

Java arrays don't have to be rectangular. You can define arrays where each inner array has a different length.

java int[][] triangle = new int[3][]; triangle[0] = new int[1]; triangle[1] = new int[2]; triangle[2] = new int[3];

4. The java.util.Arrays Class

This utility class provides essential static methods for array manipulation, such as sorting, searching, and converting to strings.

java int[] arr = {3, 1, 2}; Arrays.sort(arr); // arr is now {1, 2, 3}

// Quickly print array contents System.out.println(Arrays.toString(arr));