Generate random matrix in Java

Hello, In this tutorial I am here to explain how to generate a random matrix in Java. In java, we can generate a random matrix using Random class. Now I will be explaining how to generate a simple matrix using random class in Java.

How to generate random matrix in Java?

In order to generate random matrix of integers in Java, we use the nextInt() method which belongs to the java.util.Random class, and this method returns the next random integer value from the random generator sequence.

What is a random class and how to implement it

The Random class generates a series of random numbers. These are also called random numbers because they are uniformly distributed sequences which are unpredictable to the user.

import java.util.Random;
public class Main
{
  public static void main(String[] args) {
    
  Random r=new Random();
  int[][] a=new int[4][4];
  for(int i=0;i<4;i++)
  {
      for(int j=0;j<4;j++)
      {
         a[i][j]=r.nextInt(20);
         System.out.print(a[i][j]+"\t");
      }
  
     System.out.print("\n");
  }
  
    }
}

Output:

7   19  0  18

19  2   3   15

6    4   5   16

4    14  9   12

Here in the above code, first we initialize a Random object. In order to generate a random matrix here, use a method called “nextInt( )” which generates a random integer and even send a limit as a parameter. And the return type of this method is an integer. The method used here is “int nextInt(int n)”, this returns the next int random number within a range of zero to n. Likewise, use different methods to generate float , double , long using “double nextDouble( )”, “float nextFloat( )”, “long nextLong( )” respectively.

And also the output may not be the same for all, it varies since the generation of random numbers is not similar in all cases. Hope you understood now how to generate a random matrix using random class and its methods.

Also read:

Leave a Reply

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