16 Java Fundamentals | Multidimensional Arrays in Java | By Dummy for Dummies

Java Multidimensional Arrays | Hassan Bukhari
Java Notes

16 Java Fundamentals | Multidimensional Arrays in Java | By Dummy for Dummies

Java Beginner Guide 2D Arrays Matrices Nested Loops

INTRODUCTION

Hey guys welcome back! Remember we made variable of variables? And called it Arrays? Today we are gonna talk about how we can even make Array of Arrays; they are called multidimensional Arrays. Think of a 2D array as an array that contains arrays:

  • 2D Array → Contains Arrays → Contains variables/data
  • 3D Array → Contains 2D Arrays → Contains Arrays → Contains variables/data

And so on...


2D ARRAYS

Imagine a classroom full of chairs. It does not contain a single line of chairs (1D Array) but rather rows and columns of chairs. Where:

  • Row = Line of chairs
  • Column = Specific chair in that row

So to point to a specific chair you'd say "Row 3, column 2". That is exactly how you can access data in 2D Arrays. Let's first write the Java magical spell for the creation of a 2D Array:

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

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

  • int → It tells the program about the datatype of the array we want to create. Just like we did in making 1D Arrays and variables.
  • [][] → It tells the program that the datatype is actually 2D Array of Integers rather than just a 1D Array of Integer or a variable of integer.
  • new int[2][3] → Just focus on the numbers inside the square brackets i.e. [2][3]. The first number 2 decides the number of rows (How many 1D arrays in this 2D array). And the second number 3 decides the number of columns (How many indexes per 1D Array).

Just like in 1D arrays each entry had a specific index, here in 2D arrays each 1D array also has a specific index. And in each 1D array each entry has a specific index. So here two systems of indexes run. To access each entry in a 2D array we will need nested for loops. The outer loop will be responsible for checking the row (specific 1D array) and the inner loop will be responsible for checking the column (specific index in 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

  • Write a program to:
  • 1. Ask the user for the size of the matrix (rows and columns).
  • 2. Take input for two matrices A and B.
  • 3. Multiply them element by element → store result in C.
  • 4. Find the sum of all elements of C.
  • 5. Find the average of elements of C.
  • 6. Print results neatly.

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 are like Arrays that manage 1D Arrays. You can even create 3D Arrays but that becomes more complex. For now, they are enough and cover your syllabus.