Add Two Matrices in Java
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.
Java Program
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
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.
- 1
rowsandcolsare read froma, and a result matrixsumof the same shape is allocated. - 2The outer loop walks the rows with
i, and the inner loop walks the columns of that row withj. - 3
sum[i][j] = a[i][j] + b[i][j]fills each result cell from the matching pair. - 4Each row of
sumis printed withArrays.toString(row), so the output keeps the matrix shape.
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.
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
Approach 2: Java 8
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
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.
- 1
IntStream.range(0, a.length)streams the row indexes. - 2
mapToObj(i -> ...)turns each row index into anint[]built by a secondIntStreamover the column indexes. - 3Inside,
.map(j -> a[i][j] + b[i][j])computes each cell and.toArray()collects the row. - 4
.toArray(int[][]::new)gathers the rows into the final 2D array, which is printed row by row.
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.
Why: Each cell is still computed once, and the collected rows form a new r × c matrix.
Key Concepts
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.