Q:

# Java program to find addition and subtraction of two matrices

### 1) Java program to find addition of two matrices

``````class AddMatrixClass{
public static void main(String args[]){
/*initialize two matrices*/
int m1[][]={{1,1,1},{2,2,2},{3,3,3}};
int m2[][]={{4,4,4},{5,5,5},{6,6,6}};

/*creating third matrix to store
the sum of m1 and m2 matrices */
int m3[][]=new int[3][3];

for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
m3[i][j]=m1[i][j]+m2[i][j];
System.out.print(m3[i][j]+" ");
}
System.out.println();
}
}
}``````

Output

```D:\Java Articles>java AddMatrixClass
5 5 5
7 7 7
9 9 9
```

### 2) Java program to find subtraction of two matrices

``````class SubstractMatrixClass{
public static void main(String args[]){
/*initialize two matrices*/
int m1[][]={{1,1,1},{2,2,2},{3,3,3}};
int m2[][]={{4,4,4},{5,5,5},{6,6,6}};

/*creating third matrix to store
the substraction of m1 and m2 matrices */
int m3[][]=new int[3][3];

/* substract and print substraction of m1 and m2 matrices */
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
m3[i][j]=m1[i][j]-m2[i][j];
System.out.print(m3[i][j]+" ");
}
System.out.println();
}
}
}``````

Output

```D:\Java Articles>java SubstractMatrixClass
-3 -3 -3
-3 -3 -3
-3 -3 -3
```