Java Random.nextDouble() – Examples

In this tutorial, we will learn about the Java Random.nextDouble() method, and learn how to use this method to generate a random double value, with the help of examples.

nextDouble()

Random.nextDouble() returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator’s sequence.

ADVERTISEMENT

Syntax

The syntax of nextDouble() method is

Random.nextDouble()

Returns

The method returns double value.

Example 1 – nextDouble()

In this example, we will create an object random of Random class type. We will call nextDouble() on this Random object to get the next random double value. We shall print it to console.

Java Program

import java.util.Random;

public class Example{ 
    public static void main(String[] args) {
    	Random random = new Random();
    	double d = random.nextDouble();
    	System.out.println("Next random double value is : " + d);
    }
}

Output

Next random double value is : 0.2885113742924815

Output may vary, since the double value is generated randomly.

Example 2 – nextDouble()

In this example, we will generate random doubles in a for loop using nextDouble().

Java Program

import java.util.Random;

public class Example{ 
    public static void main(String[] args) {
    	Random random = new Random();
    	for (int i=0; i < 10; i++) {
    		System.out.println(random.nextDouble());
    	}
    }
}

Output

0.39925314723917926
0.3335576556279948
0.3458282757229312
0.07637435956643601
0.6502527977545927
0.37860105643550246
0.6067509406709645
0.5426131225702902
0.31321249578451216
0.43871946621568725

Output may vary, since the double values are generated randomly.

Conclusion

In this Java Tutorial, we have learnt the syntax of Java Random.nextDouble() method, and also learnt how to use this method with the help of examples.