Java Math.random Method

Java Math.random() Method is a random number generating method that returns a double value between 0 and 1.

Java Math.random Method

Math.random() function has no parameters and output is always a random number between 0 and 1.

Example 1: Generate 1000 random numbers with Math.random() function and for loop. Find the minimum and maximum values among these random numbers.

double max=0;
double min=1;

for (int i=1; i<=1000; i++)
{
double rand = Math.random();

if (rand > max)
max = rand;

if (rand < min)
min=rand;
}

System.out.println("Largest value: " + max); //0.9996603080869569
System.out.println("Smallest value: " + min); //0.0019330715654811703

Example 2: Generate a random number between 1 and 10 using Math.random() method

int num = (int)(Math.random() * 10) +1;

Example 3: Generate 20 random numbers between -5 and +5 (generating positive and negative numbers)

for (int i=1; i<=20; i++)
{
int num=(int)(Math.random()*11) - 5;
System.out.print(num+" ");
//-5 -1 3 1 0 -3 4 -2 2 1 -1 4 -3 -2 5 -4 -1 -5 4 5
}