Java Multidimensional Arrays

Arrays within arrays for storing data in rows and columns

🏢 What are Multidimensional Arrays?

Multidimensional arrays are arrays of arrays, creating a table-like structure with rows and columns. Think of them as spreadsheets where you can store data in a grid format, perfect for matrices, game boards, or tables.


// 2D array - like a table with 2 rows and 3 columns
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6}
};
System.out.println("Element at row 0, column 1: " + matrix[0][1]);
                                    

Output:

Element at row 0, column 1: 2

2D Array Structure

📊

Rows

Horizontal lines of data

matrix[0] // first row
📋

Columns

Vertical lines of data

matrix[0][1] // column 1
🎯

Access

Use two indices [row][column]

arr[i][j]
📐

Dimensions

Can have 2D, 3D, or more

int[][][] cube;

🔹 Creating 2D Arrays

Different ways to create and initialize 2D arrays:

🔸 Method 1: Direct Initialization

// Create a 2x3 array (2 rows, 3 columns)
int[][] scores = {
    {85, 90, 78},  // Row 0: Student 1's scores
    {92, 88, 95}   // Row 1: Student 2's scores
};

System.out.println("Student 1, Test 2: " + scores[0][1]);
System.out.println("Student 2, Test 3: " + scores[1][2]);

Output:

Student 1, Test 2: 90
Student 2, Test 3: 95

🔸 Method 2: Declare Then Fill

// Create empty 2D array
int[][] grid = new int[2][3]; // 2 rows, 3 columns

// Fill the array
grid[0][0] = 10; grid[0][1] = 20; grid[0][2] = 30;
grid[1][0] = 40; grid[1][1] = 50; grid[1][2] = 60;

System.out.println("Grid filled:");
System.out.println("Top-left: " + grid[0][0]);
System.out.println("Bottom-right: " + grid[1][2]);

Output:

Grid filled:
Top-left: 10
Bottom-right: 60

🔹 Accessing 2D Array Elements

Use two indices: first for row, second for column:

String[][] classroom = {
    {"Alice", "Bob", "Charlie"},
    {"Diana", "Eve", "Frank"},
    {"Grace", "Henry", "Ivy"}
};

// Access specific students
System.out.println("Front row, middle seat: " + classroom[0][1]);
System.out.println("Back row, left seat: " + classroom[2][0]);

// Get array dimensions
System.out.println("Number of rows: " + classroom.length);
System.out.println("Number of columns: " + classroom[0].length);

Output:

Front row, middle seat: Bob
Back row, left seat: Grace
Number of rows: 3
Number of columns: 3

🔹 Looping Through 2D Arrays

Use nested loops to process all elements:

🔸 Nested For Loops

int[][] multiplication = {
    {1, 2, 3},
    {2, 4, 6},
    {3, 6, 9}
};

System.out.println("Multiplication table:");
for (int row = 0; row < multiplication.length; row++) {
    for (int col = 0; col < multiplication[row].length; col++) {
        System.out.print(multiplication[row][col] + " ");
    }
    System.out.println(); // New line after each row
}

Output:

Multiplication table:
1 2 3 
2 4 6 
3 6 9 

🔸 Enhanced For Loops

String[][] fruits = {
    {"apple", "banana"},
    {"orange", "grape"},
    {"kiwi", "mango"}
};

System.out.println("All fruits:");
for (String[] row : fruits) {
    for (String fruit : row) {
        System.out.println("- " + fruit);
    }
}

Output:

All fruits:
- apple
- banana
- orange
- grape
- kiwi
- mango

🔹 Practical Examples

🔸 Tic-Tac-Toe Board

char[][] board = {
    {'X', 'O', 'X'},
    {'O', 'X', 'O'},
    {'X', 'O', 'X'}
};

System.out.println("Tic-Tac-Toe Board:");
for (int i = 0; i < board.length; i++) {
    for (int j = 0; j < board[i].length; j++) {
        System.out.print(board[i][j] + " ");
    }
    System.out.println();
}

Output:

Tic-Tac-Toe Board:
X O X 
O X O 
X O X 

🔸 Grade Calculator

// Grades for 3 students, 4 tests each
int[][] grades = {
    {85, 90, 78, 92},  // Student 1
    {88, 85, 90, 87},  // Student 2
    {92, 95, 89, 94}   // Student 3
};

System.out.println("Student averages:");
for (int student = 0; student < grades.length; student++) {
    int sum = 0;
    for (int test = 0; test < grades[student].length; test++) {
        sum += grades[student][test];
    }
    double average = (double) sum / grades[student].length;
    System.out.println("Student " + (student + 1) + ": " + 
                      String.format("%.1f", average));
}

Output:

Student averages:
Student 1: 86.3
Student 2: 87.5
Student 3: 92.5

🔹 3D Arrays (Brief Introduction)

Arrays can have more than 2 dimensions:

// 3D array: 2 floors, 3 rows, 4 columns
int[][][] building = new int[2][3][4];

// Set a value: Floor 0, Row 1, Column 2
building[0][1][2] = 100;

System.out.println("Value at floor 0, row 1, column 2: " + 
                   building[0][1][2]);

// Example: RGB color values for a 2x2 image
int[][][] image = {
    { {255,0,0}, {0,255,0} },    // Row 1: Red, Green
    { {0,0,255}, {255,255,0} }   // Row 2: Blue, Yellow
};

System.out.println("Top-left pixel (Red): " + 
                   image[0][0][0] + "," + image[0][0][1] + "," + image[0][0][2]);

Output:

Value at floor 0, row 1, column 2: 100
Top-left pixel (Red): 255,0,0

🧠 Test Your Knowledge

In a 2D array arr[3][4] , what does arr[1][2] represent?