← Back to all posts

16 Java Fundamentals

Multidimensional Arrays in Java

By Dummy for Dummies

Introduction

Hey, welcome back! Remember when we made variables of variables and called them Arrays? Today we're talking about Arrays of Arrays, called multidimensional arrays. Think of a 2D array as an array that holds other arrays:

And so on...


2D Arrays

Imagine a classroom full of chairs. It's not one long line of chairs (that would be a 1D array), it's rows and columns of them:

To point at one exact chair, you'd say "Row 3, column 2." That's exactly how you access data in a 2D array. Let's write the spell for creating one:

int[][] numbers = new int[2][3];

Let's break down the Java spell into our human language:

Just like each entry in a 1D array has an index, each 1D array inside a 2D array has its own index too, and each entry inside that 1D array has an index as well. So two index systems are running at once.

To reach every entry, we need nested for loops. The outer loop walks the rows (each 1D array), and the inner loop walks the columns (each entry inside that array).


Code:

Java
public class Main {
    public static void main(String[] args) {
        // Create a 2x3 2D array (2 rows, 3 columns)
        int[][] numbers = new int[2][3];

        // Fill the 2D array
        numbers[0][0] = 1;
        numbers[0][1] = 2;
        numbers[0][2] = 3;
        numbers[1][0] = 4;
        numbers[1][1] = 5;
        numbers[1][2] = 6;

        System.out.println("2D Array elements:");
        for (int row = 0; row < numbers.length; row++) {
            for (int col = 0; col < numbers[row].length; col++) {
                System.out.print(numbers[row][col] + " ");
            }
            System.out.println();
        }
    }
}
Console Output
2D Array elements: 1 2 3 4 5 6

Direct Initialization

Just like 1D arrays, we can also directly initialize 2D arrays. But here again, they are not that much useful. Here is the syntax to initialize a 2D array for a 3-by-3 Matrix:

Java
public class Main {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

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

Input in 2D Array

Taking input in a 2D array is just like taking input into a 1D array. You just have to access the right index, which can be automated using a for loop. Here is a demonstration:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of rows: ");
        int rows = sc.nextInt();
        System.out.print("Enter number of columns: ");
        int cols = sc.nextInt();

        int[][] data = new int[rows][cols];

        System.out.println("Enter elements:");
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                System.out.print("Enter element at [" + r + "][" + c + "]: ");
                data[r][c] = sc.nextInt();
            }
        }

        System.out.println("\nYou entered:");
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                System.out.print(data[r][c] + " ");
            }
            System.out.println();
        }
        sc.close();
    }
}
Console Output
Enter number of rows: 2 Enter number of columns: 3 Enter elements: Enter element at [0][0]: 1 Enter element at [0][1]: 2 Enter element at [0][2]: 3 Enter element at [1][0]: 4 Enter element at [1][1]: 5 Enter element at [1][2]: 6 You entered: 1 2 3 4 5 6

Exercise

Let's do an exercise for what we studied in this post. Study this code, break it down, analyze it and identify the concepts used here. It would be even better if you write down your observations and make a mini report on it.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of rows: ");
        int rows = sc.nextInt();
        System.out.print("Enter number of columns: ");
        int cols = sc.nextInt();

        int[][] A = new int[rows][cols];
        int[][] B = new int[rows][cols];
        int[][] sum = new int[rows][cols];

        System.out.println("Enter elements of first matrix:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print("Enter element at [" + i + "][" + j + "]: ");
                A[i][j] = sc.nextInt();
            }
        }

        System.out.println("Enter elements of second matrix:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print("Enter element at [" + i + "][" + j + "]: ");
                B[i][j] = sc.nextInt();
            }
        }

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                sum[i][j] = A[i][j] + B[i][j];
            }
        }

        System.out.println("\nResultant Matrix (A + B):");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(sum[i][j] + " ");
            }
            System.out.println();
        }
        sc.close();
    }
}
Console Output
Enter number of rows: 2 Enter number of columns: 3 Enter elements of first matrix: Enter element at [0][0]: 1 Enter element at [0][1]: 2 Enter element at [0][2]: 3 Enter element at [1][0]: 4 Enter element at [1][1]: 5 Enter element at [1][2]: 6 Enter elements of second matrix: Enter element at [0][0]: 7 Enter element at [0][1]: 8 Enter element at [0][2]: 9 Enter element at [1][0]: 1 Enter element at [1][1]: 2 Enter element at [1][2]: 3 Resultant Matrix (A + B): 8 10 12 5 7 9

Mini Project: Monkey's Matrix Power

Boss Monkey has two banana matrices. He wants to multiply them element-by-element (not normal matrix multiplication, but multiplying each corresponding element). Then, he wants to find the total sum of the new matrix and also its average.


Tasks


Example Output

Console Output
Enter number of rows: 2 Enter number of columns: 2 Enter elements of Matrix A: A[0][0]: 1 A[0][1]: 2 A[1][0]: 3 A[1][1]: 4 Enter elements of Matrix B: B[0][0]: 5 B[0][1]: 6 B[1][0]: 7 B[1][1]: 8 Resultant Matrix (A * B element-wise): 5 12 21 32 Total Sum = 70 Average = 17.5

Closing

That's it for 2D Arrays in Java. They're Arrays that manage other Arrays. You can go further into 3D Arrays too, but things get more complex from there. For now, this is enough to cover your syllabus.

← Previous 15 - Arrays in Java