Next-Gen App & Browser Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

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.
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.
The logic is the same whether the matrices are hardcoded or read from input. Follow these steps:
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();
}
}
}Each corresponding pair sums to 10, so the program prints:
Sum of the two matrices:
10 10 10
10 10 10
10 10 10To 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();
}
}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();
}
}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.
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.
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.
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.
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).
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.
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.
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.
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