This is the second program in the series of matrices related programming exercises in Java. In the last program, you have learned matrix multiplication and in this program, you will learn how to perform addition and subtraction of two matrices in Java. We'll create methods to calculate both sum and difference of two matrices in Java program. In Mathematics, a matrix is a rectangular array with two dimensions known as rows and columns. In Java, your can use a two-dimensional array to represent a matrix because it also has two dimensions rows and columns. Since a 2D array is nothing but an array of the array in Java, the length of the outer array is equal to the number of rows and length of sub-array is equal to the number of columns.

For example, to represent a 2x3 matrix in Java you need to create a two-dimensional integer array with two rows and three columns e.g. int[][] matrix = new int[2][3]. By default, each value in the two-dimensional array is populated with the default value for that data type i.e. zero for an integer array.

In order to calculate sum of two matrices, you need to loop through array and add respective elements from each matrix e.g. if given matrices are X and Y then addition of these matrices will z[i][j] = x[i][j] + y[i][j]. For subtraction just use minus sign instead of plus sign.

In order to add two matrices in maths, you just need to add the numbers in the matching positions e.g. number in the first row and column of the first matrix should be added to the first number in the second matrix as well, as shown in the following diagram:

For example, to represent a 2x3 matrix in Java you need to create a two-dimensional integer array with two rows and three columns e.g. int[][] matrix = new int[2][3]. By default, each value in the two-dimensional array is populated with the default value for that data type i.e. zero for an integer array.

In order to calculate sum of two matrices, you need to loop through array and add respective elements from each matrix e.g. if given matrices are X and Y then addition of these matrices will z[i][j] = x[i][j] + y[i][j]. For subtraction just use minus sign instead of plus sign.

**How to add two matrices in Java**In order to add two matrices in maths, you just need to add the numbers in the matching positions e.g. number in the first row and column of the first matrix should be added to the first number in the second matrix as well, as shown in the following diagram:

That's why dimension of both matrices should be same to perform addition e.g. both must have same row and same columns.

**How to subtract two matrices in Java**

In order to calculate the difference of two matrices, you just need to subtract numbers in the matching position e.g. subtract the first number of the first matrix with the first number of the second matrix. Actually, subtraction is nothing but the addition of a negative matrix e.g. to subtract matrix A and B, you perform addition of A + (-B). Here is a nice diagram which explains subtraction of matrices:

Now, let's see our program to calculate sum and difference of two matrices in Java. Btw, if you are also interested in programming exercises, you could try solving problems asked in various technical interviews e.g. Amazon or Facebook or any startups. You can find a good collection of those questions on Cracking the Coding Interview book. The 6th edition contains more than 189 problems and their solutions.

**Java Program to add and subtract two matrices in Java**

Here is our complete Java program to perform addition and subtraction of two matrices. Unlike the last article where we have created a class called Matrix to represent matrices in Java which had rows and columns and holds matrix data into a two-dimensional array, in this program we'll perform addition and subtraction of matrices using static methods, which takes two matrices and return their sum and difference.

This is not really an object-oriented approach but it's good for such task. All program is coded into a single class MatrixAdditionSubtractionDemo, which also has methods to perform addition and subtraction of matrices, a method to print matrices into the command prompt and a method to read user input from the command prompt and populate the matrices. We are also using Scanner to read user input from the command prompt.

The code to test the add() and subtract() method are inside main() method, which creates two matrices in form of two-dimensional array and pass it to these methods for calculating sum and difference.

import java.util.Scanner;

/*

* Java Program to add and subtract two matrices.

* A matrix can be represented as two dimensional array in Java

*/

public class MatrixAdditionSubtractionDemo {

public static void main(String[] args) {

System.out

.println("Welcome to Java program for calculating sum and difference of two matrices");

// we need a Scanner to read input from Console

Scanner scnr = new Scanner(System.in);

System.out.print("Please Enter number of rows: ");

int rows = scnr.nextInt();

System.out.print("Please Enter number of columns: ");

int columns = scnr.nextInt();

System.out.println();

System.out.println("Please Enter first matrix");

int[][] a = read(scnr, rows, columns);

System.out.println();

System.out.println("Please Enter second matrix");

int[][] b = read(scnr, rows, columns);

scnr.close();

// adding two matrices

int[][] sum = add(a, b);

// subtracting two matrices

int[][] difference1 = subtract(a, b);

int[][] difference2 = subtract(b, a);

System.out.println("The sum of two matrices is: ");

System.out.println("A + B =");

printMatrix(sum);

System.out.println("The differnece of two matrices is: ");

System.out.println("A - B =");

printMatrix(difference1);

System.out.println("Subtraction of matrix in opposite order");

System.out.println("B - A =");

printMatrix(difference2);

scnr.close();

}

/**

* a method to populate a matrix by reading input from console in Java

*

* @param rows

* @param columns

* @return matrix filled by user input from console

*/

public static int[][] read(Scanner s, int rows, int columns) {

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

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

for (int j = 0; j < columns; j++) {

System.out.println("Enter value of [" + (i+1) + "][" + (j+1) +"]");

result[i][j] = s.nextInt();

}

}

return result;

}

/**

* Java Program to calculate sum of two matrices

*

* @param a

* @param b

* @return return sum of given matrices

*/

public static int[][] add(int[][] a, int[][] b) {

int rows = a.length;

int columns = a[0].length;

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

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

for (int j = 0; j < columns; j++) {

result[i][j] = a[i][j] + b[i][j];

}

}

return result;

}

/**

* Java Program to calculate difference of two matrices

*

* @param a

* @param b

* @return difference of given matrix

*/

public static int[][] subtract(int[][] a, int[][] b) {

int rows = a.length;

int columns = a[0].length;

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

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

for (int j = 0; j < columns; j++) {

result[i][j] = a[i][j] - b[i][j];

}

}

return result;

}

/**

* a Java method to print result in matrix format.

*

* @param matrix

*/

public static void printMatrix(int[][] matrix) {

int rows = matrix.length;

int columns = matrix[0].length;

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

for (int j = 0; j < columns; j++) {

System.out.print(matrix[i][j] + " ");

}

System.out.println();

}

}

}

Output

Welcome to Java program for calculating sum and difference of two matrices

Please Enter number of rows: 2

Please Enter number of columns: 2

Please Enter first matrix

Enter value of [1][1]

1

Enter value of [1][2]

2

Enter value of [2][1]

3

Enter value of [2][2]

4

Please Enter second matrix

Enter value of [1][1]

5

Enter value of [1][2]

6

Enter value of [2][1]

7

Enter value of [2][2]

8

The sum of two matrices is:

A + B =

6 8

10 12

The difference of two matrices is:

A - B =

-4 -4

-4 -4

Subtraction of matrix in opposite order

B - A =

4 4

4 4

You can see the sum and difference of matrices are correctly calculated as per formula we have discussed in the second paragraph. One of the important lessons I learned while doing this exercise was about Scanner class. Earlier, I was creating and closing Scanner on the read() method itself as shown below:

public static int[][] read(int rows, int columns) {

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

Scanner s = new Scanner(System.in);

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

for (int j = 0; j < columns; j++) {

System.out.println("Enter value of [" + i + "][" + j +"]");

result[i][j] = s.nextInt();

}

}

s.close();

return result;

}

When I had this code, I was getting following Exception consistently while reading second matrices from command prompt:

Exception in thread "main" java.util.NoSuchElementException

at java.util.Scanner.throwFor(Scanner.java:862)

at java.util.Scanner.next(Scanner.java:1485)

at java.util.Scanner.nextInt(Scanner.java:2117)

at java.util.Scanner.nextInt(Scanner.java:2076)

at Pattern.read(Pattern.java:66)

at Pattern.main(Pattern.java:29)

This was coming because I was closing Scanner after reading first matrices and creating another instance for reading second matrices, this all look good on code but Java doesn't allow that. Once you close the Scanner you cannot open it again for the same stream, in our case we are using System.in, which is an InputStream for reading data entered on the command prompt.

To solve this error, I am creating Scanner once in the program and supplying that to read method for reading purpose and once I read both matrices from the command line I close the Scanner in the main() method itself. Even after working in Java for so many years, I didn't know this detail. So, even a simple program can teach us some useful things.

That's all about how to add and subtract two matrices in Java. If you are interested in more programming exercises you can check out the post listed below or you can also start solving problems from the "57 Challenges to Develop Your Coding Skills", a good book with lots of programs to improve your programming skills.