Java Programs›Arrays›Add Two Matrices

Add Two Matrices in Java

beginner·  Arrays  ·  Matrix

Problem

Two matrices can be added only when they have the same number of rows and columns, and the result holds the sum of the values found at each matching position.

Given two matrices of the same dimensions, produce a third matrix where every cell is the sum of the two cells at that position.

Input
A = [[4, 7, 1], [2, 5, 9]], B = [[3, 2, 6], [8, 1, 4]]
Output
[[7, 9, 7], [10, 6, 13]]

Java Program

Java
import java.util.Arrays; public class AddTwoMatrices { public static void main(String[] args) { int[][] a = {{4, 7, 1}, {2, 5, 9}}; int[][] b = {{3, 2, 6}, {8, 1, 4}}; 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]; // add the values sitting at the same position } } for (int[] row : sum) { System.out.println(Arrays.toString(row)); } } }

Output

[7, 9, 7] [10, 6, 13]

Core Logic

Matrix addition is purely positional: each cell of the result depends only on the two cells at the same row and column, so one pass over every position is all it takes.

How It Works
  1. 1rows and cols are read from a, and a result matrix sum of the same shape is allocated.
  2. 2The outer loop walks the rows with i, and the inner loop walks the columns of that row with j.
  3. 3sum[i][j] = a[i][j] + b[i][j] fills each result cell from the matching pair.
  4. 4Each row of sum is printed with Arrays.toString(row), so the output keeps the matrix shape.
At row 1, column 2 the cells are 9 in A and 4 in B, so the result holds 13 there — every other cell is filled the same way.
💡

Key Point: The two matrices must share both dimensions; if B had fewer rows or columns, b[i][j] would throw an ArrayIndexOutOfBoundsException, so real code should compare the sizes first.

Complexity
Time Complexity: O(r × c)Space Complexity: O(r × c)

Why: Every one of the r × c cells is visited exactly once, and the result needs a new matrix of the same size.

Key Concepts

2D arraynested for loopmatrix dimensions

Approach 2: Java 8

Java
import java.util.Arrays; import java.util.stream.IntStream; public class AddTwoMatricesStream { public static void main(String[] args) { int[][] a = {{4, 7, 1}, {2, 5, 9}}; int[][] b = {{3, 2, 6}, {8, 1, 4}}; int[][] sum = IntStream.range(0, a.length) .mapToObj(i -> IntStream.range(0, a[i].length) .map(j -> a[i][j] + b[i][j]) // one row of sums .toArray()) .toArray(int[][]::new); Arrays.stream(sum).map(Arrays::toString).forEach(System.out::println); } }

Output

[7, 9, 7] [10, 6, 13]

Core Logic

Streams can build the result matrix row by row: an outer stream of row indexes, each mapped to an inner stream that produces that row's sums.

How It Works
  1. 1IntStream.range(0, a.length) streams the row indexes.
  2. 2mapToObj(i -> ...) turns each row index into an int[] built by a second IntStream over the column indexes.
  3. 3Inside, .map(j -> a[i][j] + b[i][j]) computes each cell and .toArray() collects the row.
  4. 4.toArray(int[][]::new) gathers the rows into the final 2D array, which is printed row by row.
For row index 0, the inner stream yields 4+3, 7+2, 1+6, giving the row [7, 9, 7].
💡

Key Point: The stream version describes the result rather than filling a pre-made array, but it does the same r × c additions — it's a style choice, not a speed-up.

Complexity
Time Complexity: O(r × c)Space Complexity: O(r × c)

Why: Each cell is still computed once, and the collected rows form a new r × c matrix.

Key Concepts

IntStream.range()mapToObj()toArray(int[][]::new)

Interview Questions

What happens if the two matrices have different sizes?

Addition isn't defined for them. Accessing a missing row or column throws ArrayIndexOutOfBoundsException, so compare a.length and a[0].length with b's dimensions first.

How do you subtract two matrices?

The same way, using a[i][j] - b[i][j] for each cell. Only the operator changes.

Learn the Concept

Related Programs