JAVA - Zero to Hero / Arrays and Strings

Multidimensional Arrays

๐Ÿ“˜ What is a Multidimensional Array?

A multidimensional array in Java is an array that contains other arrays as its elements.

The most commonly used type is the 2D array, which stores data in rows and columns like a table or matrix.

๐Ÿ“Ž In Java, a 2D array is just an array of 1D arrays.


๐Ÿ—๏ธ Declaration & Initialization

int[][] arr;

๐Ÿ“ This declares a reference to a 2D integer array.


๐Ÿงฑ Memory Allocation

arr = new int[2][3];

โœ… This creates a 2D array with 2 rows and 3 columns. All elements are initialized to 0 by default.


๐Ÿ“ฆ Declaration + Initialization (Inline)

int[][] arr = {
    {1, 2, 3},
    {4, 5, 6}
};

This creates and fills a 2D array at once.

1 2 3
4 5 6

๐Ÿ” Accessing Elements

You can access values using row and column indices:

System.out.println(arr[1][2]);
6

๐Ÿ’ก Here, arr[1][2] means 2nd row, 3rd column (index starts at 0).


๐Ÿ” Traversing a 2D Array

Use nested loops:

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
        System.out.print(arr[i][j] + " ");
    }
    System.out.println();
}
1 2 3
4 5 6

Prints all elements of a 2D array row by row.

๐Ÿง  arr[i][j] โ†’ accesses each element

๐Ÿ–จ๏ธ System.out.print(arr[i][j] + " ") โ†’ prints element with a space

โ†ฉ๏ธ System.out.println() โ†’ moves to next line after each row


๐Ÿšซ Common Mistakes

  • โŒ arr[2][0] will throw ArrayIndexOutOfBoundsException if there are only 2 rows (0 and 1).

  • โœ… Always check:

    • arr.length for total rows

    • arr[i].length for number of columns in a specific row


๐Ÿงฉ Jagged Arrays (Irregular 2D Arrays)

  • Java supports jagged arrays โ€” where each row can have a different number of columns.

  • Jagged arrays are useful when data doesnโ€™t fit a perfect grid.

๐Ÿ“ค Filling and Printing a Jagged Array

int[][] jagged = new int[2][];      // Step 1: Declare jagged array
jagged[0] = new int[3];             // Row 0 โ†’ 3 columns
jagged[1] = new int[1];             // Row 1 โ†’ 1 column

// Step 2: Assign values
jagged[0][0] = 10;
jagged[0][1] = 20;
jagged[0][2] = 30;
jagged[1][0] = 40;

// Step 3: Print the jagged array
for (int i = 0; i < jagged.length; i++) {
    for (int j = 0; j < jagged[i].length; j++) {
        System.out.print(jagged[i][j] + " ");
    }
    System.out.println();
}
10 20 30
40

๐ŸŽฏ Real-World Use Cases

  • ๐Ÿ“Š Mathematical matrices

  • ๐Ÿ“‹ Tabular data (like Excel sheets)

  • ๐ŸŽฎ Game boards (Tic Tac Toe, Sudoku)

  • ๐Ÿ–ผ๏ธ Image pixel storage