Perform Matrix Subtraction in Java

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
2D arrays

What you’ll learn

  • The element-wise rule Cij = Aij − Bij for matrices of the same size.
  • A complete 3×3 Java program (including negative differences), a compact 2×2 variant, and a live preview.
  • How subtraction relates to addition (A − B = A + (−B)) and common interview follow-ups.

Overview

Subtracting matrices works like subtracting numbers in a table: each cell in A is subtracted by the matching cell in B.

Two programs

3×3 reference data and a 2×2 difference.

Live preview

Same integers as example 1; prints A, B, and A − B.

Negatives

Expect negative entries whenever B is greater than A in a cell.

Prerequisites

2D arrays, nested loops, and same-size matrix checks.

  • 2D arrays and nested loops in Java.
  • Both matrices must have the same dimensions.

What is matrix subtraction?

For same-sized matrices, subtract each matching cell: C[i][j] = A[i][j] - B[i][j]. Order matters: A - B is not equal to B - A.

Definition

(A - B)[i][j] = A[i][j] - B[i][j] (entry-wise subtraction).

Intuition

Subtract each matching cell; signs can become negative.

Live preview

Uses the same 3x3 sample matrices from Example 1.

Live result
Press "Show subtraction".

Algorithm

Goal: compute C[i][j] = A[i][j] - B[i][j] for every cell.

Same shape

A and B must have the same rows and columns.

Subtract per cell

Use nested loops for i and j, then assign result[i][j] = a[i][j] - b[i][j].

Display

Print each row in a clean format so output is easy to read.

📜 Pseudocode

Pseudocode
function subtractMatrices(A, B, C, 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]
1

Subtract two 3×3 matrices

subtractMatrices computes matrix1 - matrix2. Some cells become negative, which is normal.

java
public class Main {
    static void subtractMatrices(int[][] mat1, int[][] mat2, int[][] result) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                result[i][j] = mat1[i][j] - mat2[i][j];
            }
        }
    }

    static void displayMatrix(int[][] matrix) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] matrix1 = {
            {5, 8, 2},
            {7, 4, 9},
            {3, 6, 1}
        };
        int[][] matrix2 = {
            {3, 1, 7},
            {6, 9, 2},
            {8, 5, 4}
        };
        int[][] resultMatrix = new int[3][3];

        subtractMatrices(matrix1, matrix2, resultMatrix);

        System.out.println("Matrix 1:");
        displayMatrix(matrix1);
        System.out.println("\nMatrix 2:");
        displayMatrix(matrix2);
        System.out.println("\nResultant Matrix (Matrix1 - Matrix2):");
        displayMatrix(resultMatrix);
    }
}
2

Subtract two 2×2 matrices

A compact version for quick interview explanation.

java
public class Main {
    static final int ROWS = 2;
    static final int COLS = 2;

    static void subtractMatrices(int[][] a, int[][] b, int[][] out) {
        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                out[i][j] = a[i][j] - b[i][j];
            }
        }
    }

    static void printMatrix(String title, int[][] m) {
        System.out.println(title);
        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                System.out.print(m[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] a = {
            {1, 2},
            {3, 4}
        };
        int[][] b = {
            {4, 3},
            {2, 1}
        };
        int[][] c = new int[ROWS][COLS];

        subtractMatrices(a, b, c);

        printMatrix("A", a);
        System.out.println();
        printMatrix("B", b);
        System.out.println();
        printMatrix("A - B", c);
    }
}

Optimization note

Time is already optimal at O(m*n) because each output cell must be written once.

❓ FAQ

Subtraction works cell by cell like addition: same position in A minus same position in B. Matrix multiplication combines rows of A with columns of B and is a different operation.
Yes. Each entry of A − B needs a matching entry in B, so both must be m×n for the same m and n.
Usually no. Subtraction is not commutative: B − A is the negative of A − B entrywise.
Yes. If A[i][j] < B[i][j], the difference at that cell is negative. Java int stores negative values correctly within range.
Subtracting two large ints can still overflow int in edge cases. Use long if values can be huge.
Each of the m·n entries is computed once: O(m·n) time and O(1) extra space besides the output matrix.

🔄 Input / output examples

For A=[[1,2],[3,4]] and B=[[4,3],[2,1]], output is [[-3,-1],[1,3]].

Edge cases

Dimensions

Reject mismatch

Subtraction is valid only when rows and columns are equal in both matrices.

Range

Integer overflow

Use long if values are very large and may exceed int.

⏱️ Time and space complexity

OperationTimeExtra space
Subtract two m × n matricesO(m · n)O(1) besides result storage

Summary

  • Matrix subtraction is entry-wise and requires equal shapes.
  • Nested loops produce O(m*n) time and constant extra space (excluding output matrix).
Did you know?

Matrix subtraction is entrywise like addition: (A − B)ij = Aij − Bij. It is the same as adding A and (−B). The two matrices must have the same shape.

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.

8 people found this page helpful