How to Add Two Matrices in Java

Matrix operations are important in a number of algorithms. It is used in graph theory, geometry, probability theory and image processing. Matrix addition is simple, each entry in first matrix is added to the corresponding entry in the second matrix to get the entry in the result matrix.

The following sample program illustrates matrix addition in Java. This example uses constant matrices hard-coded in Java, but you can easily change functions getMatrixA() or getMatrixB() to read them from files or from command line. Also note how we derive number of rows and columns from the matrix data.

/**
 * Add two matrices. 
 */
public class MatrixAddition {
    
    public static void main(String[] args) {
        MatrixAddition ma = new MatrixAddition();
        ma.addMatrices();
    }

    /**
     * Gets two matrices, adds them and prints the result on console.
     */
    private void addMatrices() {
        int[][] matrixA = getMatrixA();
        int[][] matrixB = getMatrixB();
        
        int[][] matrixResult = addMatrices(matrixA, matrixB);
        printMatrix(matrixResult);
    }

    /**
     * Returns first matrix
     * @return 
     */
    private int[][] getMatrixA() {
        int[][] matrixA = new int[][] {
                                {4,5,3},
                                {2,1,3},    
                                {7,6,1}
                            };
        return matrixA;
    }
    
    /**
     * Returns second matrix
     * @return 
     */
    private int[][] getMatrixB() {
        int[][] matrixB = new int[][] {
                                {4,1,8},
                                {3,0,2},    
                                {9,1,1}
                            };
        return matrixB;
    }

    //Adds two matrices. 
    private int[][] addMatrices(int[][] matrixA, int[][] matrixB) {
        int rows=matrixA.length;
        int cols=matrixA[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] = matrixA[i][j] + matrixB[i][j];
            }
        }
        return sum;
    }
    
    /**
     * Prints the matrix on command line.
     * @param matrix 
     */
    public void printMatrix(int[][] matrix) {
        int rows=matrix.length;
        int cols=matrix[0].length;
        
        for(int i=0;i<rows;i++) {
            for(int j=0;j<cols;j++) {
                System.out.print(" "+matrix[i][j]);
            }
            System.out.println();
        }
    }
}