# Java Random Number Generator

The Java random function is one of the Java Math Library functions used to generate and return the Pseudo-random numbers between Zero and One. The basic syntax of the Math random in Java Programming language is as shown below.

```static double random(); //Return Type is Double

// In order to use in program:
Math.random();```

## Java Random Number Generator example

The Java Math.random Function returns the Pseudo-random numbers between 0 to 1. In this Java program, We are going to generate the random numbers in Java, and display the output.

```// Java Random Number Generator (Math.random) example

package MathFunctions;

public class RandomMethod {
public static void main(String[] args) {

System.out.println("\nRandom Number is = " + Math.random());
System.out.println("\nRandom Numbers is = " + Math.random());

System.out.println("\nRandom Numbers is = " + Math.random());
System.out.println("\nRandom Numbers is = " + Math.random());
}
}```

The value generated by the Java random function is from 0 (included) and less than 1. If you observe the below output, We called the Java Math.random Function four times, and it is returning four different (random) values.

``````Random Number is = 0.03922519673249125

Random Numbers is = 0.6550200808825295

Random Numbers is = 0.9178026557745128

Random Numbers is = 0.8929566570868191``````

### Java Random Number Generator example 2

In this Java program, we will show how to store random values into an array. Here, we are going to declare an array of double types and fill that array with random valued generated by Java Math.random.

```package MathFunctions;

public class RandomMethodInArray {
public static void main(String[] args) {

double [] myArray = new double;

for (int i = 0; i < 10; i++) {
myArray[i] = Math.random();
}
//Displaying Result
for (int i = 0; i < myArray.length; i++) {
System.out.println("Array Element = " + myArray[i]);
}
}
}```

First, We declared an empty double Array.

`double [] myArray = new double;`

Next, We used the Java For Loop to iterate the Array. Within the For Loop, we initialized the i value as 0. Next, the compiler will check for the condition (i < 10).

`for (int i = 0; i < 10; i++) {`

The following Java Random statements will store the random values into an array. If you observe the code snippet, we are assigning each index position with one random value. Here, the compiler will call the random Math function (static double random() ) to return a random value between 0 and 1.

`myArray[i] = Math.random();`

Next, to display the array values We used another Java For Loop to iterate the Array. Within the For Loop, we initialized i value as 0, and the compiler will check the condition (i < myArray.length). The myArray.length finds the length of an array

`for (int i = 0; i < myArray.length; i++) {`

The following Java statements prints the output.

`System.out.println("Array Element = " + myArray[i]);`