Java Random.nextFloat() – Examples

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

nextFloat()

Random.nextFloat() Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator’s sequence.

Syntax

The syntax of nextFloat() method is

</>
Copy
Random.nextFloat()

Returns

The method returns float value.

Example 1 – nextFloat()

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

Java Program

</>
Copy
import java.util.Random;

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

Output

Next random float value is : 0.9188673

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

Example 2 – nextFloat()

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

Java Program

</>
Copy
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.nextFloat());
    	}
    }
}

Output

0.8639638
0.66208106
0.4340796
0.9752728
0.53266764
0.9154337
0.6277326
0.58716
0.27133715
0.21813577

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

Conclusion

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