Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java program to add two matrices?

To add two matrices in Java, sum their corresponding elements with the rule result[i][j] = A[i][j] + B[i][j]. Both matrices must have the same dimensions (same number of rows and columns), and the addition is done with two nested loops that run in O(m × n) time. Below is a clean, runnable program, a generalized m×n version with a dimension check, and a reusable method you can drop into your own code.

What Is Matrix Addition?

Matrix addition is the element-wise sum of two matrices of the same order. You take the value at each position in the first matrix, add the value at the same position in the second matrix, and store the result at that position in a new matrix.

  • Rule: both matrices must have identical dimensions, the same number of rows and the same number of columns; otherwise the operation is undefined.
  • Element-wise: each output cell depends only on the two cells at the matching index, so positions never interact across the matrix.
  • Worked example (2×2): [[1,2],[3,4]] + [[5,6],[7,8]] = [[6,8],[10,12]], because 1+5=6, 2+6=8, 3+7=10, and 4+8=12.

Algorithm to Add Two Matrices

The logic is the same whether the matrices are hardcoded or read from input. Follow these steps:

  • Define the matrices: read or declare two matrices A and B of the same order m×n.
  • Verify dimensions: confirm the row count and column count of A and B match before proceeding.
  • Create the result: allocate a result matrix C of the same order m×n.
  • Loop and add: for every row i and column j, set C[i][j] = A[i][j] + B[i][j].
  • Print the output: traverse C row by row and print the summed values.

Java Program to Add Two Matrices (Hardcoded Example)

The simplest version uses two fixed 3×3 matrices, derives the size from the array length rather than hardcoding it, and prints the sum:

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

        int rows = a.length;
        int cols = a[0].length;
        int[][] sum = new int[rows][cols];

        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("Sum of the two matrices:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(sum[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output

Each corresponding pair sums to 10, so the program prints:

Sum of the two matrices:
10 10 10
10 10 10
10 10 10

Adding Two Matrices From User Input (3×3)

To read the values at runtime, use a Scanner to fill both 3×3 matrices before adding them:

import java.util.Scanner;

public class AddMatrix {
    public static void main(String[] args) {
        int i, j;
        int[][] m = new int[3][3];
        int[][] n = new int[3][3];
        int[][] o = new int[3][3];

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the nine elements of the first matrix: ");
        for (i = 0; i < 3; i++) {
            for (j = 0; j < 3; j++) {
                m[i][j] = sc.nextInt();
            }
        }

        System.out.print("Enter the nine elements of the second matrix: ");
        for (i = 0; i < 3; i++) {
            for (j = 0; j < 3; j++) {
                n[i][j] = sc.nextInt();
            }
        }

        for (i = 0; i < 3; i++) {
            for (j = 0; j < 3; j++) {
                o[i][j] = m[i][j] + n[i][j];
            }
        }

        System.out.println("Addition of the two matrices:");
        for (i = 0; i < 3; i++) {
            for (j = 0; j < 3; j++) {
                System.out.print(o[i][j] + " ");
            }
            System.out.println();
        }
        sc.close();
    }
}

Generalized m×n Matrix Addition With a Dimension Check

Hardcoding the size to 3 makes the program brittle. This version reads the number of rows and columns, then adds two matrices of any matching order. Because both matrices are created with the same dimensions, the addition is always valid:

import java.util.Scanner;

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

        System.out.print("Enter the number of rows: ");
        int rows = sc.nextInt();
        System.out.print("Enter the 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 the first matrix:");
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++)
                a[i][j] = sc.nextInt();

        System.out.println("Enter elements of the second matrix:");
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; 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("Resultant (sum) matrix:");
        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();
    }
}

Matrix Addition Using a Reusable Method

Extracting the addition into a method makes it modular and easy to unit test. The method validates that the dimensions match and throws an IllegalArgumentException if they do not:

public class MatrixAdder {

    // Returns A + B, or throws if dimensions do not match.
    public static int[][] add(int[][] a, int[][] b) {
        if (a.length != b.length || a[0].length != b[0].length) {
            throw new IllegalArgumentException(
                "Matrices must have the same dimensions to be added.");
        }
        int rows = a.length;
        int cols = a[0].length;
        int[][] result = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result[i][j] = a[i][j] + b[i][j];
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] a = { {2, 4}, {6, 8} };
        int[][] b = { {1, 3}, {5, 7} };
        int[][] sum = add(a, b);

        for (int[] row : sum) {
            for (int value : row) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

This prints 3 7 on the first row and 11 15 on the second. Because add is a pure function, you can call it from a JUnit test and assert the returned array against an expected matrix.

Time and Space Complexity

  • Time complexity: O(m × n), where m is the number of rows and n the number of columns. Every element is read and added exactly once.
  • Space complexity: O(m × n) for the separate result matrix, or O(1) extra space if you add one matrix into the other in place.
  • Comparison: matrix addition is cheaper than Java Program Multiply Two Matrix, which uses three nested loops and runs in O(m × n × p) time.

Common Errors When Adding Matrices in Java

  • Dimension mismatch: trying to add matrices of different orders is mathematically invalid. Guard against it with an explicit size check, as shown in the reusable method above.
  • ArrayIndexOutOfBoundsException: happens when loop bounds are not tied to array.length and array[i].length. Always derive the limits from the array itself.
  • Jagged (ragged) arrays: rows of unequal length break the assumption of a rectangular matrix. Validate each row's length, or build the arrays so every row has the same size.
  • Integer overflow: very large values can exceed the int range and wrap to a negative number. Use long when your data may overflow 32-bit integers.
  • Hardcoding the size: writing 3 everywhere instead of array.length makes the program fail for any matrix that is not 3×3. Compute the dimensions dynamically.

Validating Java Logic Across Environments

Java is a top language for test automation, so once your matrix logic compiles and passes locally, the same code often becomes part of a larger Selenium or Appium suite. You can run those Java test suites at scale across 3,000+ browser and OS combinations on the TestMu AI (Formerly LambdaTest) cloud grid, and execute them in parallel to keep feedback fast. For a small coding utility like matrix addition, a couple of JUnit assertions on the add method are enough; the cloud grid is where the broader UI tests that call into your Java code get their cross-environment coverage.

Frequently Asked Questions

Can you add two matrices of different sizes in Java?

No. Matrix addition is only defined when both matrices have identical dimensions, the same number of rows and the same number of columns. If the orders differ, the operation is undefined, so a correct program should reject the input with a dimension check before it starts looping.

What is the time complexity of matrix addition in Java?

It is O(m × n) for an m-by-n matrix, because every element is visited exactly once. The space complexity is O(m × n) for the result matrix, or O(1) extra space if you add one matrix into the other in place.

How do you add two matrices without using a third matrix in Java?

Add the second matrix into the first in place with a[i][j] += b[i][j] inside the nested loops. This overwrites matrix A with the sum and avoids allocating a separate result array, reducing the extra space to O(1).

Can you add matrices using Java Streams or the Arrays class?

Yes, you can express element-wise addition with an IntStream over the indices, but for a 2D int array the two plain nested loops are the clearest and most efficient approach. Arrays.deepToString is still handy for printing the whole matrix in one line.

What is the difference between matrix addition and multiplication in Java?

Addition is element-wise and requires both matrices to share the same dimensions, running in O(m × n) time. Java Program Multiply Two Matrix requires the columns of A to equal the rows of B, uses three nested loops, runs in O(m × n × p) time, and produces a matrix of a different shape.

How do you print a 2D matrix in Java?

Use nested loops with System.out.print for each element and System.out.println after each row to start a new line, or call Arrays.deepToString(matrix) for a quick single-line representation of the entire 2D array.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests