Java Matrix Addition Program

Introduction

Matrix Addition is one of the most common operations performed on matrices in Java programming. It involves adding two matrices by adding their corresponding elements. Matrix addition is widely used in mathematical calculations, computer graphics, scientific applications, machine learning, and data processing.

In Java, matrices are represented using two-dimensional arrays. A two-dimensional array stores data in the form of rows and columns, which makes it suitable for representing matrices.

For example:

consider two matrices:


Matrix A:
1  2
3  4

Matrix B:
5  6
7  8

After adding both matrices:

Result Matrix:

6 8
10 12

Each element of the first matrix is added with the corresponding element of the second matrix.

In this tutorial, you will learn how to perform matrix addition in Java, understand the algorithm, implement the program using arrays, take user input, analyze complexity, learn common mistakes, and explore interview questions.

What is Matrix Addition?

Matrix Addition is the process of adding two matrices by adding elements that have the same position in both matrices.

For matrix addition, both matrices must have the same number of rows and columns.

The formula for matrix addition is:


C[i][j] = A[i][j] + B[i][j]

Where:

  • A = First matrix
  • B = Second matrix
  • C = Result matrix
  • i = Row index
  • j = Column index

Example:


Matrix A:
2  4
6  8

Matrix B:
1  3
5  7

Addition:


2+1   4+3
6+5   8+7

Result:

3 7
11 15

Rules for Matrix Addition

Before adding two matrices, the following conditions must be satisfied:

1. Same Number of Rows

Both matrices should have equal rows.

Example:


Matrix A: 2 x 3
Matrix B: 2 x 3

Allowed.

2. Same Number of Columns

Both matrices should have equal columns.

Example:


Matrix A: 3 x 3
Matrix B: 3 x 3

Allowed.

3. Same Matrix Size

Invalid example:


Matrix A:
1 2
3 4

Matrix B:
5 6 7
8 9 10

These matrices cannot be added because their dimensions are different.

Syntax

The general syntax for matrix addition in Java:


The general syntax for matrix addition in Java:
for(int i = 0; i < rows; i++) {
    for(int j = 0; j < columns; j++) {
        result[i][j] = matrix1[i][j] + matrix2[i][j];
    }
}

Java Matrix Addition Program


public class MatrixAddition {
    public static void main(String[] args) {
        int[][] matrix1 = {
            {1, 2},
            {3, 4}
        };
        int[][] matrix2 = {
            {5, 6},
            {7, 8}
        };
        int[][] result = new int[2][2];
        for(int i = 0; i < 2; i++) {
            for(int j = 0; j < 2; j++) {
                result[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }
        System.out.println("Result Matrix:");
        for(int i = 0; i < 2; i++) {
            for(int j = 0; j < 2; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output

Result Matrix:

6 8
10 12

Explanation of the Program

Step 1: Declare First Matrix


int[][] matrix1 = {
    {1,2},
    {3,4}
};

This creates the first 2×2 matrix.

Step 2: Declare Second Matrix


int[][] matrix2 = {
    {5,6},
    {7,8}
};

This creates the second matrix.

Step 3: Create Result Matrix


int[][] result = new int[2][2];

The result matrix stores the sum of both matrices.

Step 4: Add Matrix Elements


result[i][j] = matrix1[i][j] + matrix2[i][j];

This statement adds corresponding elements.

Example:


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

Step 5: Display Result

Nested loops are used to print rows and columns of the result matrix.

Java Matrix Addition Using User Input


import java.util.Scanner;
public class MatrixAddition {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number of rows: ");
        int rows = scanner.nextInt();
        System.out.print("Enter number of columns: ");
        int columns = scanner.nextInt();
        int[][] matrix1 = new int[rows][columns];
        int[][] matrix2 = new int[rows][columns];
        int[][] result = new int[rows][columns];
        System.out.println("Enter first matrix elements:");
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                matrix1[i][j] = scanner.nextInt();
            }
        }
        System.out.println("Enter second matrix elements:");
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                matrix2[i][j] = scanner.nextInt();
            }
        }
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                result[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }
        System.out.println("Addition of Matrix:");
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
        scanner.close();
    }
}

Output

Enter number of rows:
2

Enter number of columns:
2

Enter first matrix elements:
1
2
3
4

Enter second matrix elements:
5
6
7
8

Addition of Matrix:
6 8
10 12

Algorithm for Matrix Addition

  1. Start the program.
  2. Declare two matrices.
  3. Create an empty result matrix.
  4. Traverse each row and column using nested loops.
  5. Add corresponding elements of both matrices.
  6. Store the result in the third matrix.
  7. Display the resulting matrix.
  8. End the program.

Flowchart


Start
  |
  |
Declare Two Matrices
  |
  |
Create Result Matrix
  |
  |
Traverse Rows and Columns
  |
  |
Add Corresponding Elements
  |
  |
Store Result
  |
  |
Display Matrix
  |
  |
 End

Time Complexity

For a matrix of size m × n:


Time Complexity = O(m × n)

Explanation:

The program visits every element of both matrices once.

Example:

For a 3×3 matrix:


3 × 3 = 9 operations

Space Complexity


Space Complexity = O(m × n)

Because an additional matrix is created to store the result.

Advantages of Matrix Addition

  • Simple and easy to implement.
  • Helps understand two-dimensional arrays.
  • Useful in mathematical computations.
  • Used in graphics and scientific applications.
  • Improves understanding of nested loops.

Disadvantages of Matrix Addition

  • Both matrices must have the same dimensions.
  • Requires additional memory for storing the result.
  • Not suitable for extremely large matrices without optimization.

Common Mistakes

1. Adding Matrices of Different Sizes

Incorrect:


Matrix A: 2 x 2
Matrix B: 3 x 3

These matrices cannot be added.

2. Incorrect Loop Conditions

Wrong:


for(int i = 0; i <= rows; i++)

Correct:


for(int i = 0; i < rows; i++)

Otherwise, it causes:


ArrayIndexOutOfBoundsException

3. Using Wrong Index Values

Incorrect:


matrix1[i][j] + matrix2[j][i]

Correct:


matrix1[i][j] + matrix2[i][j]

4. Forgetting to Initialize Result Matrix

Incorrect:


result[i][j] = sum;

without creating:


int[][] result = new int[rows][columns];

5. Confusing Matrix Addition with Multiplication

Matrix addition:


A[i][j] + B[i][j]

Matrix multiplication uses a completely different formula.

Real-Life Applications of Matrix Addition

Matrix addition is used in:

  • Computer graphics
  • Image processing
  • Machine learning algorithms
  • Scientific calculations
  • Engineering simulations
  • Data analysis
  • Game development
  • Robotics

Examples:

  • Combining image data.
  • Adding coordinate transformations.
  • Processing numerical datasets.

Summary

The Java Matrix Addition Program is an important beginner-level program that helps developers understand two-dimensional arrays and nested loops. Matrix addition involves adding corresponding elements of two matrices and storing the result in a third matrix.

Java makes matrix operations simple using arrays. By learning matrix addition, developers can build a strong foundation for advanced topics such as matrix multiplication, transpose of matrices, image processing, machine learning algorithms, and numerical computing.

After mastering matrix addition, you can explore other Java matrix programs like Matrix Multiplication, Matrix Transpose, Matrix Subtraction, and Matrix Inversion.

Related Java Tutorials