0
0
JavaProgramBeginner · 2 min read

Java Program to Add Two Matrices with Output

To add two matrices in Java, create two 2D arrays and use nested for loops to add corresponding elements, storing the result in a new matrix, like result[i][j] = matrix1[i][j] + matrix2[i][j];.
📋

Examples

Inputmatrix1 = {{1, 2}, {3, 4}}, matrix2 = {{5, 6}, {7, 8}}
Output{{6, 8}, {10, 12}}
Inputmatrix1 = {{0, 0}, {0, 0}}, matrix2 = {{0, 0}, {0, 0}}
Output{{0, 0}, {0, 0}}
Inputmatrix1 = {{-1, 2}, {3, -4}}, matrix2 = {{5, -6}, {-7, 8}}
Output{{4, -4}, {-4, 4}}
🧠

How to Think About It

To add two matrices, think of them as grids of numbers. You add each number in the first matrix to the number in the same position in the second matrix. This means you go row by row and column by column, adding pairs of numbers and saving the sums in a new matrix.
📐

Algorithm

1
Get the two matrices as input.
2
Create a new matrix to store the sum with the same size.
3
Use two loops: one for rows and one for columns.
4
Add elements from both matrices at the same position and store in the new matrix.
5
After all elements are added, return or print the new matrix.
💻

Code

java
public class MatrixAddition {
    public static void main(String[] args) {
        int[][] matrix1 = {{1, 2}, {3, 4}};
        int[][] matrix2 = {{5, 6}, {7, 8}};
        int rows = matrix1.length;
        int cols = matrix1[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] = matrix1[i][j] + matrix2[i][j];
            }
        }

        System.out.println("Sum of matrices:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output
Sum of matrices: 6 8 10 12
🔍

Dry Run

Let's trace adding matrix1 = {{1, 2}, {3, 4}} and matrix2 = {{5, 6}, {7, 8}} through the code.

1

Initialize matrices and result

matrix1 = {{1, 2}, {3, 4}}, matrix2 = {{5, 6}, {7, 8}}, result = {{0, 0}, {0, 0}}

2

Add element at position (0,0)

result[0][0] = 1 + 5 = 6

3

Add element at position (0,1)

result[0][1] = 2 + 6 = 8

4

Add element at position (1,0)

result[1][0] = 3 + 7 = 10

5

Add element at position (1,1)

result[1][1] = 4 + 8 = 12

6

Final result matrix

result = {{6, 8}, {10, 12}}

Positionmatrix1[i][j]matrix2[i][j]result[i][j]
(0,0)156
(0,1)268
(1,0)3710
(1,1)4812
💡

Why This Works

Step 1: Matrix elements correspond by position

Each element in the first matrix is added to the element in the same row and column of the second matrix using result[i][j] = matrix1[i][j] + matrix2[i][j];.

Step 2: Use nested loops to cover all elements

Two loops go through rows and columns to access every element systematically.

Step 3: Store sums in a new matrix

The sums are saved in a new matrix so the original matrices stay unchanged.

🔄

Alternative Approaches

Using user input for matrices
java
import java.util.Scanner;
public class MatrixAdditionInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int rows = 2, cols = 2;
        int[][] matrix1 = new int[rows][cols];
        int[][] matrix2 = new int[rows][cols];
        System.out.println("Enter elements of first matrix:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                matrix1[i][j] = sc.nextInt();
            }
        }
        System.out.println("Enter elements of second matrix:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                matrix2[i][j] = sc.nextInt();
            }
        }
        int[][] result = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }
        System.out.println("Sum of matrices:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
        sc.close();
    }
}
Allows dynamic input but requires user interaction and more code.
Adding matrices of different sizes with validation
java
public class MatrixAdditionCheck {
    public static void main(String[] args) {
        int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}};
        int[][] matrix2 = {{7, 8, 9}, {10, 11, 12}};
        if (matrix1.length != matrix2.length || matrix1[0].length != matrix2[0].length) {
            System.out.println("Matrices must be of same size to add.");
            return;
        }
        int rows = matrix1.length;
        int cols = matrix1[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] = matrix1[i][j] + matrix2[i][j];
            }
        }
        System.out.println("Sum of matrices:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Adds validation to ensure matrices have the same size before adding.

Complexity: O(rows * cols) time, O(rows * cols) space

Time Complexity

The program uses nested loops to visit each element once, so the time grows with the number of elements, which is rows times columns.

Space Complexity

A new matrix is created to store the sum, so space used is proportional to the size of the matrices.

Which Approach is Fastest?

All approaches have similar time complexity; using user input adds overhead but does not change complexity.

ApproachTimeSpaceBest For
Fixed matrices in codeO(rows * cols)O(rows * cols)Simple, quick testing
User input matricesO(rows * cols)O(rows * cols)Dynamic input from user
With size validationO(rows * cols)O(rows * cols)Safe addition with error checking
💡
Always check that both matrices have the same dimensions before adding to avoid errors.
⚠️
Trying to add matrices of different sizes without checking dimensions causes runtime errors.