Java Matrix Addition Program

Beginner
6 min read
Updated: Oct 2026
2 programs
Live preview

What Is Matrix Addition?

Matrix addition adds matching cells: C[i][j] = A[i][j] + B[i][j]. Both matrices must have the same number of rows and columns.

Remember
A + B is defined only when A and B have the same shape

  [ 1  2 ]   [ 5  6 ]   [ 6  8 ]
  [ 3  4 ] + [ 7  8 ] = [10 12 ]

Rule: (A + B)[i][j] = A[i][j] + B[i][j]
PositionABA + B
[0][0]156
[0][1]268
[1][0]3710
[1][1]4812

How to Add Matrices in Java

Four clear steps — nested loops do the work cell by cell.

  1. Confirm both matrices have the same rows and columns.
  2. Create a result matrix of that same size.
  3. Outer loop walks rows; inner loop walks columns.
  4. Set result[i][j] = A[i][j] + B[i][j] for every cell.
MethodIdeaTimeBest for
Nested loopsAdd matching cells into a new int[][]O(m × n)Interviews, teaching
Shape-safe addValidate length first, then addO(m × n)Safer production-style code

Pseudocode

Pseudocode
function AddMatrices(A, B):
    rows = rows of A
    cols = cols of A

    if rows != rows of B or cols != cols of B:
        error "shapes must match"

    C = new matrix[rows][cols]
    for i from 0 to rows - 1:
        for j from 0 to cols - 1:
            C[i][j] = A[i][j] + B[i][j]

    return C

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
RuleC[i][j] = A[i][j] + B[i][j]
RequirementSame rows and same columns
Rows / colsa.length / a[0].length
LoopsOuter = rows, inner = columns
Not multiplyAddition is entrywise only
Classic check{{1,2},{3,4}} + {{5,6},{7,8}} = {{6,8},{10,12}}

Live Preview

Pick a sample pair to see matrices A, B, and A + B.

Tap a chip, then Add matrices (or tap a chip alone — it runs automatically).

Result
A =
1  2
3  4

B =
5  6
7  8

A + B =
6  8
10 12

Worked Walkthrough — 2×2

Visit every index once and add the matching cells.

Calculation
A = [1 2]    B = [5 6]
    [3 4]        [7 8]

i=0, j=0 → 1 + 5 = 6
i=0, j=1 → 2 + 6 = 8
i=1, j=0 → 3 + 7 = 10
i=1, j=1 → 4 + 8 = 12

Result = [6  8]
         [10 12]

Java Programs

Start with a clear nested-loop adder. Then add a shape check so mismatched sizes fail safely.

Example 1 — Nested Loops

Add two same-sized int[][] matrices cell by cell and print the result.

Java
public class MatrixAdd {
    static int[][] addMatrices(int[][] a, int[][] b) {
        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;
    }

    static void print(int[][] m) {
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[i].length; j++) {
                System.out.print(m[i][j] + " ");
            }
            System.out.println();
        }
    }

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

How It Works

  1. Read rows and columns with a.length and a[0].length.
  2. Allocate a result matrix of the same size.
  3. Outer loop chooses row i; inner loop chooses column j.
  4. Store a[i][j] + b[i][j] into result[i][j].
  5. Print walks the result the same way — one row per line.

Example 2 — Shape-Safe Add

Validate dimensions before adding so mismatched matrices fail with a clear error.

Java
public class MatrixAddSafe {
    static int[][] addMatrices(int[][] a, int[][] b) {
        int rows = a.length;
        int cols = a[0].length;

        if (b.length != rows || b[0].length != cols) {
            throw new IllegalArgumentException("Matrices must have the same dimensions.");
        }

        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 = { { 1, 2, 3 }, { 4, 5, 6 } };
        int[][] b = { { 7, 8, 9 }, { 1, 1, 1 } };
        int[][] sum = addMatrices(a, b);

        for (int i = 0; i < sum.length; i++) {
            for (int j = 0; j < sum[i].length; j++) {
                System.out.print(sum[i][j] + " ");
            }
            System.out.println();
        }
    }
}

How It Works

  1. Compare both length (rows) and [0].length (columns) values.
  2. Throw if shapes differ — addition would be undefined.
  3. Otherwise run the same nested-loop addition as Example 1.
  4. For the 2×3 sample: each cell sums independently.
  5. Mention this check in interviews even if the sample sizes already match.

Edge Cases & Pitfalls

Check these before calling the solution done.

Shape

Must match

Different sizes cannot be added — validate first.

Indexing

0-based

Loops run 0 .. rows-1 and 0 .. cols-1.

Overflow

int can wrap

Use long[][] when cell sums may exceed Integer.MAX_VALUE.

Multiply

Different problem

Do not confuse entrywise add with row-column multiply.

Time and Space Complexity

ProgramTimeExtra space
Nested loopsO(m × n)O(1) besides result
Shape-safe addO(m × n)O(1) besides result

Every cell is touched exactly once. The result matrix needs O(m × n) space to store the answer.

Key Takeaways

  • Rule: add matching cells; shapes must match.
  • Loops: outer rows, inner columns.
  • API: length / [0].length for rows and columns.
  • Test: {{1,2},{3,4}} + {{5,6},{7,8}} → {{6,8},{10,12}}.

One line: same shape required — then C[i][j] = A[i][j] + B[i][j].

Frequently Asked Questions

Only when they have the same dimensions — same row count and same column count. Then each result cell is the sum of matching cells.
Interview problems usually use a rectangular 2D array such as int[][] m = { {1, 2}, {3, 4} }. Use m.length for rows and m[0].length for columns.
Yes. For equal-sized matrices, A + B equals B + A because each pair of matching entries is added.
No. Addition is entrywise. Multiplication mixes rows and columns and follows different dimension rules.
For an m × n matrix, each entry is visited once, so time is O(m × n). Extra space is O(1) besides the result matrix.

Next: Matrix Division

Divide matching cells of two matrices element-wise.

Matrix division tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful