How To Create Matrix In Java

Hey guys!! Welcome to flower brackets. Today we are going to learn how to create matrix in java.

We are going to set the borders of matrix equal to one and the rest equal to zero.

First thing to do is open eclipse ide and create a new class like this,

example: How To Create Matrix In Java

public class MatrixDemo
{
public static void main(String[] args)
{
int matrix[][] = new int [4][4];
matrixFunction(matrix);
}
public static void matrixFunction(int matrix[][])
{
for(int a = 0; a < 4; a++)
{
for(int b = 0; b < 4; b++)
{
if(a == 0 || b == 0 || a == 3 || b == 3)
{
matrix[a][b] = 1;
}
else
{
matrix[a][b] = 0;
}
}
}
for(int a = 0; a < 4; a++)
{
for(int b = 0; b < 4; b++)
{
System.out.print(matrix[a][b] + "    ");
}
System.out.println("    ");
}
}
}

In the above example I have created an array called “matrix” of type integer.

Matrix array is of four rows and four columns and that’s the size of the array.

Then I have created method matrixFunction and this will take in the array that we just created.

In matrixFunction method I need two for loops. Because it’s two dimensional.

Inside second for loop I have created an if statement which will basically tell you the border conditions.

Also Read – Matrix Multiplication In Java

Because I want to make the borders of array equal to one. Else I want to make those cells equal to zero.

Outside for loop we are going to create two more for loops to print the array with little space between each number.

Finally I have called matrixFunction in the main method and if I run this program you can see like this,

How To Create Matrix In Java


conclusion:

That’s it guys. This is all about how to create matrix in java. I hope you have enjoyed this post.

You can subscribe to my blog flower brackets if you haven’t already. If you found this post useful share it across social networks.

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *