Java Program to add two matrices

We can add two matrices in java using binary + operator. A matrix is also known as array of arrays. We can add, subtract and multiply matrices.

Add two matrices in Java

To subtract two matrices, use – operator. Let’s see a simple example to add two matrices of 3 rows and 3 columns.

  1. public class MatrixAdditionExample{  
  2. public static void main(String args[]){  
  3. //creating two matrices    
  4. int a[][]={{1,3,4},{2,4,3},{3,4,5}};    
  5. int b[][]={{1,3,4},{2,4,3},{1,2,4}};    
  6.     
  7. //creating another matrix to store the sum of two matrices    
  8. int c[][]=new int[3][3];  //3 rows and 3 columns  
  9.     
  10. //adding and printing addition of 2 matrices    
  11. for(int i=0;i<3;i++){    
  12. for(int j=0;j<3;j++){    
  13. c[i][j]=a[i][j]+b[i][j];    //use – for subtraction  
  14. System.out.print(c[i][j]+” “);    
  15. }    
  16. System.out.println();//new line    
  17. }    
  18. }}  

Output:

2 6 8
4 8 6
4 6 9

Leave a Comment