math.random Java


JavaViews 3716

The math.random function in java is used for random number generation. This unique number is of type Double which is greater than 0.0 and less than 1.0. Each time this method returns a new random number when it is called. We can use this method to generate random unique passwords, cookie sessions, etc.

Math.Random() Syntax

public static double random()

Package to Import

import java.math.*;

Example java program to generate a random number using math.random

The below Java program generates a unique random number for every iteration using math.random function. In order to generate multiple random numbers each time, we can use for loop. By default, random method returns a value of type Double.

import java.math.*;

public class Democlass
{
  public static void main(String[] args)
  {  
    for(int i=1;i<=2;i++)
    {
      Double a = Math.random();
      System.out.println("Random number " + i + ": " + a);
    }
  }
}

Output:
Random number 1: 0.48659120461375693
Random number 2: 0.9105621631031819

Example: To generate a random number in a specific range using math.random

We can also use java math.random method to generate a random number within a specific range. In order to achieve this, we need to multiply the return value of the random() method with the maximum range.

In the below example, we have specified the maximum range as 10. Hence, for every iteration, math.random method will return a unique number between 0 and 10. To retrieve a random integer, we need to typecast the return value of the random() method to int.

import java.math.*;

public class Democlass {

  public static void main(String[] args) {
    int max = 10;
    for(int i=1;i<=4;i++)
    {		
      int c = (int)(Math.random()*max);
      System.out.println(c);
    }	
  }
}
Output:
3
6
2
0

Example: To find minimum of 2 random numbers

In the below java example, we generate two different random numbers using java math.random method and saves in 2 variables. We then compare both integers to check which number is minimum.

public class Randomnum {

  public static void main(String[] args) {
    int max = 20;
    int a = (int)(Math.random()*max);
    int b = (int)(Math.random()*max);
    System.out.println("a value is " + a);
    System.out.println("b value is " + b);
    if(a<b)
      System.out.println(a + " is the minimum number");
    else
      System.out.println(b + " is the minimum number");

  }

}
Output:
a value is 6
b value is 18
6 is the minimum number

Conclusion

This tutorial provides an overview of random number generation of various types using java math.random.

Reference

Translate »